diff --git a/CMakeLists.txt b/CMakeLists.txt index a4395bfcf..1acc808b9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,7 +34,7 @@ if (WIN32) else () # so that sparkd looks for libspark.so in its directory set (CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) - set (CMAKE_INSTALL_RPATH ".") + set (CMAKE_INSTALL_RPATH ".:./lib") set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} \ -fPIC -Wall -pedantic -Wextra -Werror \ @@ -57,6 +57,8 @@ else () COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/src/lib/libspark.so ${CMAKE_BINARY_DIR}/server COMMAND mkdir ARGS -p ${CMAKE_BINARY_DIR}/server/plugins COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/sdk/examples/order_plugin_example.so ${CMAKE_BINARY_DIR}/server/plugins/ + COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/sdk/examples/ai_order_plugin_example.so ${CMAKE_BINARY_DIR}/server/plugins/ + COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/sdk/torch/lib ${CMAKE_BINARY_DIR}/server/lib COMMENT "Creating server runtime layout" DEPENDS sparkd data_files_dir) diff --git a/externals b/externals index eb1b42a5e..9caeae176 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit eb1b42a5e8ce132e47e9219c5bd67895a57d6776 +Subproject commit 9caeae1761585cde058a4b472ffb8d934ddedccf diff --git a/src/lib/CMakeDeps.cmake b/src/lib/CMakeDeps.cmake index 506431f9a..afd768425 100644 --- a/src/lib/CMakeDeps.cmake +++ b/src/lib/CMakeDeps.cmake @@ -1 +1 @@ -set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/quickbus_cfg.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/thread_manager.cpp) \ No newline at end of file +set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/thread_manager.cpp) \ No newline at end of file diff --git a/src/lib/CMakeLists.txt b/src/lib/CMakeLists.txt index 65064d4d2..2bc9cd150 100644 --- a/src/lib/CMakeLists.txt +++ b/src/lib/CMakeLists.txt @@ -141,4 +141,4 @@ if (WIN32) include(${CMAKE_SOURCE_DIR}/tools/vs_filters.cmake) endif() - \ No newline at end of file + diff --git a/src/lib/config/text_format/text_format.cpp b/src/lib/config/text_format/text_format.cpp index 99f352cbf..36a447f9e 100755 --- a/src/lib/config/text_format/text_format.cpp +++ b/src/lib/config/text_format/text_format.cpp @@ -33,9 +33,10 @@ // Sanjay Ghemawat, Jeff Dean, and others. // Forked from LibProtobuf for BTS Config by Eric Harding on 5/29/2013 +// KD disabled warning 4146 on 12/28/2018 to upgrade to proto 3.5 #ifdef _WIN32 -#pragma warning (disable: 4273 4800 4018) +#pragma warning (disable: 4273 4800 4018 4146) #endif #ifdef __GNUC__ diff --git a/src/lib/orderman/actors/order_manager/ChildOrder.h b/src/lib/orderman/actors/order_manager/ChildOrder.h index ed506a3d2..cecd92d8e 100644 --- a/src/lib/orderman/actors/order_manager/ChildOrder.h +++ b/src/lib/orderman/actors/order_manager/ChildOrder.h @@ -11,7 +11,7 @@ namespace orderman { class ChildOrder { public: ChildOrder() - : _order(nullptr), _parent_order_services(nullptr), _active(false) {} + : _order(nullptr), _parent_order_services(nullptr), _child_order_services(nullptr), _active(false) {} ChildOrder(Order &o, OrderServices &services) : _order(&o), _parent_order_services(&services), diff --git a/src/sdk/CMakeLists.txt b/src/sdk/CMakeLists.txt index e4a38178e..bb4174201 100644 --- a/src/sdk/CMakeLists.txt +++ b/src/sdk/CMakeLists.txt @@ -12,6 +12,7 @@ add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/sdk ${CMAKE_CURRENT_SOURCE_DIR}/examples/build_examples.sh ${CMAKE_CURRENT_SOURCE_DIR}/examples/md_publisher_example.cpp ${CMAKE_CURRENT_SOURCE_DIR}/examples/order_plugin_example.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/examples/ai_order_plugin_example.cpp server_layout) add_custom_target(sdk_dir ALL DEPENDS ${CMAKE_BINARY_DIR}/sdk) diff --git a/src/sdk/examples/ai_order_plugin_example.cpp b/src/sdk/examples/ai_order_plugin_example.cpp new file mode 100644 index 000000000..a8f257de3 --- /dev/null +++ b/src/sdk/examples/ai_order_plugin_example.cpp @@ -0,0 +1,409 @@ +//the pytorch guys were kind enough to #define LOG... +#include "torch/script.h" +#undef LOG + +#include "spark/lib/logging/logging.h" +#include "spark/lib/orderman/orders/DynamicOrder.h" +#include "spark/lib/plugin/SparkServices.h" +#include "spark/lib/orderman/actors/order_manager/ChildOrder.h" +#include "spark/lib/orderman/actors/order_manager/OrderBuilder.h" +#include "spark/lib/orderman/orders/DynamicOrder.h" +#include "spark/lib/utils/PBUtils.h" +#include "lib/config/protos/system.pb.h" +#include "lib/config/config.h" + +using namespace bts::api::orderman; +using namespace bts::orderman; + + +namespace bts { +namespace order_example { + +class AILeanOrder : public DynamicOrder { + public: + AILeanOrder(); + ~AILeanOrder(); + OrderDefinition const &definition() const override; + void on_init_new(OrderDefinition const &, + const PreActivationOrderServices &) override; + void on_init_recovered(OrderRecord const &, + const PreActivationOrderServices &) override; + void on_activate(Price, Quantity, OrderServices &, + trace::CorID const&) override; + void on_update(Price, Quantity, trace::CorID const&) override; + void on_crack(trace::CorID const &) override; + void on_cancel(trace::CorID const &) override; + + private: + void report_state(); + void send_next_child_order(); + + void merge_states(OrderState const &iceberg_state, + OrderState const &child_state, OrderState *merged); + + void on_child_order_update(OrderStateUpdateEvent const &); + void transition(OrderStatus new_state, std::string const &msg); + void transition(OrderStatus new_state); + + struct ActiveChild; + struct PImpl; + std::unique_ptr me; +}; + +struct AILeanOrder::ActiveChild { + ActiveChild() {} + ChildOrder order; + api::orderman::OrderState state; + void clear() { state = api::orderman::OrderState(); } +}; + +struct AILeanOrder::PImpl { + PImpl() : services(nullptr), child() {} + + OrderServices *services; + api::orderman::OrderDefinition def; + api::orderman::OrderState state; + OrderBuilder child_builder; + ActiveChild child; + Quantity show_quantity; +}; + +AILeanOrder::AILeanOrder() : me(new PImpl()) {} +AILeanOrder::~AILeanOrder() {} +api::orderman::OrderDefinition const &AILeanOrder::definition() const { + return me->def; +} + +void AILeanOrder::on_init_new( + api::orderman::OrderDefinition const &def, + const PreActivationOrderServices &services) { + + { + // Deserialize the ScriptModule from a file using torch::jit::load(). + std::shared_ptr module = torch::jit::load(""); + bts_assert(module != nullptr); + + std::vector inputs; + inputs.push_back(torch::ones({1, 3, 224, 224})); + + // Execute the model and turn its output into a tensor. + at::Tensor output = module->forward(inputs).toTensor(); + + std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/5) << '\n'; + } + + me->def = def; + me->state.mutable_dynamic(); + + auto const &iceberg_def = def.custom_def().dynamic(); + me->show_quantity = + Quantity(iceberg_def.order_params().at("show_size").as_uint32()); + + auto child_def = def; + *child_def.mutable_custom_def() = + iceberg_def.order_params().at("child").as_order_def(); + if (me->show_quantity.value() != 0) { + me->child_builder = OrderBuilder( + key(), child_def, services, + std::max((size_t)1, (size_t)(me->show_quantity).value() / 10)); + transition(ORDER_STATUS_INACTIVE); + } else { + auto msg = fmt::format("Show quantity must be greater than 0"); + me->state.set_last_msg(msg); + transition(ORDER_STATUS_REJECTED_BY_SPARK, msg); + } +} + +void AILeanOrder::on_init_recovered( + api::orderman::OrderRecord const &rec, const PreActivationOrderServices &) { + auto const &def = rec.def(); + me->def = def; + me->state = rec.state(); + + switch (me->state.status()) { + + case ORDER_STATUS_WORKING: + case ORDER_STATUS_DISCONNECTED: { + auto msg = "System restarted with active iceberg order"; + me->state.set_last_msg(msg); + transition(ORDER_STATUS_ERROR, msg); + break; + } + // terminal states + case ORDER_STATUS_ERROR: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + break; + + case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } +} + +void AILeanOrder::on_activate(Price p, Quantity q, + OrderServices &services, + trace::CorID const &) { + bts_assert(!me->services); + me->services = &services; + me->child_builder.activate(services); + + switch (me->state.status()) { + case ORDER_STATUS_INACTIVE: + me->state.set_price(p.value()); + me->state.set_quantity(q.value()); + services.subscribe_to_child_updates( + [this](auto const &os) { this->on_child_order_update(os); }); + transition(ORDER_STATUS_WORKING); + send_next_child_order(); + break; + + // these are not possible since the on_init_recovered code + // would have transitioned us to error already + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_DISCONNECTED: { + bts_assert(false); + break; + } + // terminal states + case ORDER_STATUS_ERROR: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + break; + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + report_state(); +} + +void AILeanOrder::on_update(Price p, Quantity q, trace::CorID const &) { + switch (me->state.status()) { + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + LOG(Plugin, Info, + "Updating DynamicIceberg order {} to price {} quantity {}", + key().value(), p.value(), q.value()); + me->state.set_price(p.value()); + me->state.set_quantity(q.value()); + break; + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + case ORDER_STATUS_ERROR: + transition(me->state.status(), "Cannot update order"); + break; + + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + report_state(); +} + +void AILeanOrder::on_crack(trace::CorID const &) {} + +void AILeanOrder::on_cancel(trace::CorID const &) { + switch (me->state.status()) { + case ORDER_STATUS_WORKING: + LOG(Plugin, Info, "Canceling DynamicIceberg Order {}", key().value()); + me->child.order.cancel(); + transition(ORDER_STATUS_CANCELED); + break; + case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_COMPLETED: + case ORDER_STATUS_CANCELED: + case ORDER_STATUS_ERROR: + transition(me->state.status(), "Cannot cancel order"); + break; + + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + report_state(); +} + +void AILeanOrder::report_state() { + if (me->child.state.filled_quantity()) { + api::orderman::OrderState merged_state; + merge_states(me->state, me->child.state, &merged_state); + me->services->report_state(merged_state); + } else + me->services->report_state(me->state); +} + +void AILeanOrder::merge_states( + api::orderman::OrderState const &iceberg_state, + api::orderman::OrderState const &child_state, + api::orderman::OrderState *merged) { + auto child_order_fills = child_state.filled_quantity(); + auto child_order_avg_price = child_state.avg_price(); + auto child_order_last_price = child_state.last_price(); + + auto iceberg_fills = iceberg_state.filled_quantity(); + auto iceberg_avg_price = iceberg_state.avg_price(); + + *merged = iceberg_state; + merged->set_filled_quantity(child_order_fills + iceberg_fills); + merged->set_last_price(child_order_last_price); + merged->set_avg_price((child_order_fills * child_order_avg_price + + iceberg_fills * iceberg_avg_price) / + (child_order_fills + iceberg_fills)); +} + +void AILeanOrder::send_next_child_order() { + bts_assert(me->state.quantity() > me->state.filled_quantity()); + + auto remaining = me->state.quantity() - me->state.filled_quantity(); + auto to_send = std::min(remaining, me->show_quantity.value()); + me->child.order = me->child_builder.build(); + LOG(Plugin, Info, + "DynamicIceberg order {} creating new child order {} with size " + "{} price {}. Filled {} so far out of {}", + key().value(), me->child.order.key().value(), to_send, me->state.price(), + me->state.filled_quantity(), me->state.quantity()); + + me->child.order.activate(Price(me->state.price()), Quantity(to_send)); +} + +void AILeanOrder::on_child_order_update( + OrderStateUpdateEvent const &ev) { + switch (me->state.status()) { + case ORDER_STATUS_WORKING: + if (ev.key == me->child.order.key()) { + me->child.state = ev.rebuild_state(); + + switch (me->child.state.status()) { + + case ORDER_STATUS_WORKING: + case ORDER_STATUS_PENDING_WORKING: + // nothing to do but report new state + break; + + case ORDER_STATUS_COMPLETED: { + api::orderman::OrderState merged_state; + merge_states(me->state, me->child.state, &merged_state); + me->state = merged_state; + me->child.clear(); + if (me->state.quantity() > me->state.filled_quantity()) + send_next_child_order(); + else + transition(ORDER_STATUS_COMPLETED); + break; + } + + case ORDER_STATUS_CANCELED: + LOG(Plugin, Info, + "Unexpected cancel of child {} in DynamicIceberg Order {}. " + "Canceling parent", + ev.key.value(), key().value()); + transition(ORDER_STATUS_CANCELED); + break; + + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_ERROR: + me->child.clear(); + transition(ORDER_STATUS_ERROR, "Unexpected child order state"); + break; + + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + + } else { + LOG(Plugin, Info, + "DynamicIceberg order {} received update for non active child " + "order{} . update state = {} ", + key().value(), me->child.order.key().value(), + utils::pb::to_string(ev.rebuild_state())); + } + break; + + case ORDER_STATUS_CANCELED: + case ORDER_STATUS_ERROR: + case ORDER_STATUS_DISCONNECTED: + case ORDER_STATUS_COMPLETED: + break; + + case ORDER_STATUS_PENDING_WORKING: + case ORDER_STATUS_REJECTED_BY_SPARK: + case ORDER_STATUS_INACTIVE: + case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_: + case OrderStatus_INT_MAX_SENTINEL_DO_NOT_USE_: + bts_assert(false); + break; + } + report_state(); +} + +void AILeanOrder::transition(api::orderman::OrderStatus new_status, + std::string const &msg) { + auto const &from = OrderStatus_Name(me->state.status()); + auto const &to = OrderStatus_Name(new_status); + LOG(Plugin, Info, + "Transitioning dynamic iceberg order {} from {} to {}. Msg: {}", + key().value(), from, to, msg); + me->state.set_last_msg(msg); + me->state.set_status(new_status); +} + +void AILeanOrder::transition(api::orderman::OrderStatus new_status) { + auto const &from = OrderStatus_Name(me->state.status()); + auto const &to = OrderStatus_Name(new_status); + LOG(OrderMan, Info, "Transitioning dynamic iceberg order {} from {} to {}", + key().value(), from, to); + me->state.set_status(new_status); +} + + +} // namespace order_example +} // namespace bts + +DynamicOrderDescriptor get_order_desc() +{ + DynamicOrderDescriptor desc; + + // order type name + desc.set_dynamic_order_type("AILeanOrder"); + + // show size + auto param = desc.add_param_desc(); + param->set_param_name("show_size"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_UINT); + + // child order + param = desc.add_param_desc(); + param->set_param_name("child"); + param->mutable_param_type()->set_primitive(DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF); + + return desc; +} + +extern "C" void init_spark_plugin(bts::SparkServices &serv) { + using namespace bts; + + if (config::get().type() == "dev") { + serv.register_dynamic_order(get_order_desc(), + []() { return std::make_unique(); }); + LOG(Plugin,Info, "Initialized ai_order_plugin_example.so"); + } +} diff --git a/src/sdk/examples/build_examples.sh b/src/sdk/examples/build_examples.sh index dc95d9732..7067e14a9 100755 --- a/src/sdk/examples/build_examples.sh +++ b/src/sdk/examples/build_examples.sh @@ -12,10 +12,32 @@ g++ -isystem ../externals/include \ -llttng-ust \ -ldl + + +if [ -d "./../../../../../torch/" ]; then + +g++ -isystem ../externals/include \ + -I ../include \ + -I ../include/spark \ + -I ../torch/include \ + -std=c++1z \ + -fPIC \ + -g \ + -shared \ + -o ai_order_plugin_example.so \ + ai_order_plugin_example.cpp \ + -Wl,-rpath,.. \ + -Wl,-rpath,./lib \ + -Wl,-rpath,../lib \ + -L ../lib \ + -l spark \ + -L ../torch/lib \ + -l torch +else + g++ -isystem ../externals/include \ -I ../include \ -I ../include/spark \ - -I ../include/mlpack \ -std=c++1z \ -fPIC \ -g \ @@ -23,8 +45,7 @@ g++ -isystem ../externals/include \ -o order_plugin_example.so \ order_plugin_example.cpp \ -Wl,-rpath,.. \ - -L ../lib \ - -l spark \ - -L ../mlpack/lib \ - -l mlpack \ - -fopenmp + -L ../lib \ + -l spark + +fi diff --git a/src/sdk/examples/order_plugin_example.cpp b/src/sdk/examples/order_plugin_example.cpp index 11d3a079c..5aa0910e1 100644 --- a/src/sdk/examples/order_plugin_example.cpp +++ b/src/sdk/examples/order_plugin_example.cpp @@ -11,21 +11,6 @@ using namespace bts::api::orderman; using namespace bts::orderman; - -#include "mlpack/core.hpp" -#include "mlpack/methods/random_forest/random_forest.hpp" -#include "mlpack/methods/decision_tree/random_dimension_select.hpp" -#include "mlpack/core/cv/k_fold_cv.hpp" -#include "mlpack/core/cv/metrics/accuracy.hpp" -#include "mlpack/core/cv/metrics/precision.hpp" -#include "mlpack/core/cv/metrics/recall.hpp" -//#include "mlpack/core/cv/metrics/F1.hpp" - -using namespace arma; -using namespace mlpack; -using namespace mlpack::tree; -using namespace mlpack::cv; - namespace bts { namespace order_example { @@ -87,27 +72,6 @@ api::orderman::OrderDefinition const &DynamicIcebergOrder::definition() const { void DynamicIcebergOrder::on_init_new( api::orderman::OrderDefinition const &def, const PreActivationOrderServices &services) { - - { - mat dataset; - - mlpack::data::Load("data/german.csv", dataset); - - Row labels; - labels = conv_to>::from(dataset.row(dataset.n_rows - 1)); - dataset.shed_row(dataset.n_rows - 1); - const size_t numClasses = 2; - const size_t minimumLeafSize = 5; - const size_t numTrees = 10; - RandomForest rf; - rf = RandomForest(dataset, labels, - numClasses, numTrees, minimumLeafSize); - - Row predictions; - rf.Classify(dataset, predictions); - const size_t correct = arma::accu(predictions == labels); - cout << "\nTraining Accuracy: " << (double(correct) / double(labels.n_elem)); - } me->def = def; me->state.mutable_dynamic(); diff --git a/src/sdk/make_sdk.sh b/src/sdk/make_sdk.sh index 837865450..2a87e408f 100755 --- a/src/sdk/make_sdk.sh +++ b/src/sdk/make_sdk.sh @@ -26,11 +26,12 @@ ln -sf $1/server $1/sdk/lib mkdir $1/sdk/examples cp $2/examples/* $1/sdk/examples -ln -sf $2/mlpack $1/sdk/mlpack -ln -sf $2/mlpack/include $1/sdk/include/mlpack -#mkdir $1/sdk/mlpack -#cp -r $2/mlpack/* $1/sdk/mlpack -#cp -r $2/mlpack/include/* $1/sdk/include +#torch is outside the spark repo, I didn't want to force a subrepo just yet +if [ -d "$2/../../../torch/" ]; then + mkdir -p $1/sdk/torch/ + ln -sf $2/../../../torch/linux/include $1/sdk/torch/include + ln -sf $2/../../../torch/linux/lib $1/sdk/torch/lib +fi cp $2/sdk_shell.sh $1/sdk/sdk_shell.sh cp $2/update_github.sh $1/sdk/update_github.sh diff --git a/src/sdk/mlpack/bin/generate_pyx_adaboost b/src/sdk/mlpack/bin/generate_pyx_adaboost deleted file mode 100644 index 78be397ee..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_adaboost and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_approx_kfn b/src/sdk/mlpack/bin/generate_pyx_approx_kfn deleted file mode 100644 index f7eaccabe..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_approx_kfn and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_cf b/src/sdk/mlpack/bin/generate_pyx_cf deleted file mode 100644 index 7768254d9..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_cf and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_dbscan b/src/sdk/mlpack/bin/generate_pyx_dbscan deleted file mode 100644 index f2d766fe1..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_dbscan and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_decision_stump b/src/sdk/mlpack/bin/generate_pyx_decision_stump deleted file mode 100644 index c2f0fb2bd..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_decision_stump and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_decision_tree b/src/sdk/mlpack/bin/generate_pyx_decision_tree deleted file mode 100644 index 50460b6b5..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_decision_tree and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_det b/src/sdk/mlpack/bin/generate_pyx_det deleted file mode 100644 index 14686aa28..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_det and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_emst b/src/sdk/mlpack/bin/generate_pyx_emst deleted file mode 100644 index f79ae96e5..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_emst and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_fastmks b/src/sdk/mlpack/bin/generate_pyx_fastmks deleted file mode 100644 index 8d54d58dc..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_fastmks and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_gmm_generate b/src/sdk/mlpack/bin/generate_pyx_gmm_generate deleted file mode 100644 index 89825ab96..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_gmm_generate and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_gmm_probability b/src/sdk/mlpack/bin/generate_pyx_gmm_probability deleted file mode 100644 index 7d5d4664e..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_gmm_probability and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_gmm_train b/src/sdk/mlpack/bin/generate_pyx_gmm_train deleted file mode 100644 index c2ae962ad..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_gmm_train and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_hmm_generate b/src/sdk/mlpack/bin/generate_pyx_hmm_generate deleted file mode 100644 index e0f10dc9b..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_hmm_generate and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_hmm_loglik b/src/sdk/mlpack/bin/generate_pyx_hmm_loglik deleted file mode 100644 index 4bb3e0208..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_hmm_loglik and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_hmm_train b/src/sdk/mlpack/bin/generate_pyx_hmm_train deleted file mode 100644 index 52b4ec4e3..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_hmm_train and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_hmm_viterbi b/src/sdk/mlpack/bin/generate_pyx_hmm_viterbi deleted file mode 100644 index dd7c7c295..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_hmm_viterbi and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_hoeffding_tree b/src/sdk/mlpack/bin/generate_pyx_hoeffding_tree deleted file mode 100644 index da45aa0b3..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_hoeffding_tree and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_kernel_pca b/src/sdk/mlpack/bin/generate_pyx_kernel_pca deleted file mode 100644 index d7e616c0b..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_kernel_pca and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_kfn b/src/sdk/mlpack/bin/generate_pyx_kfn deleted file mode 100644 index 69ee40574..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_kfn and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_kmeans b/src/sdk/mlpack/bin/generate_pyx_kmeans deleted file mode 100644 index 4bca3a88a..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_kmeans and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_knn b/src/sdk/mlpack/bin/generate_pyx_knn deleted file mode 100644 index fdae27110..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_knn and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_krann b/src/sdk/mlpack/bin/generate_pyx_krann deleted file mode 100644 index a3e486d97..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_krann and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_lars b/src/sdk/mlpack/bin/generate_pyx_lars deleted file mode 100644 index 6a7e22064..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_lars and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_linear_regression b/src/sdk/mlpack/bin/generate_pyx_linear_regression deleted file mode 100644 index 5bc39716f..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_linear_regression and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_local_coordinate_coding b/src/sdk/mlpack/bin/generate_pyx_local_coordinate_coding deleted file mode 100644 index 63370a9f8..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_local_coordinate_coding and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_logistic_regression b/src/sdk/mlpack/bin/generate_pyx_logistic_regression deleted file mode 100644 index 5d5aa3eb0..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_logistic_regression and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_lsh b/src/sdk/mlpack/bin/generate_pyx_lsh deleted file mode 100644 index 3d544cb3d..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_lsh and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_mean_shift b/src/sdk/mlpack/bin/generate_pyx_mean_shift deleted file mode 100644 index 6a300666d..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_mean_shift and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_nbc b/src/sdk/mlpack/bin/generate_pyx_nbc deleted file mode 100644 index a18799ecd..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_nbc and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_nca b/src/sdk/mlpack/bin/generate_pyx_nca deleted file mode 100644 index e1f3c104b..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_nca and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_nmf b/src/sdk/mlpack/bin/generate_pyx_nmf deleted file mode 100644 index 5bdca0f65..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_nmf and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_pca b/src/sdk/mlpack/bin/generate_pyx_pca deleted file mode 100644 index b7cb67288..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_pca and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_perceptron b/src/sdk/mlpack/bin/generate_pyx_perceptron deleted file mode 100644 index 0a874778d..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_perceptron and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_preprocess_binarize b/src/sdk/mlpack/bin/generate_pyx_preprocess_binarize deleted file mode 100644 index 34ff28042..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_preprocess_binarize and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_preprocess_describe b/src/sdk/mlpack/bin/generate_pyx_preprocess_describe deleted file mode 100644 index a8a6eb93c..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_preprocess_describe and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_preprocess_split b/src/sdk/mlpack/bin/generate_pyx_preprocess_split deleted file mode 100644 index 650fc4bbf..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_preprocess_split and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_radical b/src/sdk/mlpack/bin/generate_pyx_radical deleted file mode 100644 index ca704cb86..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_radical and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_random_forest b/src/sdk/mlpack/bin/generate_pyx_random_forest deleted file mode 100644 index 094786ffe..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_random_forest and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_softmax_regression b/src/sdk/mlpack/bin/generate_pyx_softmax_regression deleted file mode 100644 index 80cf2a2b0..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_softmax_regression and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_sparse_coding b/src/sdk/mlpack/bin/generate_pyx_sparse_coding deleted file mode 100644 index 3358459e5..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_sparse_coding and /dev/null differ diff --git a/src/sdk/mlpack/bin/generate_pyx_test_python_binding b/src/sdk/mlpack/bin/generate_pyx_test_python_binding deleted file mode 100644 index dd43fc365..000000000 Binary files a/src/sdk/mlpack/bin/generate_pyx_test_python_binding and /dev/null differ diff --git a/src/sdk/mlpack/german.csv b/src/sdk/mlpack/german.csv deleted file mode 100644 index 4ee4708d8..000000000 --- a/src/sdk/mlpack/german.csv +++ /dev/null @@ -1,1000 +0,0 @@ -1,6,4,12,5,5,3,4,1,67,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,48,2,60,1,3,2,2,1,22,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,4,21,1,4,3,3,1,49,3,1,2,1,1,0,0,1,0,0,1,0,1,0 -1,42,2,79,1,4,3,4,2,45,3,1,2,1,1,0,0,0,0,0,0,0,0,1 -1,24,3,49,1,3,3,4,4,53,3,2,2,1,1,1,0,1,0,0,0,0,0,1 -4,36,2,91,5,3,3,4,4,35,3,1,2,2,1,0,0,1,0,0,0,0,1,0 -4,24,2,28,3,5,3,4,2,53,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,36,2,69,1,3,3,2,3,35,3,1,1,2,1,0,1,1,0,1,0,0,0,0 -4,12,2,31,4,4,1,4,1,61,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,30,4,52,1,1,4,2,3,28,3,2,1,1,1,1,0,1,0,0,1,0,0,0 -2,12,2,13,1,2,2,1,3,25,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -1,48,2,43,1,2,2,4,2,24,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -2,12,2,16,1,3,2,1,3,22,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,24,4,12,1,5,3,4,3,60,3,2,1,1,1,1,0,1,0,0,1,0,1,0 -1,15,2,14,1,3,2,4,3,28,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -1,24,2,13,2,3,2,2,3,32,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,24,4,24,5,5,3,4,2,53,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -1,30,0,81,5,2,3,3,3,25,1,3,1,1,1,0,0,1,0,0,1,0,0,1 -2,24,2,126,1,5,2,2,4,44,3,1,1,2,1,0,1,1,0,0,0,0,0,0 -4,24,2,34,3,5,3,2,3,31,3,1,2,2,1,0,0,1,0,0,1,0,0,1 -4,9,4,21,1,3,3,4,3,48,3,3,1,2,1,1,0,1,0,0,1,0,0,1 -1,6,2,26,3,3,3,3,1,44,3,1,2,1,1,0,0,1,0,1,0,0,0,1 -1,10,4,22,1,2,3,3,1,48,3,2,2,1,2,1,0,1,0,1,0,0,1,0 -2,12,4,18,2,2,3,4,2,44,3,1,1,1,1,0,1,1,0,0,1,0,0,1 -4,10,4,21,5,3,4,1,3,26,3,2,1,1,2,0,0,1,0,0,1,0,0,1 -1,6,2,14,1,3,3,2,1,36,1,1,1,2,1,0,0,1,0,0,1,0,1,0 -4,6,0,4,1,5,4,4,3,39,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -3,12,1,4,4,3,2,3,1,42,3,2,1,1,1,0,0,1,0,1,0,0,0,1 -2,7,2,24,1,3,3,2,1,34,3,1,1,1,1,0,0,0,0,0,1,0,0,1 -1,60,3,68,1,5,3,4,4,63,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,18,2,19,4,2,4,3,1,36,1,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,24,2,40,1,3,3,2,3,27,2,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,2,59,2,3,3,2,3,30,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -4,12,4,13,5,5,3,4,4,57,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -3,12,2,15,1,2,2,1,2,33,1,1,1,2,1,0,0,1,0,0,1,0,0,0 -2,45,4,47,1,2,3,2,2,25,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -4,48,4,61,1,3,3,3,4,31,1,1,1,2,1,0,0,1,0,0,0,0,0,1 -3,18,2,21,1,3,3,2,1,37,2,1,1,1,1,0,0,0,1,0,1,0,0,1 -3,10,2,12,1,3,3,2,3,37,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,9,2,5,1,3,3,3,1,24,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,30,2,23,3,5,3,2,3,30,1,1,1,1,1,0,0,1,0,0,1,0,0,0 -2,12,2,12,3,3,1,1,3,26,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,18,3,62,1,3,3,4,1,44,3,1,2,2,1,0,0,1,0,0,1,0,1,0 -1,30,4,62,2,4,4,4,3,24,3,2,1,1,1,0,1,1,0,1,0,0,0,1 -1,48,4,61,1,5,2,4,4,58,2,2,1,1,1,0,1,1,0,0,0,0,1,0 -4,11,4,14,1,2,2,4,3,35,3,2,1,1,1,1,0,1,0,0,1,0,0,0 -4,36,2,23,3,5,3,4,3,39,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,6,2,14,3,1,2,2,2,23,3,1,1,2,1,0,1,1,0,1,0,1,0,0 -4,11,4,72,1,3,3,4,2,39,3,2,1,1,1,1,0,1,0,0,1,0,1,0 -4,12,2,21,2,3,2,2,1,28,3,1,1,1,1,0,0,0,1,0,1,0,0,1 -2,24,3,23,5,2,3,2,2,29,1,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,27,3,60,1,5,3,2,3,30,3,2,1,2,1,0,1,1,0,0,1,0,0,0 -4,12,2,13,1,3,3,2,3,25,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,2,34,5,3,3,1,2,31,3,1,1,2,1,0,1,1,0,0,1,0,0,1 -2,36,3,22,1,5,3,4,4,57,1,2,1,2,1,1,0,1,0,0,0,0,0,1 -4,6,1,8,5,3,3,2,1,26,2,1,2,1,1,1,0,0,0,0,1,0,1,0 -2,12,2,65,5,1,3,1,4,52,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -4,36,4,96,1,3,2,2,3,31,2,2,1,1,1,0,0,1,0,0,1,0,0,1 -3,18,2,20,1,5,2,2,3,23,3,1,1,1,1,1,0,1,0,0,1,0,0,0 -1,36,4,62,1,2,2,4,4,23,3,2,1,2,1,0,0,0,1,1,0,0,1,0 -2,9,2,14,1,3,4,1,1,27,1,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,15,4,15,5,5,3,4,1,50,3,2,1,2,1,0,0,0,0,0,1,0,0,1 -2,36,0,20,1,5,3,4,4,61,3,1,1,2,1,0,0,1,0,0,0,0,0,0 -2,48,0,144,1,3,3,2,3,25,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,24,2,32,1,2,2,4,2,26,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,27,2,52,5,5,3,4,2,48,3,4,2,2,1,0,0,1,0,0,1,0,0,1 -4,12,2,22,1,2,2,2,3,29,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,12,2,10,4,3,4,1,1,22,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,36,2,18,1,3,3,4,4,37,2,1,1,2,1,0,0,1,0,0,0,0,0,1 -4,36,2,24,5,3,2,4,3,25,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,36,2,81,1,3,2,2,2,30,1,1,1,1,1,0,1,1,0,0,1,0,0,1 -4,7,4,7,5,5,3,2,2,46,3,2,1,2,1,0,0,1,0,1,0,0,1,0 -1,8,4,12,1,5,3,4,4,51,1,2,2,2,1,0,0,1,0,0,0,0,0,0 -2,42,4,60,1,4,2,1,1,41,1,2,1,1,1,0,0,1,0,0,1,0,1,0 -1,36,2,20,5,5,3,4,4,40,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -1,12,4,15,1,5,3,4,4,66,3,2,1,1,1,0,1,1,0,0,0,0,0,0 -1,42,2,40,1,2,3,3,3,34,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,11,3,48,1,4,3,4,2,51,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,54,0,94,5,3,3,2,2,39,3,1,2,1,1,0,1,1,0,0,1,0,1,0 -2,30,2,38,1,2,4,1,2,22,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,2,59,5,2,2,1,3,44,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,15,2,12,3,5,3,3,2,47,2,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,18,2,16,2,3,2,4,2,24,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -1,24,2,18,1,5,2,4,1,58,3,1,1,2,1,0,0,0,0,0,1,0,1,0 -1,10,2,23,1,5,3,4,1,52,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,12,4,14,1,3,2,2,1,29,3,2,1,2,1,0,0,0,0,0,1,0,0,0 -2,18,4,13,1,2,2,1,2,27,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,36,2,126,2,3,3,4,4,47,3,1,2,2,1,0,0,1,0,0,0,0,0,1 -1,18,2,22,2,4,3,3,3,30,3,1,2,2,1,1,0,1,0,0,1,0,0,0 -1,12,0,11,1,4,3,3,1,28,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,4,6,1,5,3,4,1,56,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,4,14,1,5,3,3,1,54,3,1,1,1,1,0,1,1,0,0,1,0,0,1 -4,12,4,8,5,5,2,3,2,33,1,1,2,1,1,0,0,1,0,0,1,0,1,0 -3,24,4,36,5,5,3,4,4,20,3,2,1,1,1,0,0,0,1,1,0,0,0,1 -2,12,2,13,4,5,3,4,1,54,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -2,54,0,159,1,2,3,4,4,58,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -4,12,4,20,5,4,2,2,3,61,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,2,26,2,3,3,4,3,34,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,36,4,23,1,5,3,4,1,36,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,20,3,71,5,4,3,4,2,36,1,2,2,2,1,0,1,1,0,1,0,0,0,0 -4,24,2,15,2,5,4,4,1,41,3,1,1,1,1,1,0,1,0,1,0,0,1,0 -2,36,2,23,1,4,3,4,3,24,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -4,6,3,9,1,3,2,2,1,24,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,9,4,19,1,4,3,3,3,35,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -4,12,2,24,5,2,4,4,3,26,3,1,1,2,1,0,1,1,0,1,0,0,0,1 -2,24,4,119,1,3,3,3,3,39,3,2,2,2,1,0,0,0,1,0,1,0,0,0 -4,18,1,65,1,5,3,4,4,39,1,2,2,2,1,1,0,1,0,0,1,0,0,0 -2,12,2,61,1,4,3,2,3,32,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -1,24,2,77,5,2,2,2,2,30,3,1,1,2,2,0,0,1,0,0,1,0,0,1 -2,14,2,14,3,5,4,2,1,35,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,6,3,14,2,5,1,2,3,31,1,2,2,1,1,0,0,1,0,0,1,0,0,1 -3,15,2,4,1,2,2,4,2,23,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -2,18,2,63,1,4,3,3,1,28,3,1,1,1,1,1,0,1,0,1,0,0,1,0 -4,36,4,79,1,3,2,2,1,25,2,2,1,2,1,1,0,1,0,0,1,0,0,1 -1,12,2,17,3,5,4,1,1,35,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,48,4,36,5,5,3,1,1,47,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,42,2,72,5,4,2,3,3,30,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -1,10,4,21,5,2,2,3,1,27,3,2,1,1,2,0,0,0,1,1,0,0,0,1 -1,33,4,43,3,3,2,4,3,23,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,12,4,24,3,4,1,3,3,36,3,1,1,2,1,1,0,1,0,0,1,0,0,0 -1,21,2,18,1,3,2,2,1,25,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,24,4,39,1,5,2,2,3,41,3,2,1,2,1,0,1,1,0,1,0,0,0,0 -4,12,2,18,1,3,3,2,1,24,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -3,10,4,8,1,5,3,4,4,63,3,2,1,2,1,1,0,1,0,0,0,0,0,1 -2,18,2,19,5,2,2,3,1,27,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,12,4,21,1,3,3,2,2,30,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -1,12,2,7,1,3,4,2,1,40,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,12,2,6,1,3,3,2,3,30,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,12,4,19,1,1,3,2,3,34,3,2,1,2,1,0,1,1,0,0,1,0,0,0 -1,12,4,35,1,3,2,2,1,29,3,2,1,1,1,1,0,0,1,0,1,0,0,1 -2,48,2,85,5,4,2,2,3,24,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -1,36,3,69,1,3,3,3,2,29,2,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,15,2,27,1,2,3,3,2,27,1,2,1,1,1,0,0,1,0,0,1,0,1,0 -4,18,2,20,1,3,3,4,4,47,1,2,1,1,1,0,0,1,0,0,0,0,0,1 -4,60,2,101,2,4,2,4,1,21,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,12,4,12,5,5,2,2,1,38,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,27,3,86,4,3,3,2,3,27,3,2,1,1,1,0,1,1,0,0,1,0,0,1 -2,12,2,8,3,3,3,3,1,66,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,15,4,27,5,4,3,2,1,35,1,3,1,2,1,0,0,0,0,0,1,0,0,1 -3,12,2,19,1,3,2,2,3,44,3,1,1,2,1,0,0,1,0,1,0,0,1,0 -3,6,2,7,4,2,4,2,1,27,3,1,1,1,2,1,0,1,0,0,1,1,0,0 -2,36,2,48,1,2,2,1,4,30,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -1,27,2,34,1,3,3,2,3,27,3,1,1,1,1,0,0,1,0,0,1,0,0,0 -1,18,2,25,1,3,3,2,3,22,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,21,4,23,1,2,2,4,2,23,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,48,1,36,2,4,3,2,3,30,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,6,4,9,1,5,2,4,4,39,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -4,12,4,7,2,4,2,3,3,51,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -1,36,4,54,1,3,3,2,2,28,3,2,1,1,1,0,0,0,0,0,1,0,0,1 -4,18,4,16,4,5,3,4,3,46,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,6,2,13,2,5,3,4,4,42,1,1,2,2,1,0,0,1,0,0,0,0,0,1 -4,10,2,19,1,3,3,4,2,38,3,1,1,2,2,0,0,1,0,0,1,0,0,1 -3,36,2,58,1,3,3,1,3,24,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,24,4,78,4,5,2,4,4,29,3,1,1,1,1,0,1,1,0,1,0,0,0,1 -2,24,3,70,2,4,3,4,3,36,3,1,1,2,1,0,0,1,0,1,0,0,0,0 -1,12,2,13,1,3,2,4,3,20,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,9,4,13,2,5,3,4,1,48,3,2,2,1,2,0,0,0,0,0,1,0,0,1 -1,12,1,3,1,5,4,1,3,45,1,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,24,2,35,2,4,3,3,3,38,1,2,1,2,1,1,0,1,0,0,1,0,0,1 -4,6,4,19,5,3,3,2,1,34,3,2,2,1,1,0,0,1,0,0,1,0,1,0 -4,24,4,29,2,5,3,4,1,36,3,1,2,2,1,0,0,1,0,0,1,0,0,1 -4,18,4,11,1,2,2,1,2,30,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,15,2,13,3,4,3,3,2,36,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,10,2,73,1,1,3,4,4,70,1,1,1,2,1,1,0,1,0,0,0,0,0,0 -4,36,2,9,3,5,3,4,2,36,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,6,2,30,3,3,3,2,3,32,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,18,2,11,1,1,2,2,3,33,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,11,2,16,4,2,2,1,1,20,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,2,40,1,4,2,4,2,25,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -2,24,4,19,1,5,1,4,1,31,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -1,15,0,10,1,5,3,3,3,33,3,2,2,1,1,1,0,1,0,1,0,0,0,1 -4,12,2,8,1,3,2,1,1,26,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,24,3,21,1,1,2,2,2,34,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -2,8,2,14,1,3,3,2,1,33,3,1,1,1,2,0,0,0,0,0,1,0,0,1 -1,21,3,34,1,2,3,1,2,26,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,30,1,75,5,1,2,1,1,53,1,1,1,2,1,0,1,1,0,0,1,0,0,0 -1,12,2,26,1,3,1,1,3,42,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,6,4,3,3,5,3,4,3,52,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,2,20,1,4,3,2,3,31,3,2,2,2,1,0,0,1,0,1,0,0,0,0 -1,21,4,6,1,5,3,4,1,65,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,36,3,96,1,2,1,1,3,28,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,36,3,45,1,3,1,2,1,30,2,2,1,2,1,0,0,1,0,0,1,0,0,0 -1,21,1,16,5,3,3,2,2,40,3,2,2,1,1,1,0,1,0,0,1,0,1,0 -4,24,4,38,4,3,3,4,1,50,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,18,4,9,1,5,3,4,3,36,1,1,2,2,1,1,0,1,0,0,1,0,0,1 -4,15,4,14,1,3,3,2,2,31,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,9,1,51,1,5,2,4,4,74,1,1,2,2,1,0,1,1,0,0,0,0,0,0 -2,16,4,12,1,1,3,3,3,68,3,3,1,2,1,1,0,1,0,0,0,1,0,0 -1,12,2,7,2,4,4,1,2,20,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,0,32,1,3,2,4,3,33,1,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,24,2,46,4,3,3,3,2,54,3,3,1,2,1,0,0,1,0,0,1,0,0,0 -2,48,0,38,2,4,3,4,4,34,3,1,2,1,1,0,0,1,0,0,0,0,1,0 -2,27,2,39,1,3,3,2,3,36,3,1,2,2,1,0,0,1,0,0,1,0,0,1 -4,6,2,21,1,4,4,2,1,29,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -2,45,2,30,2,3,3,4,2,21,3,1,1,1,1,0,0,0,0,1,0,0,0,1 -2,9,4,15,1,5,2,3,3,34,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -4,6,4,14,1,3,2,1,3,28,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,12,2,10,2,2,2,4,3,27,1,4,1,1,1,0,0,1,0,1,0,0,0,1 -2,24,2,28,5,5,3,4,4,36,1,1,1,2,1,0,1,1,0,0,0,0,0,1 -2,18,3,43,1,5,1,3,4,40,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -4,9,4,9,3,5,3,2,3,52,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -1,12,2,12,1,3,4,3,1,27,3,1,1,1,1,1,0,1,0,0,1,0,1,0 -4,27,3,51,1,4,3,4,3,26,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,2,9,1,4,4,4,2,21,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -4,12,4,15,1,5,3,1,1,38,3,2,2,1,1,1,0,1,0,0,1,0,1,0 -1,30,4,106,1,5,3,4,4,38,3,3,2,2,1,0,1,1,0,0,0,0,0,0 -4,12,4,19,1,5,3,4,1,43,3,3,1,2,1,0,0,1,0,0,1,0,0,1 -2,12,4,14,1,4,3,3,2,26,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,66,1,3,4,2,3,21,2,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,12,2,14,4,4,3,2,2,55,3,1,1,1,2,0,1,1,0,0,1,0,0,1 -4,9,4,31,5,3,3,2,1,33,3,2,2,1,1,0,0,1,0,0,1,0,0,1 -4,36,2,38,5,5,2,4,1,45,3,1,1,2,1,0,0,1,0,0,1,0,1,0 -1,27,0,53,1,1,3,4,2,50,2,2,1,2,1,0,0,1,0,0,1,0,0,1 -3,30,3,19,1,5,3,4,1,66,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -4,36,4,33,5,5,3,2,3,51,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,6,4,9,5,4,2,3,2,39,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -1,18,0,31,1,4,3,1,2,31,1,1,1,2,1,0,0,1,0,0,1,0,0,1 -3,36,2,39,1,3,3,2,1,23,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,24,2,30,1,3,1,2,1,24,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -4,10,2,14,1,3,2,4,3,64,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -2,12,2,6,1,2,4,1,1,26,1,1,1,1,1,0,0,0,0,0,1,0,1,0 -1,12,2,12,5,3,2,4,2,23,1,1,1,2,1,0,0,1,0,1,0,0,0,1 -4,12,2,7,1,3,3,2,1,30,1,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,3,30,5,3,3,4,1,32,3,2,2,2,1,0,0,1,0,0,1,0,0,1 -4,15,2,47,1,3,3,2,3,30,3,1,1,2,1,0,1,1,0,0,1,0,0,1 -4,36,0,26,1,3,3,2,3,27,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,48,2,110,4,4,3,2,4,27,1,2,1,2,1,0,0,0,1,0,1,0,0,1 -1,12,2,79,1,5,3,4,4,53,3,1,1,2,1,0,0,1,0,0,0,0,0,0 -4,9,2,15,1,4,3,2,3,22,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,31,1,2,3,1,4,22,1,1,1,1,1,0,0,1,0,0,0,0,0,1 -3,36,2,42,1,3,3,2,3,26,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,9,2,25,3,5,3,4,4,51,3,1,1,1,1,1,0,1,0,0,0,0,1,0 -4,12,2,21,2,4,3,1,4,35,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,2,9,1,3,4,2,1,25,3,1,1,1,1,0,0,0,0,0,1,0,1,0 -4,4,4,15,1,4,3,1,1,42,3,3,2,1,1,0,0,1,0,0,1,0,1,0 -1,24,2,18,1,1,3,2,3,30,2,1,2,1,1,0,0,1,0,0,1,0,0,0 -2,6,2,146,5,1,3,2,2,23,3,1,1,2,1,1,0,1,0,0,1,1,0,0 -2,21,2,28,2,5,1,2,3,61,1,2,1,1,1,0,0,1,0,1,0,0,1,0 -4,12,4,13,1,3,2,2,2,35,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -1,30,2,25,1,5,3,3,2,39,3,1,2,1,1,0,0,0,0,0,1,0,0,1 -1,24,2,9,5,5,2,2,3,29,1,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,6,2,16,1,4,3,2,2,51,3,1,2,1,1,0,0,1,0,0,1,0,0,1 -1,48,0,46,1,5,3,4,4,24,3,2,2,1,1,0,1,1,0,0,0,0,0,1 -4,12,4,12,1,3,2,2,1,27,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,1,34,3,3,2,3,1,35,3,1,2,1,1,0,0,1,0,0,1,0,1,0 -4,24,2,13,1,4,3,1,1,25,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,12,4,7,1,5,3,4,1,52,3,3,1,1,1,0,0,1,0,0,1,0,0,1 -4,6,0,12,2,3,3,1,4,35,1,1,1,1,2,1,0,1,0,1,0,0,0,1 -3,24,2,19,1,3,3,2,1,26,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,2,4,1,1,2,4,1,22,3,1,1,1,1,0,0,0,1,1,0,0,0,1 -1,6,4,7,4,4,2,4,1,39,3,2,1,2,1,1,0,1,0,0,1,0,1,0 -3,12,2,23,1,3,2,2,3,46,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,30,2,22,1,3,2,2,4,24,1,1,1,1,1,1,0,0,0,0,1,0,0,1 -4,24,3,42,2,3,3,3,2,35,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,9,2,20,5,4,3,1,3,24,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,60,3,74,5,3,3,1,1,27,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,24,4,27,1,3,3,2,1,35,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -1,12,1,21,1,3,1,1,4,29,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -4,15,2,38,2,2,2,4,3,23,3,1,1,2,1,0,1,1,0,0,1,0,0,1 -4,11,4,12,2,1,2,4,1,57,3,3,1,1,1,0,0,1,0,0,1,0,1,0 -1,12,2,17,1,3,3,2,1,27,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,16,1,5,2,4,3,55,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,18,4,53,1,5,3,4,4,36,3,3,1,2,1,1,0,1,0,0,0,0,0,0 -4,12,4,27,1,5,2,4,4,57,1,3,1,1,1,0,0,1,0,0,0,0,1,0 -4,10,4,12,1,5,3,4,1,32,3,2,2,1,2,1,0,1,0,0,1,0,1,0 -2,15,2,8,1,5,3,3,3,37,3,1,2,1,1,0,0,1,0,0,1,0,0,1 -4,36,4,63,5,5,3,4,1,36,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,2,15,1,2,2,3,3,38,2,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,14,2,90,1,5,1,4,2,45,3,1,1,2,2,1,0,1,0,0,1,0,0,0 -4,24,2,10,5,5,3,2,3,25,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,2,27,5,4,3,3,2,32,3,1,1,1,2,1,0,1,0,0,1,0,0,1 -4,12,4,14,3,4,2,4,3,37,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -2,48,1,122,5,1,3,4,4,36,3,1,1,2,1,1,0,0,1,0,0,0,0,0 -2,48,2,31,1,4,3,4,1,28,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -1,30,2,120,1,2,1,1,4,34,3,1,1,2,1,0,0,1,0,0,1,0,1,0 -4,9,2,27,1,3,3,2,1,32,3,1,2,1,1,0,0,1,0,0,1,0,0,1 -4,18,4,24,1,3,2,2,3,26,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,2,13,5,5,1,4,2,49,3,1,1,2,1,0,0,1,0,0,1,0,1,0 -4,6,2,46,1,2,2,4,2,32,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,2,19,2,3,3,4,3,29,3,1,1,2,1,0,0,1,0,1,0,0,0,0 -4,15,4,34,4,5,3,4,4,23,3,2,1,2,1,0,1,1,0,1,0,0,0,1 -4,12,2,16,1,3,3,2,1,50,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -3,18,1,14,5,4,3,4,3,49,1,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,15,4,15,5,5,3,4,2,63,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,24,4,39,2,2,1,2,3,37,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -1,47,2,107,1,2,2,1,1,35,3,1,1,2,1,1,0,1,0,0,1,0,1,0 -1,48,2,48,1,4,3,3,2,26,3,1,2,1,1,0,1,1,0,0,1,0,0,1 -2,48,3,76,2,1,3,4,4,31,3,1,1,2,1,0,0,1,0,0,0,0,0,0 -2,12,2,11,1,3,2,4,1,49,3,2,1,2,1,0,0,0,0,0,1,0,0,1 -1,24,3,10,1,2,4,4,1,48,2,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,2,11,1,3,4,2,1,26,3,1,1,2,2,0,0,1,0,0,1,0,0,1 -2,36,2,94,1,2,4,4,3,28,3,1,1,2,1,0,1,1,0,1,0,0,0,0 -1,24,4,64,1,5,2,4,4,44,3,2,2,2,1,0,1,1,0,0,0,0,0,0 -3,42,4,48,1,5,3,4,4,56,3,1,1,1,1,0,1,1,0,0,0,0,0,1 -4,48,4,76,5,5,1,2,3,46,1,2,2,1,1,0,0,1,0,0,1,0,0,0 -2,48,2,100,1,2,2,2,3,26,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,12,2,47,5,2,2,4,3,20,3,1,1,1,1,0,1,1,0,1,0,0,0,1 -4,10,2,13,5,5,3,2,2,45,3,1,1,1,2,1,0,0,1,0,1,0,1,0 -4,18,2,25,1,3,3,4,1,43,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,21,4,27,4,4,3,2,3,32,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,6,2,7,1,1,2,4,1,54,3,1,1,2,1,1,0,1,0,0,1,1,0,0 -2,36,0,38,1,3,2,1,3,42,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -3,24,4,13,5,4,3,2,1,37,1,2,2,1,1,1,0,1,0,0,1,0,1,0 -1,10,4,10,1,4,3,3,2,49,3,2,1,2,1,1,0,0,1,0,1,0,0,1 -4,48,4,101,3,3,3,2,4,44,1,1,1,1,1,1,0,1,0,0,0,0,0,1 -4,6,2,15,4,3,1,2,1,33,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,30,2,48,5,4,2,4,2,24,2,1,1,1,1,0,1,1,0,1,0,0,1,0 -1,12,2,7,2,2,4,3,4,33,3,1,1,2,1,0,0,1,0,0,1,0,1,0 -2,8,2,12,1,3,2,4,1,24,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,9,2,3,1,3,4,4,1,22,3,1,1,1,1,1,0,1,0,1,0,0,1,0 -2,48,2,54,5,1,3,4,4,40,1,1,1,2,1,0,0,1,0,0,0,1,0,0 -4,24,2,55,2,3,3,1,3,25,2,1,1,1,1,0,0,1,0,0,1,0,0,1 -3,24,2,37,1,2,2,4,3,26,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,12,2,7,1,4,4,3,3,25,1,1,1,1,1,1,0,1,0,0,1,0,1,0 -3,4,2,15,5,2,3,2,1,29,3,1,2,1,2,1,0,1,0,0,1,0,1,0 -1,36,1,27,1,5,3,4,3,31,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,2,7,1,3,3,3,2,38,3,1,2,1,1,0,0,0,0,0,1,0,1,0 -2,24,2,44,5,3,2,4,2,48,3,1,1,2,1,0,0,1,0,0,1,0,1,0 -4,12,4,7,1,3,3,2,3,32,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -1,15,3,36,1,5,2,4,2,27,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -2,30,4,42,1,1,4,2,3,28,3,2,1,1,1,1,0,1,0,0,1,0,0,0 -1,24,2,19,1,2,1,3,2,32,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,29,1,4,3,1,4,34,3,1,1,2,1,0,1,1,0,0,0,0,0,0 -1,18,2,27,4,3,3,2,3,28,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,4,10,1,3,2,3,1,36,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -1,8,4,34,1,4,3,4,1,39,3,2,1,1,2,1,0,1,0,0,1,0,1,0 -4,12,4,58,5,5,3,4,2,49,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -4,24,2,15,4,4,2,3,3,34,3,1,2,2,1,1,0,1,0,0,1,0,0,1 -3,36,2,45,1,5,3,2,3,31,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,6,2,11,1,5,3,4,3,28,3,1,2,1,1,0,0,1,0,0,1,0,0,1 -1,24,4,66,1,1,3,4,4,75,3,2,1,2,1,0,1,1,0,0,0,0,0,0 -4,18,4,19,2,3,2,2,1,30,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,60,2,74,2,2,2,2,2,24,3,1,1,1,1,1,0,1,0,0,1,0,0,0 -4,48,4,116,2,3,2,4,3,24,1,2,1,1,1,0,1,1,0,1,0,0,1,0 -1,24,0,41,1,5,3,4,4,23,1,2,2,1,1,0,0,1,0,1,0,0,0,1 -1,6,4,34,1,3,1,4,1,44,3,1,1,2,1,0,0,1,0,1,0,0,0,0 -2,13,2,21,1,2,2,4,2,23,3,1,1,1,1,0,0,0,0,0,1,0,1,0 -1,15,2,13,5,3,2,2,3,24,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,24,2,42,1,3,3,4,2,28,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,10,2,15,1,3,1,2,3,31,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,24,4,57,1,2,2,4,4,24,3,2,1,2,1,0,0,1,0,0,0,0,0,1 -1,21,2,36,1,4,2,4,3,26,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -2,18,2,32,3,2,4,3,1,25,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -2,18,2,44,1,5,3,1,1,33,1,1,1,2,1,0,0,0,1,0,1,0,0,0 -3,10,2,39,1,2,3,1,2,37,3,1,2,1,1,1,0,0,0,0,1,0,1,0 -4,15,4,15,1,3,2,2,3,43,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,13,4,9,1,2,3,4,1,23,3,2,1,1,1,0,0,0,0,0,1,0,0,1 -2,24,2,38,3,1,2,4,4,23,3,1,1,1,1,0,0,1,0,1,0,1,0,0 -4,6,3,17,2,3,3,2,1,34,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -2,9,4,11,4,5,3,3,4,32,3,2,2,1,1,0,0,1,0,0,0,0,0,1 -4,9,2,12,1,2,2,4,1,23,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -2,9,2,10,1,3,2,2,3,29,3,1,1,1,2,0,0,1,0,0,1,0,0,1 -4,18,4,32,5,1,3,4,4,38,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -1,12,0,62,1,3,3,2,2,28,3,2,1,2,1,0,0,1,0,1,0,0,0,1 -4,10,2,7,3,5,3,4,4,46,3,1,1,2,1,0,0,1,0,0,0,0,0,1 -2,24,2,12,1,2,3,2,1,23,2,1,1,1,1,1,0,1,0,0,1,0,1,0 -4,12,4,23,5,5,3,4,1,49,3,1,1,2,1,0,0,0,1,0,1,0,0,1 -4,36,3,45,1,3,3,2,3,26,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -4,12,2,8,1,3,4,2,1,28,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,30,2,24,1,4,2,4,1,23,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -2,18,2,12,5,3,3,4,4,61,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -3,12,2,34,5,5,3,3,3,37,3,1,1,1,1,0,0,1,0,0,1,0,0,0 -3,12,3,22,1,3,2,2,3,36,2,2,1,2,1,1,0,1,0,0,1,0,0,1 -4,6,2,18,1,3,4,2,2,21,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,18,2,25,1,1,3,1,3,25,3,1,1,1,1,0,0,1,0,0,1,1,0,0 -4,12,2,15,1,4,3,4,3,36,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,18,4,38,1,4,3,1,3,27,3,2,1,1,1,0,1,1,0,0,1,0,0,1 -1,18,2,36,1,2,2,4,3,22,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,36,2,34,1,5,3,2,3,42,3,1,2,1,1,0,0,1,0,0,1,0,0,1 -2,18,2,30,1,4,2,4,1,40,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -4,36,2,31,5,3,3,4,1,36,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,18,4,61,1,5,3,4,3,33,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,10,4,21,1,2,2,3,1,23,3,2,1,1,1,0,0,1,0,1,0,0,0,1 -4,60,4,138,5,5,3,4,4,63,1,1,1,2,1,1,0,1,0,0,0,0,0,0 -2,60,1,148,2,5,2,4,4,60,1,2,1,2,1,0,0,1,0,0,0,0,0,0 -1,48,1,77,1,4,2,4,3,37,3,1,1,1,1,0,0,0,0,1,0,0,0,1 -4,18,3,23,1,1,4,3,1,34,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,7,3,8,5,5,3,4,4,36,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -2,36,2,143,1,5,3,2,4,57,3,1,1,2,1,1,0,1,0,0,0,0,0,0 -4,6,4,4,2,3,2,4,3,52,3,2,1,1,1,1,0,1,0,0,1,0,1,0 -1,20,2,22,5,4,3,4,3,39,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,18,2,130,1,1,2,4,4,38,3,1,1,2,1,0,1,1,0,0,0,0,0,0 -4,22,2,13,5,4,2,4,2,25,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -3,12,2,13,1,2,3,1,1,26,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,30,3,43,2,3,3,2,2,26,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -4,18,4,22,1,3,2,1,3,25,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,2,11,5,2,2,2,1,21,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -2,18,4,74,1,1,3,4,2,40,2,2,1,2,1,0,0,1,0,0,1,0,0,0 -2,15,4,23,3,3,3,4,3,27,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,9,2,14,1,4,2,2,3,27,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,2,18,1,3,4,2,2,30,3,1,1,2,1,1,0,1,0,0,1,0,0,0 -2,12,2,10,4,2,2,4,1,19,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -1,36,2,32,1,4,3,4,4,39,1,1,2,2,1,1,0,1,0,0,0,0,0,0 -1,6,4,20,1,4,2,4,3,31,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,9,4,24,1,1,3,3,3,31,3,1,1,1,1,0,0,1,0,0,1,0,0,0 -2,39,3,118,2,4,3,3,4,32,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -1,12,2,26,1,1,2,4,4,55,3,1,1,1,1,0,0,1,0,0,0,0,0,0 -1,36,4,23,1,3,4,2,2,46,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,12,2,12,1,5,1,1,1,46,3,2,1,1,1,1,0,1,0,1,0,0,0,1 -4,24,4,15,4,3,2,1,1,43,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -4,18,2,15,1,2,4,4,1,39,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,18,4,19,5,3,4,4,1,28,1,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,3,86,1,2,3,2,3,27,1,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,14,3,8,1,3,3,2,3,27,3,2,1,1,1,1,0,1,0,0,1,0,1,0 -2,18,3,29,5,5,3,4,3,43,3,1,2,1,1,1,0,1,0,0,1,0,0,1 -2,24,2,20,1,2,4,1,2,22,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,24,4,22,5,4,3,4,3,43,3,2,2,2,1,0,1,1,0,0,1,0,0,1 -1,15,2,11,1,2,4,2,1,27,3,1,1,1,2,0,0,1,0,0,1,0,0,1 -4,24,2,32,3,5,1,2,3,26,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -3,12,4,9,3,4,4,2,1,28,3,3,1,2,1,1,0,1,0,0,1,0,0,1 -2,24,2,20,1,5,2,4,3,20,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,33,4,73,1,4,3,2,3,35,3,2,1,2,1,0,1,1,0,0,1,0,0,0 -4,12,4,23,1,1,3,2,3,42,2,2,1,2,1,0,0,1,0,0,1,0,0,0 -4,10,2,16,3,3,3,2,4,40,3,1,2,1,2,1,0,1,0,1,0,0,1,0 -1,24,2,14,5,3,2,2,2,35,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,36,4,58,1,5,3,2,2,35,3,2,2,2,1,0,1,1,0,0,1,0,0,1 -1,12,2,26,1,2,3,1,1,33,3,1,2,1,1,1,0,1,0,0,1,0,1,0 -1,18,3,85,5,3,2,2,3,23,3,2,1,2,1,0,0,1,0,1,0,0,0,1 -4,21,2,28,3,4,2,2,3,31,1,1,1,1,1,1,0,1,0,0,1,0,0,0 -2,18,2,10,5,3,2,2,2,33,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,15,2,32,4,4,2,3,3,20,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -2,12,2,20,5,3,3,2,3,30,3,1,1,1,1,0,1,1,0,0,1,0,0,1 -2,12,4,10,1,4,3,3,1,47,3,2,2,1,1,1,0,1,0,0,1,0,1,0 -4,21,3,16,2,4,3,3,1,34,3,2,1,1,1,0,0,1,0,0,1,0,0,0 -2,12,2,28,5,5,2,2,2,25,1,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,18,2,28,1,3,4,3,3,21,3,1,1,2,1,0,1,1,0,1,0,0,0,1 -4,28,4,27,1,5,3,2,3,29,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,4,11,4,3,3,3,1,46,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,9,2,13,1,5,3,4,3,20,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,18,4,12,1,1,2,4,4,55,3,3,2,1,1,0,0,1,0,0,0,1,0,0 -4,5,2,34,1,4,3,4,1,74,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,24,2,113,1,3,3,3,3,29,1,2,1,2,1,0,0,0,1,0,1,0,0,0 -1,6,4,19,1,1,3,4,4,36,3,3,1,2,1,0,0,1,0,0,0,0,0,0 -4,24,4,21,1,3,1,2,1,33,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -1,9,2,21,1,3,3,2,1,25,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,12,2,15,5,3,4,1,1,25,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,6,2,7,3,4,4,4,1,23,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -4,24,4,13,4,5,2,4,1,37,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -1,42,4,34,1,1,3,4,3,65,3,2,1,1,1,0,0,0,1,0,1,1,0,0 -3,12,1,6,1,2,2,1,1,26,3,1,1,1,1,0,0,1,0,0,1,1,0,0 -4,12,2,19,1,5,3,4,3,39,3,1,1,2,1,1,0,1,0,0,1,0,0,0 -1,12,2,16,1,3,2,3,2,30,3,1,1,1,1,0,0,0,1,0,1,0,0,1 -2,20,3,26,1,3,3,3,3,29,1,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,12,2,7,1,5,3,4,3,41,1,1,2,1,1,0,0,1,0,0,1,0,1,0 -2,48,4,51,1,3,2,3,3,30,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -4,9,4,12,5,5,2,4,2,41,3,2,1,1,1,0,0,1,0,1,0,0,1,0 -1,36,2,18,1,2,2,4,3,34,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -2,7,2,26,1,3,3,2,1,35,3,1,1,1,1,0,0,0,0,0,1,0,0,1 -3,12,2,14,5,5,2,4,1,55,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -2,15,3,15,4,3,4,3,2,61,2,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,36,4,111,5,3,3,2,3,30,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -4,6,2,5,1,3,2,1,1,29,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,0,28,1,5,3,4,2,34,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,2,27,1,5,3,4,3,35,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -1,24,2,48,1,4,3,3,2,31,3,1,1,2,1,1,0,0,1,0,1,0,0,1 -4,24,2,27,1,2,2,1,4,29,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -1,11,4,39,1,3,3,2,1,36,3,2,2,1,1,1,0,1,0,1,0,0,0,1 -1,12,2,34,1,5,3,4,4,35,3,1,1,2,1,0,1,1,0,0,0,0,0,1 -1,6,2,3,1,2,2,1,1,27,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,2,46,1,2,3,2,3,32,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,36,2,36,1,3,3,2,2,37,3,1,2,1,1,0,0,0,0,0,1,0,0,1 -1,15,2,17,1,2,3,3,1,36,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -2,12,2,30,1,2,2,1,1,34,3,1,1,1,1,0,0,1,0,1,0,0,0,0 -2,12,2,8,5,5,3,4,2,38,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,2,20,1,4,3,1,3,34,2,2,1,2,1,0,0,1,0,0,1,0,0,1 -1,24,2,29,1,3,3,4,4,63,1,1,2,2,1,0,1,0,0,0,1,0,0,1 -1,24,3,17,1,2,2,2,3,29,3,1,1,2,1,0,0,1,0,1,0,0,1,0 -4,48,3,72,5,5,3,3,3,32,1,2,2,1,1,0,0,1,0,0,1,0,0,1 -4,33,3,28,1,3,2,2,3,26,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,24,3,47,1,4,3,3,3,35,3,2,1,2,1,0,1,1,0,0,1,0,1,0 -2,24,2,31,2,2,4,2,3,22,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -1,6,2,4,1,2,2,4,2,23,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,9,2,7,1,3,3,3,3,28,3,1,1,1,1,1,0,1,0,0,1,0,1,0 -4,6,2,12,5,1,3,4,2,36,3,1,2,2,1,0,0,1,0,0,1,0,0,0 -2,18,4,12,1,3,4,2,3,33,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,18,0,31,1,2,2,4,2,26,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -4,39,2,26,3,3,3,4,3,24,3,1,1,1,1,0,1,1,0,0,1,0,0,1 -3,24,2,52,1,4,3,2,3,25,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,12,2,10,2,4,3,4,1,39,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -1,15,4,15,1,5,3,4,3,44,3,2,2,2,1,0,0,1,0,0,1,0,0,1 -2,12,4,36,1,3,2,1,1,23,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,24,2,12,1,2,3,1,2,26,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -1,30,2,36,4,5,2,4,2,57,3,2,1,2,1,0,0,1,0,1,0,0,0,1 -4,15,3,10,4,4,2,2,2,30,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,4,12,3,3,3,4,1,44,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -2,6,3,12,1,1,3,4,2,47,3,1,1,2,1,1,0,1,0,0,1,0,0,0 -4,12,2,31,1,3,3,4,3,52,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,24,2,38,1,5,2,4,4,62,3,1,1,2,1,1,0,0,1,0,0,0,0,1 -4,10,2,14,2,3,3,2,1,35,3,1,1,1,2,1,0,1,0,1,0,0,1,0 -4,6,2,35,1,3,3,3,2,26,3,1,1,1,1,1,0,0,0,1,0,0,0,1 -4,12,4,19,1,5,3,2,4,26,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,27,0,83,1,5,2,4,4,42,3,2,1,2,1,0,0,1,0,0,0,0,0,0 -4,6,4,12,2,3,2,1,2,27,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,6,2,4,5,5,3,4,2,38,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,4,21,1,3,3,2,1,39,3,2,2,1,2,1,0,1,0,1,0,0,1,0 -1,24,2,30,5,3,4,4,3,20,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,36,2,90,2,2,3,1,4,29,3,1,1,2,1,0,0,0,1,1,0,0,0,0 -4,24,4,16,1,4,3,3,2,40,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,2,13,1,5,4,2,1,32,3,1,1,1,1,0,0,0,0,0,1,0,1,0 -3,6,4,13,2,5,1,4,3,28,3,2,2,2,1,1,0,1,0,0,1,0,0,1 -1,24,2,31,1,2,2,1,2,27,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -1,36,2,55,1,5,3,4,4,42,3,1,2,1,1,0,1,1,0,0,0,0,0,1 -3,9,2,11,2,5,1,4,1,49,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,24,4,12,2,2,3,4,4,38,1,2,2,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,12,1,2,2,4,2,24,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -4,10,2,13,5,3,3,4,2,27,3,1,1,1,1,1,0,0,0,0,1,0,1,0 -3,15,4,24,3,3,3,2,3,36,3,1,1,2,1,0,1,1,0,0,1,0,0,1 -2,15,1,68,2,1,3,2,2,34,3,1,2,2,1,1,0,1,0,0,1,0,0,0 -4,24,2,14,1,3,4,2,2,28,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,39,2,86,2,5,3,2,3,45,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -1,12,2,8,1,4,3,2,1,26,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,36,2,47,1,3,3,2,4,32,3,1,1,2,1,0,1,1,0,0,0,0,0,0 -3,15,2,27,1,4,3,4,2,26,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -2,12,3,6,1,3,4,4,1,20,3,2,1,1,1,0,0,0,1,1,0,0,0,1 -4,24,2,23,5,2,3,1,2,54,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -1,6,4,6,1,4,2,3,2,37,3,2,1,1,2,1,0,1,0,0,1,0,0,1 -1,6,4,14,1,2,3,4,1,40,3,1,2,1,2,1,0,1,0,0,1,0,1,0 -4,36,4,71,1,2,2,4,2,23,3,2,1,2,1,0,0,1,0,1,0,0,0,1 -1,6,2,12,2,5,3,2,2,43,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -4,6,4,7,5,5,3,4,4,36,3,2,1,1,1,0,0,1,0,0,0,0,0,1 -4,24,4,55,1,5,3,4,4,44,3,2,1,1,1,0,0,1,0,0,0,0,0,1 -1,18,2,32,1,3,2,2,1,24,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,48,0,71,1,3,3,4,4,53,3,2,2,1,1,0,0,1,0,0,0,0,0,1 -4,24,2,35,2,4,2,4,3,23,3,1,1,1,1,0,1,1,0,0,1,0,0,1 -2,18,2,11,1,3,2,4,1,26,3,1,2,1,1,0,0,0,0,0,1,0,1,0 -2,26,2,80,1,2,3,3,3,30,3,2,1,1,1,0,1,1,0,0,1,0,0,1 -4,15,4,15,2,3,2,3,3,31,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,4,4,15,1,4,3,1,1,42,3,2,2,1,1,0,0,1,0,0,1,0,1,0 -1,36,2,23,1,3,1,4,3,31,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,6,2,7,1,2,3,4,1,41,3,1,2,2,1,1,0,1,0,0,1,0,1,0 -2,36,2,23,1,4,3,1,3,32,3,2,2,1,1,0,0,1,0,0,1,0,0,1 -2,15,2,26,2,3,2,4,3,28,3,2,1,2,1,1,0,1,0,1,0,0,0,1 -4,12,3,15,1,3,4,4,1,41,3,1,1,1,1,0,1,1,0,1,0,0,0,1 -4,24,2,13,2,4,4,3,2,26,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,24,2,31,5,2,3,2,3,25,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -3,21,4,23,1,2,1,1,3,33,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,6,2,14,5,1,2,3,2,75,3,1,1,2,1,1,0,1,0,0,1,0,0,0 -2,18,4,36,1,5,2,4,2,37,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,48,2,78,1,5,3,4,4,42,1,1,1,1,1,1,0,1,0,0,0,0,0,0 -3,18,2,30,1,2,2,1,2,45,2,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,12,2,15,1,2,4,1,1,23,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -4,24,3,20,1,5,3,4,4,60,3,2,1,2,1,1,0,1,0,0,0,0,0,1 -1,30,2,64,5,5,3,4,2,31,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -3,18,2,29,1,3,3,1,1,34,3,1,2,1,1,0,0,1,0,0,1,0,1,0 -4,12,4,13,1,5,3,4,1,61,3,2,1,1,1,1,0,1,0,0,1,0,1,0 -1,24,3,13,1,1,3,2,1,43,3,2,2,1,1,1,0,1,0,0,0,0,0,1 -4,24,4,20,1,3,2,4,3,37,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -4,24,2,16,1,4,3,1,3,32,1,1,2,1,1,0,0,1,0,0,1,0,0,1 -1,12,1,6,1,3,2,4,1,24,1,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,48,4,89,5,4,3,1,4,35,3,2,1,2,1,0,1,1,0,0,0,0,0,1 -4,12,4,10,5,4,2,4,1,23,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,6,1,18,3,5,3,4,2,45,1,1,2,1,1,0,0,1,0,0,1,0,1,0 -1,48,2,70,1,4,4,1,1,34,3,2,1,2,1,0,0,0,0,0,1,0,0,1 -2,12,4,20,2,2,3,1,3,27,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -2,9,2,12,1,4,2,4,2,67,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -2,12,2,13,1,2,3,1,3,22,2,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,0,23,2,2,2,3,3,28,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,21,0,50,5,3,2,4,2,29,1,2,1,2,1,1,0,1,0,0,1,0,0,1 -1,24,1,36,1,4,3,4,3,27,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,4,19,1,2,3,2,1,31,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -1,24,2,30,5,5,3,4,4,49,1,1,2,2,1,0,1,1,0,0,0,0,0,1 -1,24,1,15,1,4,3,4,3,24,1,1,1,1,1,0,0,0,0,1,0,0,1,0 -3,6,3,7,1,2,2,1,2,29,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,36,2,124,5,3,3,4,4,37,3,1,1,2,1,1,0,1,0,0,0,0,0,1 -2,24,3,47,5,3,3,2,2,37,1,2,1,2,1,0,0,1,0,0,1,0,0,0 -2,24,3,16,2,4,2,2,2,23,3,2,1,2,1,0,0,1,0,1,0,0,0,1 -1,12,2,14,1,4,1,3,3,36,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,24,4,26,4,5,3,2,3,34,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,48,2,40,5,4,3,1,3,41,3,2,2,2,1,0,0,1,0,0,1,0,0,1 -1,48,2,68,1,3,2,2,3,31,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,24,2,32,1,2,2,4,1,23,3,1,1,2,1,0,0,1,0,1,0,0,1,0 -4,30,4,60,1,4,3,2,3,38,3,1,1,1,1,0,0,0,1,0,1,0,0,1 -4,24,2,54,5,1,2,4,2,26,3,1,1,2,1,0,1,1,0,1,0,0,0,0 -1,15,2,8,1,3,2,4,2,22,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,9,2,11,1,5,3,4,3,27,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -4,15,4,28,1,4,2,3,3,24,1,2,1,1,1,0,0,0,1,0,1,0,0,1 -2,12,2,29,1,4,2,1,1,27,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,4,19,5,3,2,2,3,33,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,36,4,28,1,2,1,4,3,27,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,24,2,9,1,2,4,3,3,27,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -2,18,4,11,1,5,3,3,1,30,1,2,1,1,1,1,0,0,0,0,1,0,0,1 -2,12,4,31,1,2,3,3,1,49,1,2,2,1,1,1,0,1,0,0,1,0,1,0 -4,9,2,14,1,3,2,2,1,26,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -2,36,2,24,1,2,3,1,4,33,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -4,12,2,21,5,5,2,4,4,52,3,1,1,2,1,1,0,1,0,0,0,0,0,0 -1,18,2,20,1,3,2,4,1,20,1,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,9,4,28,1,3,3,2,1,36,3,2,2,1,1,1,0,1,0,1,0,0,0,1 -1,12,2,13,1,3,3,1,2,21,3,1,1,1,1,0,0,0,0,0,1,0,1,0 -1,18,2,12,1,3,4,3,1,47,3,1,1,2,1,0,0,1,0,0,1,0,1,0 -1,12,4,22,1,5,3,3,2,60,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,4,4,1,4,2,3,1,58,3,4,1,2,1,0,0,1,0,0,1,0,1,0 -2,24,3,20,5,3,2,4,3,42,3,2,1,2,1,1,0,1,0,1,0,0,0,1 -4,21,2,16,4,5,2,4,1,36,1,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,24,2,27,1,3,2,4,2,20,3,1,1,2,1,1,0,1,0,1,0,0,1,0 -1,24,1,14,5,5,3,3,3,40,2,1,1,2,1,0,0,1,0,0,1,0,0,0 -2,6,1,9,2,2,2,1,2,32,2,1,1,1,1,1,0,1,0,0,1,0,1,0 -1,24,2,14,1,4,2,4,3,23,3,2,1,1,1,1,0,1,0,1,0,0,0,1 -2,24,0,42,1,3,3,4,1,36,3,3,1,2,1,0,0,1,0,0,1,0,1,0 -4,18,4,28,1,4,3,2,2,31,1,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,24,3,39,1,3,3,2,4,32,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -2,7,2,23,1,2,2,1,1,45,3,1,1,1,1,0,0,0,0,0,1,0,0,1 -2,9,2,9,1,3,2,1,2,30,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,24,1,18,1,4,2,4,4,34,1,1,1,1,1,0,0,1,0,0,0,0,1,0 -4,36,2,33,1,3,2,2,3,28,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -3,10,2,13,1,2,2,2,2,23,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,1,28,3,3,3,4,1,22,2,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,24,4,45,1,3,3,2,1,74,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -2,36,2,27,2,3,2,4,4,50,3,1,1,1,1,0,0,0,1,0,0,0,0,1 -4,18,2,21,1,2,3,1,1,33,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,15,2,13,5,5,3,4,4,45,1,1,2,1,1,0,1,1,0,0,0,0,0,1 -1,12,2,7,2,1,2,3,2,22,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -3,10,2,12,2,5,2,4,4,48,3,1,2,1,1,1,0,1,0,0,0,0,1,0 -1,21,2,34,4,2,2,2,3,29,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,1,36,1,3,2,4,3,22,1,1,1,1,2,0,1,0,0,1,0,0,0,1 -4,18,3,18,1,4,2,1,1,22,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,48,0,122,5,3,3,2,3,48,1,1,1,2,1,0,0,1,0,0,1,0,0,0 -2,60,3,92,5,3,3,2,4,27,3,1,1,1,1,0,0,1,0,0,0,0,0,0 -1,6,4,37,1,3,3,3,1,37,3,3,2,1,1,1,0,1,0,1,0,0,0,1 -2,30,2,34,2,3,2,4,3,21,3,1,1,1,1,0,0,0,1,1,0,0,0,1 -4,12,2,6,1,3,1,2,1,49,3,1,1,1,1,1,0,1,0,0,1,0,1,0 -2,21,4,37,1,4,3,3,2,27,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,18,4,15,1,3,3,2,2,32,1,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,48,2,39,5,3,1,2,1,38,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,2,19,1,2,2,1,3,22,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,18,2,26,1,3,3,4,4,65,3,2,1,1,1,0,0,1,0,0,0,0,0,1 -4,15,2,20,5,5,3,2,3,35,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -3,6,2,21,1,3,3,2,1,41,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,9,1,14,2,4,3,3,4,29,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,42,4,40,3,3,3,4,1,36,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,9,2,38,5,5,3,4,1,64,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -1,24,2,37,1,3,2,4,3,28,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,18,1,16,1,3,3,3,3,44,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,15,2,14,5,2,3,1,2,23,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,9,2,20,1,2,2,2,3,19,3,2,1,1,1,0,0,0,1,1,0,0,0,1 -2,24,2,14,1,2,2,4,3,25,3,1,1,2,1,1,0,1,0,0,1,0,1,0 -4,12,2,14,1,5,3,4,2,47,1,3,2,2,1,0,0,1,0,0,1,0,0,1 -4,24,2,14,3,4,2,1,3,28,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,60,3,157,1,4,3,4,3,21,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,12,2,15,1,2,2,3,3,34,3,1,2,1,1,0,0,1,0,0,1,0,0,1 -1,42,3,44,1,4,3,2,2,26,1,2,2,2,1,0,0,1,0,0,1,0,0,1 -1,18,2,8,1,1,2,1,1,27,3,1,1,1,1,0,0,1,0,0,1,1,0,0 -2,15,2,13,1,5,3,4,3,38,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -4,15,2,46,2,3,3,2,2,40,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -4,24,4,19,1,4,4,2,3,33,3,2,1,2,1,0,0,0,0,0,1,0,0,1 -1,18,4,19,1,4,4,1,2,32,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -4,36,3,80,5,2,3,4,3,27,3,2,1,2,1,0,0,1,0,1,0,0,0,1 -1,30,0,46,1,3,1,2,1,32,3,2,1,1,1,0,0,0,0,0,1,0,0,1 -4,12,2,14,3,3,2,2,2,26,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -3,24,2,9,1,4,3,3,4,38,1,1,2,1,1,1,0,1,0,0,0,0,0,1 -1,12,2,7,1,3,3,4,3,40,3,1,2,1,1,0,0,1,0,1,0,0,1,0 -1,48,2,75,1,4,3,1,4,50,3,1,1,2,1,0,0,1,0,0,0,0,0,0 -2,12,2,19,1,3,3,2,2,37,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -1,24,2,23,1,5,3,1,1,45,3,1,1,1,1,1,0,0,1,0,1,0,0,1 -2,36,3,81,2,5,3,4,3,42,3,4,1,2,1,1,0,1,0,0,1,0,0,0 -4,24,4,23,1,4,3,3,3,35,3,2,1,2,1,0,1,1,0,0,1,0,0,1 -1,14,2,40,1,1,3,4,4,22,3,1,1,1,1,1,0,1,0,0,0,0,0,1 -2,12,2,9,1,5,3,4,3,41,1,1,2,1,1,1,0,1,0,0,1,0,1,0 -4,48,2,102,5,4,3,3,3,37,2,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,30,0,42,1,3,2,1,3,28,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,4,64,1,5,3,1,4,41,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -3,12,2,13,1,3,4,4,1,23,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,12,2,9,5,3,4,2,3,23,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,21,2,22,1,5,3,2,1,50,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,6,3,10,1,1,3,1,2,35,2,2,1,2,1,0,0,1,0,0,1,0,0,0 -3,6,4,10,1,3,2,4,2,50,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,24,4,63,1,1,3,2,4,27,1,2,1,2,1,0,0,0,1,0,1,0,0,0 -2,30,1,35,4,3,3,2,3,34,2,1,2,2,1,0,0,1,0,0,1,0,0,1 -4,48,1,36,1,3,2,1,1,27,2,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,4,48,1,5,3,4,2,43,3,2,1,2,1,1,0,0,1,1,0,0,0,1 -3,30,4,30,1,5,3,4,2,47,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,4,41,2,3,3,3,2,27,3,2,1,2,1,0,0,1,0,0,1,0,1,0 -4,36,2,57,2,4,3,2,3,31,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,60,2,104,1,5,3,4,2,42,3,1,1,2,1,1,0,1,0,0,1,0,0,0 -4,6,4,21,3,3,4,2,3,24,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,21,3,26,3,2,3,2,1,41,1,1,2,1,1,0,0,1,0,0,1,0,1,0 -4,30,4,45,1,4,2,4,3,26,3,1,1,2,1,0,0,1,0,1,0,0,0,0 -4,24,4,52,1,5,3,4,3,33,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,72,2,56,2,3,4,2,3,24,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,24,1,5,3,4,1,64,1,1,1,1,1,0,0,1,0,1,0,0,1,0 -4,18,2,15,1,2,2,1,1,26,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,6,2,15,1,2,2,2,4,56,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,2,23,5,3,3,4,4,37,3,1,1,2,1,0,0,1,0,0,0,0,0,1 -4,15,3,15,1,3,4,3,1,33,1,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,4,51,1,2,4,3,4,47,3,3,1,2,1,0,0,1,0,0,0,0,0,1 -2,36,3,99,2,4,3,3,2,31,3,2,2,2,1,0,0,1,0,0,1,0,1,0 -4,60,2,65,5,3,3,4,4,34,3,1,2,2,1,1,0,1,0,0,0,0,0,1 -3,10,4,13,5,4,3,2,2,27,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,36,3,29,2,5,3,3,4,30,3,1,1,1,1,1,0,1,0,0,0,0,0,1 -4,9,2,28,2,5,3,4,3,35,3,1,1,2,1,0,0,0,1,0,1,0,0,1 -1,12,2,37,4,3,3,3,2,31,3,1,2,1,1,1,0,1,0,0,1,0,0,1 -1,15,4,10,1,3,1,3,2,25,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,15,2,26,2,3,2,2,1,25,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,24,2,29,2,2,3,1,3,29,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,6,4,47,5,2,3,3,1,44,3,2,2,1,1,1,0,1,0,0,1,0,1,0 -4,24,2,23,1,4,3,2,3,28,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,6,2,12,3,3,3,4,2,50,3,1,1,1,1,0,1,1,0,1,0,0,0,1 -2,12,2,11,1,4,3,3,1,29,3,2,1,1,2,0,0,0,0,0,1,0,0,1 -4,12,4,9,1,1,2,2,2,38,3,1,1,1,1,1,0,1,0,0,1,1,0,0 -4,18,4,18,1,3,3,2,3,24,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -3,15,2,19,1,5,3,4,3,40,3,1,1,2,1,0,0,1,0,1,0,0,0,0 -4,12,2,11,3,3,2,4,3,29,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -1,48,4,63,1,5,3,4,4,46,3,2,1,2,1,0,1,1,0,0,0,0,0,1 -3,24,2,14,2,5,2,2,4,47,3,1,1,2,1,0,0,1,0,0,0,0,0,1 -2,30,3,25,2,5,3,2,2,41,2,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,27,2,25,1,2,2,1,2,32,3,1,2,2,1,0,0,1,0,0,1,0,0,1 -4,15,2,53,3,5,2,4,4,35,3,1,1,1,1,1,0,1,0,0,0,0,0,1 -2,48,2,66,2,4,3,2,2,24,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -2,12,0,30,1,2,2,3,2,25,3,2,1,1,1,0,0,1,0,1,0,0,0,1 -2,9,2,12,1,5,2,4,1,25,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,9,2,21,1,3,3,2,1,37,3,1,2,1,1,0,0,1,0,0,1,0,1,0 -4,18,4,6,3,5,3,3,2,32,1,2,1,2,1,0,0,1,0,0,1,0,0,0 -1,6,1,12,1,5,2,4,4,35,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -4,21,2,25,5,5,3,4,1,46,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -1,9,4,11,1,3,3,4,1,25,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -2,60,2,140,1,4,3,2,4,27,3,1,1,2,1,1,0,1,0,0,1,0,0,0 -4,30,4,76,5,5,3,4,3,63,3,2,1,1,1,0,1,1,0,0,1,0,0,1 -4,30,4,31,5,5,3,2,3,40,3,2,2,2,1,0,0,1,0,0,1,0,0,1 -4,18,2,15,1,3,3,2,4,32,3,1,1,2,1,0,0,1,0,0,0,0,0,0 -3,24,4,31,5,3,3,2,3,31,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,20,0,61,2,5,4,4,3,31,1,2,1,2,1,0,1,1,0,0,1,0,0,1 -3,9,0,13,1,2,3,2,3,34,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -2,6,1,4,4,2,2,2,2,24,1,1,2,1,1,0,0,1,0,1,0,0,0,1 -1,12,2,12,1,3,2,2,1,24,3,1,1,1,1,1,0,1,0,0,1,0,1,0 -2,9,2,8,3,3,2,3,1,66,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,27,2,26,1,3,2,3,1,21,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -4,6,4,2,4,3,2,2,1,41,1,2,1,1,1,1,0,1,0,0,1,0,1,0 -4,15,4,13,3,3,4,2,2,47,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -1,18,2,19,1,3,2,4,3,25,1,2,1,1,1,0,0,1,0,1,0,0,0,1 -2,48,1,64,1,5,2,3,4,59,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -3,24,4,13,4,3,1,4,1,36,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,24,3,64,1,2,3,2,3,33,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,20,1,3,3,4,1,21,3,1,2,1,1,0,0,1,0,1,0,0,1,0 -2,8,2,8,1,4,2,2,1,44,3,1,1,1,1,0,0,0,0,0,1,0,1,0 -4,24,2,26,4,3,2,4,3,28,3,1,1,2,1,0,1,1,0,1,0,0,0,1 -4,4,4,34,1,4,2,1,1,37,3,1,2,1,1,1,0,1,0,0,1,0,0,1 -2,36,1,40,5,2,2,2,4,29,1,1,1,1,1,0,0,1,0,0,1,1,0,0 -2,24,2,116,1,3,2,4,3,23,3,2,1,1,1,0,1,1,0,1,0,0,0,0 -1,18,2,44,2,3,3,4,3,35,3,1,2,2,1,1,0,1,0,0,1,0,1,0 -4,6,4,68,1,4,3,3,4,45,3,2,2,2,1,1,0,1,0,0,1,0,0,0 -2,30,0,43,2,3,2,4,3,26,3,2,1,1,1,0,0,1,0,1,0,0,1,0 -1,24,1,23,2,4,3,3,3,32,1,1,1,1,1,1,0,1,0,0,1,0,0,1 -2,10,1,10,1,3,3,4,1,23,2,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,21,2,32,5,5,3,3,2,41,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,24,1,25,3,3,3,4,1,22,2,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,39,4,142,5,4,3,4,2,30,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -1,13,4,18,1,2,3,1,2,28,1,2,1,1,1,0,0,1,0,0,1,0,1,0 -1,15,2,25,1,1,2,4,3,23,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -1,12,2,13,1,2,2,1,1,37,3,1,1,1,1,1,0,1,0,0,1,0,1,0 -4,21,2,52,5,3,3,3,3,26,3,1,1,1,1,0,1,1,0,0,1,0,0,1 -4,15,2,30,1,4,3,2,3,33,3,1,1,1,1,0,1,1,0,0,1,0,0,1 -1,6,2,4,1,5,2,1,2,49,1,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,18,2,10,1,2,2,2,3,23,3,1,1,1,1,1,0,1,0,0,1,0,1,0 -2,12,2,8,2,4,2,4,1,23,3,1,1,1,1,0,0,1,0,1,0,0,1,0 -4,30,4,58,1,4,2,2,3,25,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,3,16,4,5,3,4,4,55,3,2,2,1,1,0,0,1,0,0,0,0,0,1 -1,24,2,13,5,4,2,4,4,32,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -3,6,4,13,1,3,3,1,1,74,3,3,2,1,2,1,0,1,0,0,1,1,0,0 -3,15,4,13,5,3,3,4,4,39,3,2,1,2,1,0,0,1,0,0,0,0,0,1 -4,24,2,14,1,3,3,2,1,31,3,1,1,2,1,1,0,0,0,0,1,0,0,1 -1,12,4,7,1,5,3,3,2,35,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,15,4,50,5,5,2,4,3,59,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -1,18,4,21,1,3,2,4,1,24,3,2,1,1,1,0,0,1,0,1,0,0,0,1 -1,12,2,22,1,3,3,3,2,24,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,21,4,127,5,5,3,4,4,30,3,1,1,2,1,1,0,1,0,0,0,0,0,0 -4,24,4,25,2,4,4,3,2,27,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -2,12,2,12,1,5,4,3,1,40,1,2,1,1,1,0,0,0,0,0,1,0,1,0 -1,30,2,31,1,2,1,4,2,31,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -4,10,2,29,5,2,2,4,1,31,3,1,1,1,1,0,1,1,0,1,0,0,0,1 -2,12,4,36,1,5,3,4,3,28,3,3,1,2,1,0,0,1,0,1,0,0,0,1 -4,12,4,17,1,5,3,4,1,63,3,2,1,2,1,0,0,1,0,0,1,0,1,0 -1,24,2,28,5,5,2,4,1,26,3,1,1,1,1,0,1,1,0,1,0,0,0,1 -1,36,4,81,1,3,2,2,4,25,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -4,21,4,33,1,5,3,4,3,36,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -4,24,4,22,2,5,3,4,2,52,1,2,1,1,1,0,0,1,0,0,1,0,0,1 -3,12,4,15,3,1,3,4,4,66,1,3,1,1,1,1,0,1,0,0,0,1,0,0 -1,24,2,14,5,3,2,4,1,25,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -4,36,4,35,1,4,3,4,3,37,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -1,18,2,35,1,4,2,1,1,25,3,1,1,1,1,0,0,0,0,0,1,0,0,1 -4,36,4,57,4,5,3,2,3,38,3,2,1,2,1,0,1,1,0,0,1,0,0,0 -2,18,2,39,1,1,2,4,3,67,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,39,4,49,1,4,3,2,1,25,3,2,1,1,1,0,0,0,0,0,1,0,0,1 -4,24,4,19,4,5,3,4,1,60,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -2,12,0,14,1,3,3,2,1,31,3,1,1,2,1,0,0,1,0,0,1,0,1,0 -2,12,2,8,2,2,2,2,2,23,1,1,1,1,1,1,0,1,0,0,1,0,1,0 -2,20,2,65,5,1,1,4,1,60,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -2,18,2,19,4,3,3,2,2,35,3,1,1,2,1,0,0,1,0,0,1,0,1,0 -4,22,2,27,3,5,3,4,3,40,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,48,4,28,5,5,3,3,3,38,3,2,2,2,1,0,1,1,0,0,1,0,0,1 -2,48,3,62,1,5,3,4,4,50,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -1,40,4,60,1,3,3,3,4,27,1,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,21,2,12,1,5,2,4,2,39,3,1,2,1,1,0,0,1,0,0,1,0,0,1 -4,24,2,63,5,5,3,4,3,41,3,1,2,2,1,0,1,1,0,0,1,0,0,0 -4,6,4,12,5,3,4,2,2,27,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -3,24,2,29,1,5,1,4,4,51,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -4,24,2,31,3,5,3,3,4,32,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -4,9,2,23,2,2,2,4,2,22,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,18,2,75,5,5,3,4,2,51,3,1,2,2,1,0,1,1,0,0,0,0,0,1 -4,12,4,13,1,2,2,4,2,22,3,2,1,1,1,0,0,1,0,1,0,0,1,0 -4,24,3,7,5,5,4,4,3,54,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -2,9,2,15,5,2,3,2,1,35,3,1,1,1,1,1,0,1,0,0,1,1,0,0 -4,24,4,16,1,5,3,4,4,54,3,2,2,1,1,0,0,1,0,0,0,0,0,1 -2,18,4,18,1,5,2,4,1,48,1,2,1,2,1,0,0,0,0,1,0,0,1,0 -1,20,4,43,1,5,2,4,2,24,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,4,10,5,5,3,4,3,35,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,12,2,75,5,1,2,2,1,24,3,1,1,1,1,1,0,1,0,1,0,1,0,0 -1,36,2,93,1,4,3,1,3,24,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -2,6,2,6,1,2,4,3,1,26,3,1,1,1,2,0,0,1,0,0,1,0,1,0 -4,12,4,9,5,5,3,4,1,65,3,4,1,1,1,0,0,1,0,0,1,0,0,1 -2,42,1,93,1,1,3,2,4,55,1,1,1,2,1,0,1,1,0,0,0,0,0,0 -2,15,0,18,1,2,2,1,1,26,3,2,1,1,1,1,0,1,0,1,0,1,0,0 -2,8,2,9,1,2,4,2,1,26,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -2,6,2,5,1,4,4,3,1,28,1,1,1,1,1,0,0,0,0,0,1,0,1,0 -1,36,4,96,1,4,3,4,3,24,3,2,1,2,1,0,1,1,0,0,1,0,0,1 -1,48,2,31,1,3,3,4,3,54,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,48,2,39,1,4,3,4,4,46,3,1,2,1,1,1,0,1,0,0,0,0,0,1 -2,36,3,74,1,3,2,2,2,54,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -4,6,2,13,3,3,1,4,1,62,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,6,4,16,1,4,2,2,3,24,3,2,1,2,1,0,0,1,0,1,0,0,0,1 -1,36,2,159,1,1,1,3,3,43,3,1,1,1,1,0,0,0,1,0,1,0,0,0 -1,18,2,13,1,3,4,3,1,26,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,2,11,1,3,4,2,1,27,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -3,12,2,30,1,3,4,1,3,24,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,36,2,27,1,5,3,2,2,41,1,1,2,1,1,0,0,1,0,0,1,0,0,1 -1,8,4,7,1,5,3,4,1,47,3,2,1,1,1,1,0,1,0,0,1,0,1,0 -4,18,4,38,1,2,1,2,3,35,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -1,21,4,16,1,5,4,3,3,30,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -1,18,4,40,1,5,2,4,1,33,1,3,1,2,1,1,0,1,0,1,0,0,0,1 -4,18,0,42,1,3,3,2,3,36,2,2,2,1,1,0,0,1,0,0,1,0,0,1 -1,36,2,83,5,5,3,4,4,47,3,1,1,1,1,0,1,1,0,0,0,0,0,1 -2,48,3,67,5,3,3,4,4,38,3,1,2,2,1,0,0,1,0,0,0,0,0,1 -4,24,3,24,3,3,3,2,3,44,3,2,2,2,1,0,0,1,0,0,1,0,0,1 -1,18,2,12,1,2,2,3,3,23,3,1,1,2,1,1,0,1,0,1,0,0,0,1 -1,45,0,118,1,5,3,4,3,29,3,2,1,1,1,0,0,1,0,1,0,0,0,1 -2,24,2,51,5,5,2,4,3,42,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -3,15,2,23,1,2,2,3,1,25,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -1,12,0,11,1,3,3,4,3,48,1,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,12,2,9,5,3,2,2,3,21,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,4,2,6,1,2,2,3,1,23,3,1,2,1,1,0,0,1,0,1,0,0,1,0 -1,24,4,30,1,5,3,4,2,63,3,2,1,2,1,0,1,1,0,0,1,0,0,1 -4,24,4,26,1,5,4,3,1,46,3,2,1,1,1,0,0,0,1,0,1,0,0,1 -1,36,2,52,1,4,3,2,2,29,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,21,3,30,1,3,3,2,1,28,2,2,1,1,1,0,1,1,0,0,1,0,1,0 -4,18,2,19,1,2,2,4,1,23,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,1,16,1,4,3,4,3,50,1,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,18,2,34,1,5,3,4,2,47,1,3,2,2,1,0,0,1,0,0,1,0,0,1 -2,21,2,40,5,4,3,3,3,35,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,18,2,68,5,3,3,4,3,68,3,2,1,1,1,1,0,1,0,1,0,0,0,1 -4,24,2,12,1,2,4,2,1,28,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -1,9,2,14,1,4,3,4,1,59,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,2,7,1,5,3,4,1,57,2,1,1,1,1,0,0,1,0,0,1,0,1,0 -1,20,4,22,1,3,4,2,2,33,1,2,1,1,2,1,0,0,0,1,0,0,0,1 -4,24,4,40,5,4,3,4,2,43,3,2,1,2,1,0,1,1,0,0,1,0,0,1 -4,15,4,15,1,3,3,4,4,35,3,2,1,2,1,0,0,1,0,0,0,0,0,1 -1,18,1,14,1,4,3,4,4,32,3,2,2,1,1,1,0,1,0,0,0,0,1,0 -4,36,3,109,1,5,3,2,3,45,3,2,2,2,1,1,0,1,0,0,1,0,0,1 -4,24,2,15,2,2,4,3,1,33,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -4,10,2,9,5,4,2,3,2,40,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,15,4,33,1,3,3,2,4,28,3,1,1,2,1,0,0,1,0,0,0,0,0,1 -1,15,2,40,1,3,2,2,2,29,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -4,9,2,36,2,3,3,2,1,26,3,1,2,1,2,1,0,0,0,1,0,0,0,1 -4,24,4,58,4,3,3,2,1,27,3,2,1,1,1,0,1,1,0,0,1,0,0,1 -4,18,3,22,1,3,4,2,3,28,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,24,2,24,1,2,2,4,1,35,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,27,4,45,4,2,3,2,1,32,2,2,2,2,1,0,0,1,0,0,1,0,1,0 -4,10,2,22,1,3,3,2,1,25,1,1,1,1,1,0,0,1,0,1,0,0,1,0 -4,15,2,22,3,3,2,4,3,20,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,18,2,24,1,2,2,1,3,27,2,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,12,4,33,1,5,3,4,2,42,2,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,36,2,74,5,5,3,2,2,37,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,2,7,1,5,2,4,2,24,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -4,36,3,77,3,4,2,4,3,40,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -3,6,4,13,1,5,3,4,1,46,3,2,2,1,2,1,0,1,0,0,1,0,0,1 -1,24,4,14,2,4,3,1,1,26,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,15,2,9,5,2,2,1,1,24,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,12,2,36,1,3,3,2,2,29,3,1,2,1,1,0,0,0,1,0,1,0,1,0 -2,11,4,13,4,3,2,4,3,40,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -1,18,1,19,1,2,3,4,4,36,1,1,1,2,1,0,0,0,1,0,0,0,0,0 -4,36,2,36,1,5,3,2,3,28,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,9,2,14,1,2,3,2,4,27,3,1,1,2,1,1,0,1,0,0,0,0,0,0 -4,30,4,67,5,4,3,3,2,36,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,2,78,1,4,3,3,3,38,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -4,24,2,93,5,3,1,4,4,48,3,1,1,2,1,0,1,1,0,0,0,0,0,1 -2,30,4,22,5,5,3,4,1,36,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,18,4,11,1,1,2,4,3,65,3,2,1,1,1,0,0,1,0,0,1,1,0,0 -2,24,2,41,1,4,1,3,3,43,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,12,2,8,1,2,2,4,2,53,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,24,4,28,5,4,3,3,4,34,3,2,2,2,1,0,0,1,0,0,1,0,0,1 -2,48,2,157,1,3,3,2,3,23,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,36,4,66,1,5,3,4,3,34,3,2,1,2,1,1,0,1,0,0,1,0,0,0 -4,28,1,78,5,2,3,4,1,40,1,2,2,2,1,0,1,0,0,1,0,0,0,1 -1,27,4,24,1,5,3,4,3,43,2,4,2,2,1,0,0,1,0,0,1,0,0,0 -4,15,4,18,1,5,3,4,3,46,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -1,12,4,22,1,3,3,4,2,38,1,2,1,1,2,1,0,1,0,0,1,0,1,0 -2,36,4,58,1,3,3,4,3,34,3,2,1,2,1,0,1,1,0,0,1,0,0,1 -4,18,4,12,5,3,3,3,2,29,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -4,36,3,89,5,4,3,2,3,31,2,1,2,2,1,0,1,1,0,0,1,0,0,0 -1,21,2,26,1,2,2,4,2,28,3,1,1,2,1,0,0,1,0,1,0,0,0,0 -4,12,4,16,4,4,2,2,2,35,3,1,1,1,2,0,0,1,0,0,1,0,0,1 -4,15,2,22,5,4,2,4,1,33,1,1,1,1,1,0,0,1,0,1,0,0,1,0 -1,18,2,42,1,3,3,3,3,42,3,1,1,1,1,0,0,0,1,0,1,0,0,1 -1,16,4,26,1,5,3,4,2,43,1,1,1,2,1,1,0,0,0,1,0,0,0,1 -4,20,4,35,5,2,1,4,1,44,3,2,1,2,1,1,0,1,0,0,1,0,0,1 -4,36,4,105,5,5,3,4,4,42,3,2,1,1,1,0,1,1,0,0,0,0,0,1 -4,15,2,14,5,3,4,2,1,40,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -4,24,2,13,1,5,3,1,1,36,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -1,12,2,11,1,3,3,2,1,20,3,1,2,2,1,0,0,1,0,1,0,0,0,0 -1,21,2,38,5,4,3,2,1,24,3,1,1,1,2,1,0,0,1,0,1,0,1,0 -2,36,2,37,5,3,4,2,3,27,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,15,3,36,1,2,2,2,2,46,3,2,1,1,1,0,1,1,0,0,1,0,1,0 -2,9,2,32,5,3,2,2,1,33,3,1,1,1,1,1,0,1,0,0,1,0,1,0 -4,36,3,45,1,3,2,4,1,34,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,24,4,47,1,2,2,4,3,25,1,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,30,2,30,5,5,2,4,3,25,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,11,2,21,4,5,1,2,1,28,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,24,1,32,1,3,3,2,2,31,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -2,48,0,184,1,3,2,2,2,32,1,1,1,2,2,0,0,1,0,0,1,0,0,0 -4,10,2,28,2,3,3,2,1,32,3,1,2,1,1,0,1,0,1,0,1,0,0,1 -1,6,2,149,1,5,3,4,4,68,1,1,1,2,1,1,0,1,0,0,1,0,0,0 -1,24,2,24,2,1,1,1,2,33,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,33,1,5,3,2,2,39,3,1,1,2,1,0,0,1,0,1,0,0,0,0 -4,18,4,18,1,3,2,2,4,28,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,48,3,127,3,4,3,1,3,37,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -1,9,2,14,1,2,2,4,2,22,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -2,12,2,20,1,4,3,4,2,30,3,1,2,2,1,1,0,1,0,1,0,0,0,1 -1,24,1,69,1,2,1,1,2,55,1,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,12,1,7,1,2,3,2,3,46,1,2,1,2,1,1,0,1,0,0,1,0,0,1 -1,18,4,10,1,2,2,4,2,21,3,1,1,1,1,0,0,1,0,1,0,0,0,1 -1,48,2,103,1,4,3,4,4,39,2,3,2,2,1,0,1,1,0,0,0,0,0,1 -4,30,2,19,5,5,3,4,3,58,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -1,12,3,13,1,3,3,2,1,43,3,2,2,1,1,1,0,1,0,0,1,0,1,0 -1,24,2,17,1,2,3,1,2,24,3,1,1,1,2,0,0,0,1,0,1,0,1,0 -2,9,2,17,1,2,2,2,3,22,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,9,4,12,1,3,3,1,1,30,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,12,4,5,3,5,3,4,2,42,3,2,2,2,1,0,0,1,0,0,1,0,0,1 -1,12,2,15,1,3,2,1,3,23,1,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,30,3,19,2,2,3,3,4,30,2,2,1,1,1,0,0,1,0,0,1,0,0,0 -3,9,2,7,1,3,2,2,1,28,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,6,2,21,1,2,4,3,3,30,3,1,1,2,1,0,0,1,0,1,0,0,0,0 -2,60,2,63,1,3,3,4,4,42,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -4,24,4,68,5,3,3,4,2,46,3,2,2,2,1,0,1,1,0,0,1,0,0,0 -4,12,2,35,5,2,3,3,2,45,3,1,2,2,1,1,0,1,0,0,1,0,0,0 -4,10,2,15,1,3,3,2,1,31,3,1,2,1,2,1,0,1,0,0,1,0,1,0 -4,24,2,9,5,4,3,2,3,31,2,1,1,2,1,0,0,1,0,0,1,0,0,1 -4,4,4,15,1,4,3,1,1,42,3,3,2,1,1,1,0,1,0,0,1,0,1,0 -1,15,2,18,1,2,2,1,2,46,3,1,1,1,1,0,0,0,0,1,0,0,0,1 -2,48,0,84,3,2,2,1,3,30,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -1,24,1,33,3,2,3,4,4,30,3,1,2,2,1,0,0,1,0,0,0,0,0,1 -4,12,2,29,5,1,3,4,4,38,3,1,1,2,1,1,0,1,0,0,1,0,0,0 -4,18,2,15,1,2,4,1,2,43,3,1,2,1,1,0,0,0,1,0,1,0,1,0 -4,24,2,36,2,5,3,4,3,31,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -2,18,4,36,1,1,4,3,3,40,3,3,2,2,1,0,0,1,0,0,1,1,0,0 -1,36,3,21,1,4,3,1,3,24,3,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,24,2,41,3,2,2,4,3,28,3,1,1,1,1,0,1,1,0,1,0,0,0,1 -4,36,2,110,1,1,2,2,3,26,3,2,1,2,1,0,0,1,0,0,1,0,0,0 -1,12,2,19,1,3,2,4,2,29,3,1,1,2,1,1,0,0,0,0,1,0,0,1 -1,24,4,12,4,5,2,4,2,57,3,2,1,2,1,0,0,1,0,1,0,0,0,0 -3,30,4,37,5,5,3,4,2,49,2,2,1,1,1,0,0,1,0,0,1,0,1,0 -2,9,4,12,1,5,3,4,1,37,3,3,1,1,1,0,0,1,0,0,1,0,1,0 -1,28,2,40,1,3,3,2,3,45,3,1,1,1,1,1,0,1,0,0,1,0,1,0 -2,24,2,31,2,5,3,4,4,30,3,1,1,1,1,0,0,1,0,0,0,0,0,1 -4,6,4,17,1,5,4,2,1,30,3,2,1,1,1,0,0,1,0,1,0,0,0,1 -2,21,3,24,1,3,1,4,2,47,3,2,1,1,1,1,0,1,0,0,1,0,0,1 -4,15,2,36,5,3,3,2,4,29,3,1,1,1,1,1,0,1,0,0,1,0,0,1 -4,24,2,24,3,5,3,2,3,35,1,2,1,2,1,0,0,1,0,0,1,0,0,1 -2,6,2,5,1,2,4,1,2,22,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,30,2,17,5,3,2,1,3,26,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -2,27,4,25,3,3,3,2,2,23,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -4,15,2,36,1,5,2,2,3,54,1,1,1,2,1,0,0,1,0,1,0,0,0,0 -4,42,2,72,5,4,4,4,2,29,3,1,1,2,1,0,0,1,0,1,0,0,0,1 -1,11,4,39,1,3,3,2,1,40,3,2,2,1,1,1,0,1,0,0,1,0,1,0 -2,15,2,15,2,3,3,2,1,22,3,1,1,1,1,0,0,0,0,0,1,0,0,1 -4,24,2,74,1,3,3,4,2,43,3,1,2,1,1,1,0,1,0,0,1,0,1,0 -1,24,1,12,1,1,2,4,4,29,3,2,1,1,1,1,0,0,1,1,0,1,0,0 -1,60,2,73,1,5,3,4,4,36,3,1,1,1,1,0,0,0,1,1,0,0,0,1 -4,30,4,28,1,3,2,2,3,33,3,1,1,2,1,0,0,1,0,0,1,0,0,1 -3,24,2,13,3,3,2,3,3,57,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -2,6,2,8,1,3,2,3,1,64,3,1,1,1,1,0,0,0,0,0,1,0,0,1 -2,18,3,24,5,5,3,2,2,42,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,24,3,25,1,5,3,4,3,47,3,2,2,1,1,1,0,1,0,0,1,0,1,0 -2,15,1,13,2,3,4,2,2,25,3,1,1,1,1,1,0,1,0,1,0,0,0,1 -2,30,4,84,1,4,3,2,2,49,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -4,48,2,48,1,1,3,2,3,33,1,1,1,2,1,0,0,1,0,1,0,0,0,0 -3,21,2,29,2,3,2,1,3,28,1,1,1,2,1,1,0,1,0,0,1,0,0,0 -1,36,2,82,1,3,3,2,2,26,3,1,2,1,1,0,1,1,0,0,1,0,0,1 -4,24,4,20,1,4,3,2,2,30,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -1,15,4,14,1,3,2,3,2,25,3,2,1,1,1,0,0,1,0,1,0,0,0,1 -3,42,0,63,1,2,1,1,2,33,3,2,1,1,1,0,0,1,0,0,1,0,0,1 -4,13,2,14,2,1,2,4,1,64,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,24,2,66,1,1,3,2,4,29,3,1,1,2,1,0,1,1,0,0,0,0,0,0 -2,24,4,17,1,5,3,2,2,48,3,2,1,1,1,0,0,1,0,0,1,0,1,0 -4,12,4,36,5,2,3,1,2,37,3,2,2,1,1,0,0,1,0,0,1,0,1,0 -4,15,1,16,2,5,3,4,3,34,1,1,2,1,1,0,0,1,0,0,1,0,1,0 -1,18,2,19,5,4,4,4,3,23,3,2,1,1,1,0,0,1,0,1,0,0,1,0 -1,36,2,40,1,1,3,3,2,30,3,1,1,2,1,0,0,1,0,0,1,0,0,0 -4,12,2,24,5,5,3,3,3,50,3,1,1,2,1,1,0,1,0,0,1,0,0,1 -4,12,2,17,1,4,2,4,1,31,3,1,1,1,1,0,0,1,0,0,1,0,1,0 -1,30,2,39,1,3,1,4,2,40,3,1,1,2,1,0,1,1,0,0,1,0,0,0 -4,12,2,8,1,5,3,4,3,38,3,1,1,1,1,0,0,1,0,0,1,0,0,1 -1,45,2,18,1,3,3,4,4,23,3,1,1,2,1,0,0,1,0,0,0,0,0,1 -2,45,4,46,2,1,3,4,3,27,3,1,1,1,1,0,1,1,0,0,1,0,0,1 \ No newline at end of file diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/add_to_po.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/add_to_po.hpp deleted file mode 100644 index a8bea29fa..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/add_to_po.hpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @file add_to_po.hpp - * @author Ryan Curtin - * - * Utility functions to add options to boost::program_options based on their - * type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_ADD_TO_PO_HPP -#define MLPACK_BINDINGS_CLI_ADD_TO_PO_HPP - -#include -#include -#include -#include "map_parameter_name.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Add a non-vector option to boost::program_options. - * - * @param boostName The name of the option to add to boost::program_options. - * @param descr Description string for parameter. - * @param desc Options description to add parameter to. - */ -template -void AddToPO(const std::string& boostName, - const std::string& descr, - boost::program_options::options_description& desc, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - desc.add_options()(boostName.c_str(), boost::program_options::value(), - descr.c_str()); -} - -/** - * Add a vector option to boost::program_options. This overload will use the - * multitoken() option. - * - * @param boostName The name of the option to add to boost::program_options. - * @param descr Description string for parameter. - * @param desc Options description to add parameter to. - */ -template -void AddToPO(const std::string& boostName, - const std::string& descr, - boost::program_options::options_description& desc, - const typename boost::enable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - desc.add_options()(boostName.c_str(), - boost::program_options::value()->multitoken(), descr.c_str()); -} - -/** - * Add a boolean option to boost::program_options. - * - * @param boostName The name of the option to add to boost::program_options. - * @param descr Description string for parameter. - * @param desc Options description to add parameter to. - */ -template -void AddToPO(const std::string& boostName, - const std::string& descr, - boost::program_options::options_description& desc, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - desc.add_options()(boostName.c_str(), descr.c_str()); -} - -/** - * Add an option to boost::program_options. This is the function meant to be - * used in the CLI function map. - * - * @param d Parameter data. - * @param input Unused void pointer. - * @param output Void pointer to options_description object. - */ -template -void AddToPO(const util::ParamData& d, - const void* /* input */, - void* output) -{ - // Cast boost::program_options::options_description object. - boost::program_options::options_description* desc = - (boost::program_options::options_description*) output; - - // Generate the name to be given to boost::program_options. - const std::string mappedName = - MapParameterName::type>(d.name); - std::string boostName = (d.alias != '\0') ? mappedName + "," + - std::string(1, d.alias) : mappedName; - - // Note that we have to add the option as type equal to the mapped type, not - // the true type of the option. - AddToPO::type>::type>( - boostName, d.desc, *desc); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/cli_option.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/cli_option.hpp deleted file mode 100644 index 794403962..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/cli_option.hpp +++ /dev/null @@ -1,199 +0,0 @@ -/** - * @file option.hpp - * @author Matthew Amidon - * - * Definition of the Option class, which is used to define parameters which are - * used by CLI. The ProgramDoc class also resides here. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_BINDINGS_CLI_CLI_OPTION_HPP -#define MLPACK_CORE_BINDINGS_CLI_CLI_OPTION_HPP - -#include - -#include -#include "parameter_type.hpp" -#include "add_to_po.hpp" -#include "default_param.hpp" -#include "output_param.hpp" -#include "get_printable_param.hpp" -#include "string_type_param.hpp" -#include "get_param.hpp" -#include "get_raw_param.hpp" -#include "map_parameter_name.hpp" -#include "set_param.hpp" -#include "get_printable_param_name.hpp" -#include "get_printable_param_value.hpp" -#include "get_allocated_memory.hpp" -#include "delete_allocated_memory.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * A static object whose constructor registers a parameter with the CLI class. - * This should not be used outside of CLI itself, and you should use the - * PARAM_FLAG(), PARAM_DOUBLE(), PARAM_INT(), PARAM_STRING(), or other similar - * macros to declare these objects instead of declaring them directly. - * - * @see core/util/cli.hpp, mlpack::CLI - */ -template -class CLIOption -{ - public: - /** - * Construct an Option object. When constructed, it will register - * itself with CLI. - * - * @param defaultValue Default value this parameter will be initialized to - * (for flags, this should be false, for instance). - * @param identifier The name of the option (no dashes in front; for --help, - * we would pass "help"). - * @param description A short string describing the option. - * @param alias Short name of the parameter. "" for no alias. - * @param cppName Name of the C++ type of this parameter (i.e. "int"). - * @param required Whether or not the option is required at runtime. - * @param input Whether or not the option is an input option. - * @param noTranspose If the parameter is a matrix and this is true, then the - * matrix will not be transposed on loading. - * @param testName Is not used and added for compatibility reasons. - */ - CLIOption(const N defaultValue, - const std::string& identifier, - const std::string& description, - const std::string& alias, - const std::string& cppName, - const bool required = false, - const bool input = true, - const bool noTranspose = false, - const std::string& /*testName*/ = "") - { - // Create the ParamData object to give to CLI. - util::ParamData data; - - data.desc = description; - data.name = identifier; - data.tname = TYPENAME(N); - data.alias = alias[0]; - data.wasPassed = false; - data.noTranspose = noTranspose; - data.required = required; - data.input = input; - data.loaded = false; - data.persistent = false; // All CLI parameters are not persistent. - data.cppType = cppName; - - // Apply default value. - if (std::is_same::type, - typename ParameterType::type>::type>::value) - { - data.value = boost::any(defaultValue); - } - else - { - typename ParameterType::type>::type tmp; - data.value = boost::any(std::tuple(defaultValue, tmp)); - } - - const std::string tname = data.tname; - const std::string boostName = MapParameterName< - typename std::remove_pointer::type>(identifier); - std::string progOptId = (alias[0] != '\0') ? boostName + "," - + std::string(1, alias[0]) : boostName; - - // Do a check to ensure that the boost name isn't already in use. - const std::map& parameters = - CLI::Parameters(); - if (parameters.count(boostName) > 0) - { - // Create a fake Log::Fatal since it may not yet be initialized. - // Temporarily define color code escape sequences. - #ifndef _WIN32 - #define BASH_RED "\033[0;31m" - #define BASH_CLEAR "\033[0m" - #else - #define BASH_RED "" - #define BASH_CLEAR "" - #endif - - // Temporary outstream object for detecting duplicate identifiers. - util::PrefixedOutStream outstr(std::cerr, - BASH_RED "[FATAL] " BASH_CLEAR, false, true /* fatal */); - - #undef BASH_RED - #undef BASH_CLEAR - - outstr << "Parameter --" << boostName << " (" << data.alias << ") " - << "is defined multiple times with the same identifiers." - << std::endl; - } - - CLI::Add(std::move(data)); - - // Set some function pointers that we need. - CLI::GetSingleton().functionMap[tname]["DefaultParam"] = - &DefaultParam; - CLI::GetSingleton().functionMap[tname]["OutputParam"] = - &OutputParam; - CLI::GetSingleton().functionMap[tname]["GetPrintableParam"] = - &GetPrintableParam; - CLI::GetSingleton().functionMap[tname]["StringTypeParam"] = - &StringTypeParam; - CLI::GetSingleton().functionMap[tname]["GetParam"] = &GetParam; - CLI::GetSingleton().functionMap[tname]["GetRawParam"] = &GetRawParam; - CLI::GetSingleton().functionMap[tname]["AddToPO"] = &AddToPO; - CLI::GetSingleton().functionMap[tname]["MapParameterName"] = - &MapParameterName; - CLI::GetSingleton().functionMap[tname]["SetParam"] = &SetParam; - CLI::GetSingleton().functionMap[tname]["GetPrintableParamName"] = - &GetPrintableParamName; - CLI::GetSingleton().functionMap[tname]["GetPrintableParamValue"] = - &GetPrintableParamValue; - CLI::GetSingleton().functionMap[tname]["GetAllocatedMemory"] = - &GetAllocatedMemory; - CLI::GetSingleton().functionMap[tname]["DeleteAllocatedMemory"] = - &DeleteAllocatedMemory; - } -}; - -/** - * A static object whose constructor registers program documentation with the - * CLI class. This should not be used outside of CLI itself, and you should use - * the PROGRAM_INFO() macro to declare these objects. Only one ProgramDoc - * object should ever exist. - * - * @see core/util/cli.hpp, mlpack::CLI - */ -class ProgramDoc -{ - public: - /** - * Construct a ProgramDoc object. When constructed, it will register itself - * with CLI. - * - * @param programName Short string representing the name of the program. - * @param documentation Long string containing documentation on how to use the - * program and what it is. No newline characters are necessary; this is - * taken care of by CLI later. - */ - ProgramDoc(const std::string& programName, - const std::string& documentation); - - //! The name of the program. - std::string programName; - //! Documentation for what the program does. - std::string documentation; -}; - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/default_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/default_param.hpp deleted file mode 100644 index b4740dd5c..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/default_param.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @file default_param.hpp - * @author Ryan Curtin - * - * Return the default value of a parameter, depending on its type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_DEFAULT_PARAM_HPP -#define MLPACK_BINDINGS_CLI_DEFAULT_PARAM_HPP - -#include -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Return the default value of an option. This is for regular types. - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0); - -/** - * Return the default value of a vector option. - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0); - -/** - * Return the default value of a string option. - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0); - -/** - * Return the default value of a matrix option, a tuple option, a - * serializable option, or a string option (this returns the default filename, - * or '' if the default is no file). - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::enable_if_c< - arma::is_arma_type::value || - std::is_same>::value>::type* /* junk */ = 0); - -/** - * Return the default value of a model option (this returns the default - * filename, or '' if the default is no file). - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0); - -/** - * Return the default value of an option. This is the function that will be - * placed into the CLI functionMap. - */ -template -void DefaultParam(const util::ParamData& data, - const void* /* input */, - void* output) -{ - std::string* outstr = (std::string*) output; - *outstr = DefaultParamImpl::type>(data); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "default_param_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/default_param_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/default_param_impl.hpp deleted file mode 100644 index 8c1740c1f..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/default_param_impl.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file default_param_impl.hpp - * @author Ryan Curtin - * - * Return the default value of a parameter, depending on its type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_DEFAULT_PARAM_IMPL_HPP -#define MLPACK_BINDINGS_CLI_DEFAULT_PARAM_IMPL_HPP - -#include "default_param.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Return the default value of an option. - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>>::type* /* junk */) -{ - std::ostringstream oss; - oss << boost::any_cast(data.value); - return oss.str(); -} - -/** - * Return the default value of a vector option. - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::enable_if>::type* /* junk */) -{ - // Print each element in an array delimited by square brackets. - std::ostringstream oss; - const T& vector = boost::any_cast(data.value); - oss << "["; - for (size_t i = 0; i < vector.size() - 1; ++i) - oss << vector[i] << " "; - oss << vector[vector.size() - 1] << "]"; - return oss.str(); -} - -/** - * Return the default value of a string option. - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::enable_if>::type*) -{ - const std::string& s = *boost::any_cast(&data.value); - return "'" + s + "'"; -} - -/** - * Return the default value of a matrix option (this returns the default - * filename, or '' if the default is no file). - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::enable_if_c< - arma::is_arma_type::value || - std::is_same>::value>::type* /* junk */) -{ - // Get the filename and return it, or return an empty string. - typedef std::tuple TupleType; - const TupleType& tuple = *boost::any_cast(&data.value); - const std::string& filename = std::get<1>(tuple); - return "'" + filename + "'"; -} - -/** - * Return the default value of a model option (this returns the default - * filename, or '' if the default is no file). - */ -template -std::string DefaultParamImpl( - const util::ParamData& data, - const typename boost::disable_if>::type* /* junk */, - const typename boost::enable_if>::type* /* junk */) -{ - // Get the filename and return it, or return an empty string. - typedef std::tuple TupleType; - const TupleType& tuple = *boost::any_cast(&data.value); - const std::string& filename = std::get<1>(tuple); - return "'" + filename + "'"; -} - - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/delete_allocated_memory.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/delete_allocated_memory.hpp deleted file mode 100644 index 298f05eed..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/delete_allocated_memory.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file delete_allocated_memory.hpp - * @author Ryan Curtin - * - * If any memory has been allocated by the parameter, delete it. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_DELETE_ALLOCATED_MEMORY_HPP -#define MLPACK_BINDINGS_CLI_DELETE_ALLOCATED_MEMORY_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -template -void DeleteAllocatedMemoryImpl( - const util::ParamData& /* d */, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - // Do nothing. -} - -template -void DeleteAllocatedMemoryImpl( - const util::ParamData& /* d */, - const typename boost::enable_if>::type* = 0) -{ - // Do nothing. -} - -template -void DeleteAllocatedMemoryImpl( - const util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // Delete the allocated memory (hopefully we actually own it). - typedef std::tuple TupleType; - delete std::get<0>(*boost::any_cast(&d.value)); -} - -template -void DeleteAllocatedMemory( - const util::ParamData& d, - const void* /* input */, - void* /* output */) -{ - DeleteAllocatedMemoryImpl::type>(d); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/end_program.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/end_program.hpp deleted file mode 100644 index 031c49d5f..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/end_program.hpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @file end_program.hpp - * @author Ryan Curtin - * @author Matthew Amidon - * - * Terminate the program; handle --verbose option; print output parameters. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_END_PROGRAM_HPP -#define MLPACK_BINDINGS_CLI_END_PROGRAM_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Handle command-line program termination. If --help or --info was passed, we - * won't make it here, so we don't have to write any contingencies for that. - */ -inline void EndProgram() -{ - // Stop the CLI timers. - CLI::GetSingleton().timer.StopAllTimers(); - - // Print any output. - const std::map& parameters = CLI::Parameters(); - std::map::const_iterator it = - parameters.begin(); - while (it != parameters.end()) - { - const util::ParamData& d = it->second; - if (!d.input) - CLI::GetSingleton().functionMap[d.tname]["OutputParam"](d, NULL, NULL); - - ++it; - } - - if (CLI::HasParam("verbose")) - { - Log::Info << std::endl << "Execution parameters:" << std::endl; - - // Print out all the values. - it = parameters.begin(); - while (it != parameters.end()) - { - // Now, figure out what type it is, and print it. - // We can handle strings, ints, bools, floats, doubles. - const util::ParamData& data = it->second; - std::string boostName; - CLI::GetSingleton().functionMap[data.tname]["MapParameterName"](data, - NULL, (void*) &boostName); - Log::Info << " " << boostName << ": "; - - std::string printableParam; - CLI::GetSingleton().functionMap[data.tname]["GetPrintableParam"](data, - NULL, (void*) &printableParam); - Log::Info << printableParam << std::endl; - - ++it; - } - - Log::Info << "Program timers:" << std::endl; - for (auto it2 : CLI::GetSingleton().timer.GetAllTimers()) - { - Log::Info << " " << it2.first << ": "; - CLI::GetSingleton().timer.PrintTimer(it2.first); - } - } - - // Lastly clean up any memory. If we are holding any pointers, then we "own" - // them. But we may hold the same pointer twice, so we have to be careful to - // not delete it multiple times. - std::unordered_map memoryAddresses; - it = parameters.begin(); - while (it != parameters.end()) - { - const util::ParamData& data = it->second; - - void* result; - CLI::GetSingleton().functionMap[data.tname]["GetAllocatedMemory"](data, - NULL, (void*) &result); - if (result != NULL && memoryAddresses.count(result) == 0) - memoryAddresses[result] = &data; - - ++it; - } - - // Now we have all the unique addresses that need to be deleted. - std::unordered_map::const_iterator it2; - it2 = memoryAddresses.begin(); - while (it2 != memoryAddresses.end()) - { - const util::ParamData& data = *(it2->second); - - CLI::GetSingleton().functionMap[data.tname]["DeleteAllocatedMemory"](data, - NULL, NULL); - - ++it2; - } -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_allocated_memory.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_allocated_memory.hpp deleted file mode 100644 index 03980bdb1..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_allocated_memory.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @file get_allocated_memory.hpp - * @author Ryan Curtin - * - * If the parameter has a type that may need to be deleted, return the address - * of that object. Otherwise return NULL. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_ALLOCATED_MEMORY_HPP -#define MLPACK_BINDINGS_CLI_GET_ALLOCATED_MEMORY_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -template -void* GetAllocatedMemory( - const util::ParamData& /* d */, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - return NULL; -} - -template -void* GetAllocatedMemory( - const util::ParamData& /* d */, - const typename boost::enable_if>::type* = 0) -{ - return NULL; -} - -template -void* GetAllocatedMemory( - const util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // Here we have a model, which is a tuple, and we need the address of the - // memory. - typedef std::tuple TupleType; - return std::get<0>(*boost::any_cast(&d.value)); -} - -template -void GetAllocatedMemory(const util::ParamData& d, - const void* /* input */, - void* output) -{ - *((void**) output) = - GetAllocatedMemory::type>(d); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_param.hpp deleted file mode 100644 index 1580635f7..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_param.hpp +++ /dev/null @@ -1,143 +0,0 @@ -/** - * @file get_param.hpp - * @author Ryan Curtin - * - * Use template metaprogramming to get the right type of parameter. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_PARAM_HPP -#define MLPACK_BINDINGS_CLI_GET_PARAM_HPP - -#include -#include "parameter_type.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * This overload is called when nothing special needs to happen to the name of - * the parameter. - * - * @param d ParamData object to get parameter value from. - */ -template -T& GetParam( - util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0) -{ - // No mapping is needed, so just cast it directly. - return *boost::any_cast(&d.value); -} - -/** - * Return a matrix parameter. - * - * @param d ParamData object to get parameter value from. - */ -template -T& GetParam( - util::ParamData& d, - const typename boost::enable_if>::type* = 0) -{ - // If the matrix is an input matrix, we have to load the matrix. 'value' - // contains the filename. It's possible we could load empty matrices many - // times, but I am not bothered by that---it shouldn't be something that - // happens. - typedef std::tuple::type> TupleType; - TupleType& tuple = *boost::any_cast(&d.value); - const std::string& value = std::get<1>(tuple); - T& matrix = std::get<0>(tuple); - if (d.input && !d.loaded) - { - // Call correct data::Load() function. - if (arma::is_Row::value || arma::is_Col::value) - data::Load(value, matrix, true); - else - data::Load(value, matrix, true, !d.noTranspose); - d.loaded = true; - } - - return matrix; -} - -/** - * Return a matrix/dataset info parameter. - * - * @param d ParamData object to get parameter value from. - */ -template -T& GetParam( - util::ParamData& d, - const typename boost::enable_if>>::type* = 0) -{ - // If this is an input parameter, we need to load both the matrix and the - // dataset info. - typedef std::tuple TupleType; - TupleType* tuple = boost::any_cast(&d.value); - const std::string& value = std::get<1>(*tuple); - T& t = std::get<0>(*tuple); - if (d.input && !d.loaded) - { - data::Load(value, std::get<1>(t), std::get<0>(t), true, !d.noTranspose); - d.loaded = true; - } - - return t; -} - -/** - * Return a serializable object. - * - * @param d ParamData object to get parameter value from. - */ -template -T*& GetParam( - util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // If the model is an input model, we have to load it from file. 'value' - // contains the filename. - typedef std::tuple TupleType; - TupleType* tuple = boost::any_cast(&d.value); - const std::string& value = std::get<1>(*tuple); - if (d.input && !d.loaded) - { - T* model = new T(); - data::Load(value, "model", *model, true); - d.loaded = true; - std::get<0>(*tuple) = model; - } - return std::get<0>(*tuple); -} - -/** - * Return a parameter casted to the given type. Type checking does not happen - * here! - * - * @param d Parameter information. - * @param input Unused parameter. - * @param output Place to store pointer to value. - */ -template -void GetParam(const util::ParamData& d, const void* /* input */, void* output) -{ - // Cast to the correct type. - *((T**) output) = &GetParam::type>( - const_cast(d)); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param.hpp deleted file mode 100644 index 7f5074288..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file get_printable_param.hpp - * @author Ryan Curtin - * - * Print the parameter to stdout, using template metaprogramming to enforce - * different behavior for different parameter types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_HPP -#define MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_HPP - -#include -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Print an option. - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0); - -/** - * Print a vector option, with spaces between it. - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename std::enable_if::value>::type* = 0); - -/** - * Print a matrix/tuple option (this just prints the filename). - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename std::enable_if::value || - std::is_same>::value>::type* = 0); - -/** - * Print a model option (this just prints the filename). - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0); - -/** - * Print an option into a std::string. This should print a short, one-line - * representation of the object. The string will be stored in the output - * pointer. - */ -template -void GetPrintableParam(const util::ParamData& data, - const void* /* input */, - void* output) -{ - *((std::string*) output) = - GetPrintableParam::type>(data); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "get_printable_param_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_impl.hpp deleted file mode 100644 index 60177ca10..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_impl.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file get_printable_param_impl.hpp - * @author Ryan Curtin - * - * Implementation of parameter printing functions. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_IMPL_HPP -#define MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_IMPL_HPP - -#include "get_printable_param.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -//! Print an option. -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>>::type* /* junk */) -{ - std::ostringstream oss; - oss << boost::any_cast(data.value); - return oss.str(); -} - -//! Print a vector option. -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename std::enable_if::value>::type* - /* junk */) -{ - const T& t = boost::any_cast(data.value); - - std::ostringstream oss; - for (size_t i = 0; i < t.size(); ++i) - oss << t[i] << " "; - return oss.str(); -} - -//! Print a matrix/tuple option (this just prints the filename). -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename std::enable_if::value || - std::is_same>::value>::type* /* junk */) -{ - // Extract the string from the tuple that's being held. - typedef std::tuple::type> TupleType; - const TupleType* tuple = boost::any_cast(&data.value); - - std::ostringstream oss; - oss << std::get<1>(*tuple); - return oss.str(); -} - -//! Print a model option (this just prints the filename). -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* /* junk */, - const typename boost::enable_if>::type* /* junk */) -{ - // Extract the string from the tuple that's being held. - typedef std::tuple::type> TupleType; - const TupleType* tuple = boost::any_cast(&data.value); - - std::ostringstream oss; - oss << std::get<1>(*tuple); - return oss.str(); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_name.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_name.hpp deleted file mode 100644 index cd3f9139e..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_name.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @file get_printable_param_name.hpp - * @author Ryan Curtin - * - * Return the parameter name that the user would specify on the command line, - * with different behavior for different parameter types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_NAME_HPP -#define MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_NAME_HPP - -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Get the parameter name for a type that has no special handling. - */ -template -std::string GetPrintableParamName( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0); - -/** - * Get the parameter name for a matrix type (where the user has to pass the file - * that holds the matrix). - */ -template -std::string GetPrintableParamName( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0); - -/** - * Get the parameter name for a serializable model type (where the user has to - * pass the file that holds the matrix). - */ -template -std::string GetPrintableParamName( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0); - -/** - * Get the parameter name for a mapped matrix type (where the user has to pass - * the file that holds the matrix). - */ -template -std::string GetPrintableParamName( - const util::ParamData& data, - const typename boost::enable_if>>::type* = 0); - -/** - * Get the parameter's name as seen by the user. - */ -template -void GetPrintableParamName( - const util::ParamData& d, - const void* /* input */, - void* output) -{ - *((std::string*) output) = - GetPrintableParamName::type>(d); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "get_printable_param_name_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_name_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_name_impl.hpp deleted file mode 100644 index ae2467a78..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_name_impl.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file get_printable_param_name_impl.hpp - * @author Ryan Curtin - * - * Return the parameter name that the user would specify on the command line, - * with different behavior for different parameter types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_NAME_IMPL_HPP -#define MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_NAME_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Get the parameter name for a type that has no special handling. - */ -template -std::string GetPrintableParamName( - const util::ParamData& data, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>>::type*) -{ - return "--" + data.name; -} - -/** - * Get the parameter name for a matrix type (where the user has to pass the file - * that holds the matrix). - */ -template -std::string GetPrintableParamName( - const util::ParamData& data, - const typename boost::enable_if>::type*) -{ - return "--" + data.name + "_file"; -} - -/** - * Get the parameter name for a serializable model type (where the user has to - * pass the file that holds the matrix). - */ -template -std::string GetPrintableParamName( - const util::ParamData& data, - const typename boost::disable_if>::type*, - const typename boost::enable_if>::type*) -{ - return "--" + data.name + "_file"; -} - -/** - * Get the parameter name for a mapped matrix type (where the user has to pass - * the file that holds the matrix). - */ -template -std::string GetPrintableParamName( - const util::ParamData& data, - const typename boost::enable_if>>::type*) -{ - return "--" + data.name + "_file"; -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_value.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_value.hpp deleted file mode 100644 index 04e3849c4..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_value.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file get_printable_param_value.hpp - * @author Ryan Curtin - * - * Given a parameter value, print what the user might actually specify on the - * command line. Basically this adds ".csv" to types where data must be loaded. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_VALUE_HPP -#define MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_VALUE_HPP - -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Get the parameter name for a type that has no special handling. - */ -template -std::string GetPrintableParamValue( - const util::ParamData& data, - const std::string& value, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0); - -/** - * Get the parameter name for a matrix type (where the user has to pass the file - * that holds the matrix). - */ -template -std::string GetPrintableParamValue( - const util::ParamData& data, - const std::string& value, - const typename boost::enable_if>::type* = 0); - -/** - * Get the parameter name for a serializable model type (where the user has to - * pass the file that holds the matrix). - */ -template -std::string GetPrintableParamValue( - const util::ParamData& data, - const std::string& value, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0); - -/** - * Get the parameter name for a mapped matrix type (where the user has to pass - * the file that holds the matrix). - */ -template -std::string GetPrintableParamValue( - const util::ParamData& data, - const std::string& value, - const typename boost::enable_if>>::type* = 0); - -/** - * Get the parameter's name as seen by the user. - */ -template -void GetPrintableParamValue( - const util::ParamData& d, - const void* input, - void* output) -{ - *((std::string*) output) = - GetPrintableParamValue::type>(d, - *((std::string*) input)); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "get_printable_param_value_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_value_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_value_impl.hpp deleted file mode 100644 index 5a013569f..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_printable_param_value_impl.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file get_printable_param_value_impl.hpp - * @author Ryan Curtin - * - * Return the parameter value that the user would specify on the command line - * depending on the type of the option. Basically this adds ".csv" to types - * that need to be loaded. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_VALUE_IMPL_HPP -#define MLPACK_BINDINGS_CLI_GET_PRINTABLE_PARAM_VALUE_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Get the parameter name for a type that has no special handling. - */ -template -std::string GetPrintableParamValue( - const util::ParamData& /* data */, - const std::string& input, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>>::type*) -{ - return input; -} - -/** - * Get the parameter name for a matrix type (where the user has to pass the file - * that holds the matrix). - */ -template -std::string GetPrintableParamValue( - const util::ParamData& /* data */, - const std::string& input, - const typename boost::enable_if>::type*) -{ - return input + ".csv"; -} - -/** - * Get the parameter name for a serializable model type (where the user has to - * pass the file that holds the matrix). - */ -template -std::string GetPrintableParamValue( - const util::ParamData& /* data */, - const std::string& input, - const typename boost::disable_if>::type*, - const typename boost::enable_if>::type*) -{ - return input + ".bin"; -} - -/** - * Get the parameter name for a mapped matrix type (where the user has to pass - * the file that holds the matrix). - */ -template -std::string GetPrintableParamValue( - const util::ParamData& /* data */, - const std::string& input, - const typename boost::enable_if>>::type*) -{ - return input + ".arff"; -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/get_raw_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/get_raw_param.hpp deleted file mode 100644 index cbd0b7725..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/get_raw_param.hpp +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @file get_raw_param.hpp - * @author Ryan Curtin - * - * Use template metaprogramming to get the right type of parameter, but without - * any processing. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_RAW_PARAM_HPP -#define MLPACK_BINDINGS_CLI_GET_RAW_PARAM_HPP - -#include -#include "parameter_type.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * This overload is called when nothing special needs to happen to the name of - * the parameter. - */ -template -T& GetRawParam( - util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0) -{ - // No mapping is needed, so just cast it directly. - return *boost::any_cast(&d.value); -} - -/** - * Return a matrix parameter. - */ -template -T& GetRawParam( - util::ParamData& d, - const typename boost::enable_if_c< - arma::is_arma_type::value || - std::is_same>::value>::type* = 0) -{ - // Don't load the matrix. - typedef std::tuple TupleType; - T& value = std::get<0>(*boost::any_cast(&d.value)); - return value; -} - -/** - * Return the name of a model parameter. - */ -template -T*& GetRawParam( - util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // Don't load the model. - typedef std::tuple TupleType; - T*& value = std::get<0>(*boost::any_cast(&d.value)); - return value; -} - -/** - * Return a parameter casted to the given type. Type checking does not happen - * here! - * - * @param d Parameter information. - * @param input Unused parameter. - * @param output Place to store pointer to value. - */ -template -void GetRawParam(const util::ParamData& d, - const void* /* input */, - void* output) -{ - // Cast to the correct type. - *((T**) output) = &GetRawParam::type>( - const_cast(d)); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/map_parameter_name.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/map_parameter_name.hpp deleted file mode 100644 index 2d6583974..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/map_parameter_name.hpp +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @file map_parameter_name.hpp - * @author Ryan Curtin - * - * Map a parameter name to what it seen by boost::program_options using template - * metaprogramming. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_MAP_PARAMETER_NAME_HPP -#define MLPACK_BINDINGS_CLI_MAP_PARAMETER_NAME_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * If needed, map the parameter name to the name that is used by - * boost::program_options. This overload simply returns the same name, so it is - * used for primitive types. - */ -template -std::string MapParameterName( - const std::string& identifier, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0) -{ - return identifier; -} - -/** - * Map the parameter name to the name that is used by boost::program_options. - * This overload addresses matrices and models, where the parameter name has - * "_file" appended to it (since a filename will be provided). - */ -template -std::string MapParameterName( - const std::string& identifier, - const typename boost::enable_if_c< - arma::is_arma_type::value || - std::is_same>::value || - data::HasSerialize::value>::type* /* junk */ = 0) -{ - return identifier + "_file"; -} - -/** - * Map the parameter name to the name seen by boost::program_options. - * - * @param d Parameter data. - * @param input Unused parameter. - * @param output Pointer to std::string that will hold the mapped name. - */ -template -void MapParameterName(const util::ParamData& d, - const void* /* input */, - void* output) -{ - // Store the mapped name in the output pointer, which is actually a string - // pointer. - *((std::string*) output) = - MapParameterName::type>(d.name); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/output_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/output_param.hpp deleted file mode 100644 index cc221b491..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/output_param.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file output_param.hpp - * @author Ryan Curtin - * - * Output a parameter of different types using template metaprogramming. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_OUTPUT_PARAM_HPP -#define MLPACK_BINDINGS_CLI_OUTPUT_PARAM_HPP - -#include -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Output an option (print to stdout). - */ -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0); - -/** - * Output a vector option (print to stdout). - */ -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0); - -/** - * Output a matrix option (this saves it to the given file). - */ -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0); - -/** - * Output a serializable class option (this saves it to the given file). - */ -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0); - -/** - * Output a mapped dataset. - */ -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::enable_if>>::type* = 0); - -/** - * Output an option. This is the function that will be called by the CLI - * module. - */ -template -void OutputParam(const util::ParamData& data, - const void* /* input */, - void* /* output */) -{ - OutputParamImpl::type>(data); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "output_param_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/output_param_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/output_param_impl.hpp deleted file mode 100644 index c19b6d0aa..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/output_param_impl.hpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @file output_param_impl.hpp - * @author Ryan Curtin - * - * Implementations of functions to output parameters of different types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_OUTPUT_PARAM_IMPL_HPP -#define MLPACK_CORE_UTIL_OUTPUT_PARAM_IMPL_HPP - -#include "output_param.hpp" -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -//! Output an option. -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>>::type* /* junk */) -{ - std::cout << data.name << ": " << *boost::any_cast(&data.value) - << std::endl; -} - -//! Output a vector option. -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::enable_if>::type* /* junk */) -{ - std::cout << data.name << ": "; - const T& t = *boost::any_cast(&data.value); - for (size_t i = 0; i < t.size(); ++i) - std::cout << t[i] << " "; - std::cout << std::endl; -} - -//! Output a matrix option (this saves it to file). -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::enable_if>::type* /* junk */) -{ - typedef std::tuple TupleType; - const T& output = std::get<0>(*boost::any_cast(&data.value)); - const std::string& filename = - std::get<1>(*boost::any_cast(&data.value)); - - if (output.n_elem > 0 && filename != "") - { - if (arma::is_Row::value || arma::is_Col::value) - data::Save(filename, output, false); - else - data::Save(filename, output, false, !data.noTranspose); - } -} - -//! Output a model option (this saves it to file). -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::disable_if>::type* /* junk */, - const typename boost::enable_if>::type* /* junk */) -{ - // The const cast is necessary here because Serialize() can't ever be marked - // const. In this case we can assume it though, since we will be saving and - // not loading. - typedef std::tuple TupleType; - T*& output = const_cast(std::get<0>(*boost::any_cast( - &data.value))); - const std::string& filename = - std::get<1>(*boost::any_cast(&data.value)); - - if (filename != "") - data::Save(filename, "model", *output); -} - -//! Output a mapped dataset. -template -void OutputParamImpl( - const util::ParamData& data, - const typename boost::enable_if>>::type* /* junk */) -{ - // Output the matrix with the mappings. - typedef std::tuple TupleType; - const T& tuple = std::get<0>(*boost::any_cast(&data.value)); - const std::string& filename = - std::get<1>(*boost::any_cast(&data.value)); - const arma::mat& matrix = std::get<1>(tuple); - - // The mapping isn't taken into account. We should write a data::Save() - // overload for this. - if (filename != "") - data::Save(filename, matrix, false, !data.noTranspose); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/parameter_type.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/parameter_type.hpp deleted file mode 100644 index aecdda41f..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/parameter_type.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file parameter_type.hpp - * @author Ryan Curtin - * - * Template metaprogramming structures to find the type (as seen by - * boost::program_options) of a particular option type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_PARAMETER_TYPE_HPP -#define MLPACK_BINDINGS_CLI_PARAMETER_TYPE_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -// Default: HasSerialize = false. -template -struct ParameterTypeDeducer -{ - typedef T type; -}; - -// If we have a serialize() function, then the type is a string. -template -struct ParameterTypeDeducer -{ - typedef std::string type; -}; - -/** - * Utility struct to return the type that boost::program_options should accept - * for a given input type. In general, there is no change from the input type, - * but in some cases this may be another type. - */ -template -struct ParameterType -{ - typedef typename ParameterTypeDeducer::value, T>::type - type; -}; - -/** - * For vector types, boost::program_options will accept a std::string, not an - * arma::Col (since it is not clear how to specify a vector on the - * command-line). - */ -template -struct ParameterType> -{ - typedef std::string type; -}; - -/** - * For row vector types, boost::program_options will accept a std::string, not - * an - * arma::Row (since it is not clear how to specify a vector on the - * command-line). - */ -template -struct ParameterType> -{ - typedef std::string type; -}; - -/** - * For matrix types, boost::program_options will accept a std::string, not an - * arma::mat (since it is not clear how to specify a matrix on the - * command-line). - */ -template -struct ParameterType> -{ - typedef std::string type; -}; - -/** - * For matrix+dataset info types, we should accept a std::string. - */ -template -struct ParameterType, arma::Mat>> -{ - typedef std::string type; -}; - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/parse_command_line.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/parse_command_line.hpp deleted file mode 100644 index db75573d4..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/parse_command_line.hpp +++ /dev/null @@ -1,201 +0,0 @@ -/** - * @file parse_command_line.hpp - * @author Ryan Curtin - * @author Matthew Amidon - * - * Parse the command line options. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_PARSE_COMMAND_LINE_HPP -#define MLPACK_BINDINGS_CLI_PARSE_COMMAND_LINE_HPP - -#include -#include -#include "print_help.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -// Add default parameters that are included in every program. -PARAM_FLAG("help", "Default help info.", "h"); -PARAM_STRING_IN("info", "Get help on a specific module or option.", "", ""); -PARAM_FLAG("verbose", "Display informational messages and the full list of " - "parameters and timers at the end of execution.", "v"); -PARAM_FLAG("version", "Display the version of mlpack.", "V"); - -/** - * Parse the command line, setting all of the options inside of the CLI object - * to their appropriate given values. - */ -void ParseCommandLine(int argc, char** argv) -{ - // First, we need to build the boost::program_options variables for parsing. - using namespace boost::program_options; - options_description desc; - variables_map vmap; - - // Go through list of options in order to add them. - std::map& parameters = CLI::Parameters(); - typedef std::map::const_iterator IteratorType; - std::map boostNameMap; - for (IteratorType it = parameters.begin(); it != parameters.end(); ++it) - { - // Add the parameter to desc. - const util::ParamData& d = it->second; - CLI::GetSingleton().functionMap[d.tname]["AddToPO"](d, NULL, - (void*) &desc); - - // Generate the name the user passes on the command line. - std::string boostName; - CLI::GetSingleton().functionMap[d.tname]["MapParameterName"](d, NULL, - (void*) &boostName); - boostNameMap[boostName] = d.name; - } - - // Mark that we did parsing. - CLI::GetSingleton().didParse = true; - - // Parse the command line, then place the values in the right place. - try - { - basic_parsed_options bpo(parse_command_line(argc, argv, desc)); - - // Iterate over all the options, looking for duplicate parameters. If we - // find any, remove the duplicates. Note that vector options can have - // duplicates, so we check for those with max_tokens(). - for (size_t i = 0; i < bpo.options.size(); ++i) - { - for (size_t j = i + 1; j < bpo.options.size(); ++j) - { - if ((bpo.options[i].string_key == bpo.options[j].string_key) && - (desc.find(bpo.options[i].string_key, - false).semantic()->max_tokens() <= 1)) - { - // If a duplicate is found, check to see if either one has a value. - if (bpo.options[i].value.size() == 0 && - bpo.options[j].value.size() == 0) - { - // If neither has a value, we'll consider it a duplicate flag and - // remove the duplicate. It's important to not break out of this - // loop because there might be another duplicate later on in the - // vector. - bpo.options.erase(bpo.options.begin() + j); - --j; // Fix the index. - } - else - { - // If one or both has a value, produce an error and politely - // terminate. We pull the name from the original_tokens, rather - // than from the string_key, because the string_key is the parameter - // after aliases have been expanded. - Log::Fatal << "\"" << bpo.options[j].original_tokens[0] << "\" is " - << "defined multiple times." << std::endl; - } - } - } - } - - store(bpo, vmap); - } - catch (std::exception& ex) - { - Log::Fatal << "Caught exception from parsing command line: " << ex.what() - << std::endl; - } - - // Now iterate through the filled vmap, and overwrite default values with - // anything that's found on the command line. - for (variables_map::iterator i = vmap.begin(); i != vmap.end(); ++i) - { - // There is not a possibility of an unknown option, since - // boost::program_options would have already thrown an exception. Because - // some names may be mapped, we have to look through each ParamData object - // and get its boost name. - const std::string identifier = boostNameMap[i->first]; - util::ParamData& param = parameters[identifier]; - param.wasPassed = true; - CLI::GetSingleton().functionMap[param.tname]["SetParam"](param, - (void*) &vmap[i->first].value(), NULL); - } - - // Flush the buffer, make sure changes are propagated to vmap. - notify(vmap); - - // If the user specified any of the default options (--help, --version, or - // --info), handle those. - - // --version is prioritized over --help. - if (CLI::HasParam("version")) - { - std::cout << CLI::GetSingleton().ProgramName() << ": part of " - << util::GetVersion() << "." << std::endl; - exit(0); // Don't do anything else. - } - - // Default help message. - if (CLI::HasParam("help")) - { - Log::Info.ignoreInput = false; - PrintHelp(); - exit(0); // The user doesn't want to run the program, he wants help. - } - - // Info on a specific parameter. - if (CLI::HasParam("info")) - { - Log::Info.ignoreInput = false; - std::string str = CLI::GetParam("info"); - - // The info node should always be there, but the user may not have specified - // anything. - if (str != "") - { - PrintHelp(str); - exit(0); - } - - // Otherwise just print the generalized help. - PrintHelp(); - exit(0); - } - - // Print whether or not we have debugging symbols. This won't show anything - // if we have not compiled in debugging mode. - Log::Debug << "Compiled with debugging symbols." << std::endl; - - if (CLI::HasParam("verbose")) - { - // Give [INFO ] output. - Log::Info.ignoreInput = false; - } - - // Now, issue an error if we forgot any required options. - for (std::map::const_iterator iter = - parameters.begin(); iter != parameters.end(); ++iter) - { - const util::ParamData d = iter->second; - if (d.required) - { - const std::string boostName; - CLI::GetSingleton().functionMap[d.tname]["MapParameterName"](d, NULL, - (void*) &boostName); - - if (!vmap.count(boostName)) - { - Log::Fatal << "Required option --" << boostName << " is undefined." - << std::endl; - } - } - } -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/print_doc_functions.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/print_doc_functions.hpp deleted file mode 100644 index cfc024b2c..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/print_doc_functions.hpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file print_doc_functions.hpp - * @author Ryan Curtin - * - * This will generate a string representing what a user should type to invoke a - * given option. For the command-line bindings, this will generate strings like - * '--param_name=x' or '--param_name'. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_PRINT_DOC_FUNCTIONS_HPP -#define MLPACK_BINDINGS_CLI_PRINT_DOC_FUNCTIONS_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Given a parameter type, print the corresponding value. - */ -template -inline std::string PrintValue(const T& value, bool quotes); - -/** - * Print a dataset type parameter (add .csv and return). - */ -inline std::string PrintDataset(const std::string& dataset); - -/** - * Print a model type parameter (add .bin and return). - */ -inline std::string PrintModel(const std::string& model); - -/** - * Base case for recursion. - */ -inline std::string ProcessOptions(); - -/** - * Print an option for a command-line argument. - */ -template -std::string ProcessOptions(const std::string& paramName, - const T& value, - Args... args); - -/** - * Given a program name and arguments for it, print what its invocation would - * be. - */ -template -std::string ProgramCall(const std::string& programName, Args... args); - -/** - * Print what a user would type to invoke the given option name. Note that the - * name *must* exist in the CLI module. (Note that because of the way - * ProgramInfo is structured, this doesn't mean that all of the PARAM_*() - * declarataions need to come before the PROGRAM_INFO() declaration.) - */ -inline std::string ParamString(const std::string& paramName); - -/** - * Return whether or not a runtime check on parameters should be ignored. We - * don't ignore any runtime checks for CLI bindings, so this always returns - * false. - */ -template -inline bool IgnoreCheck(const T& /* t */) { return false; } - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "print_doc_functions_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/print_doc_functions_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/print_doc_functions_impl.hpp deleted file mode 100644 index 0f37e7d5e..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/print_doc_functions_impl.hpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @file print_doc_functions_impl.hpp - * @author Ryan Curtin - * - * This will generate a string representing what a user should type to invoke a - * given option. For the command-line bindings, this will generate strings like - * '--param_name=x' or '--param_name'. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_PRINT_DOC_FUNCTIONS_IMPL_HPP -#define MLPACK_BINDINGS_CLI_PRINT_DOC_FUNCTIONS_IMPL_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Given a parameter type, print the corresponding value. - */ -template -inline std::string PrintValue(const T& value, bool quotes) -{ - std::ostringstream oss; - if (quotes) - oss << "'"; - oss << value; - if (quotes) - oss << "'"; - return oss.str(); -} - -/** - * Print a dataset type parameter (add .csv and return). - */ -inline std::string PrintDataset(const std::string& dataset) -{ - return "'" + dataset + ".csv'"; -} - -/** - * Print a model type parameter (add .bin and return). - */ -inline std::string PrintModel(const std::string& model) -{ - return "'" + model + ".bin'"; -} - -// Base case for recursion. -inline std::string ProcessOptions() { return ""; } - -/** - * Print an option for a command-line argument. - */ -template -std::string ProcessOptions(const std::string& paramName, - const T& value, - Args... args) -{ - // See if it is part of the program. - std::string result = ""; - if (CLI::Parameters().count(paramName) > 0) - { - const util::ParamData& d = CLI::Parameters()[paramName]; - - std::string name; - CLI::GetSingleton().functionMap[d.tname]["GetPrintableParamName"](d, NULL, - (void*) &name); - - std::ostringstream ossValue; - ossValue << value; - std::string rawValue = ossValue.str(); - std::string fullValue; - CLI::GetSingleton().functionMap[d.tname]["GetPrintableParamValue"](d, - (void*) &rawValue, (void*) &fullValue); - - std::ostringstream oss; - if (d.tname != TYPENAME(bool)) - oss << name << " " << fullValue; - else - oss << name; - result = oss.str(); - } - else - { - throw std::runtime_error("Unknown parameter '" + paramName + "' " + - "encountered while assembling documentation! Check PROGRAM_INFO() " + - "declaration."); - } - - std::string rest = ProcessOptions(args...); - if (rest != "") - result += " " + rest; - - return result; -} - -/** - * Given a program name and arguments for it, print what its invocation would - * be. - */ -template -std::string ProgramCall(const std::string& programName, Args... args) -{ - return util::HyphenateString("$ " + programName + " " + - ProcessOptions(args...), 2); -} - -/** - * Print what a user would type to invoke the given option name. Note that the - * name *must* exist in the CLI module. (Note that because of the way - * ProgramInfo is structured, this doesn't mean that all of the PARAM_*() - * declarataions need to come before the PROGRAM_INFO() declaration.) - */ -inline std::string ParamString(const std::string& paramName) -{ - // Return the correct parameter name. - if (CLI::Parameters().count(paramName) > 0) - { - util::ParamData& d = CLI::Parameters()[paramName]; - - std::string output; - CLI::GetSingleton().functionMap[d.tname]["GetPrintableParamName"](d, NULL, - (void*) &output); - // Is there an alias? - std::string alias = ""; - if (d.alias != '\0') - alias = " (-" + std::string(1, d.alias) + ")"; - - return "'" + output + alias + "'"; - } - else - { - throw std::runtime_error("Parameter '" + paramName + "' not known! Check " - "PROGRAM_INFO() definition."); - } -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/print_help.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/print_help.hpp deleted file mode 100644 index e2c1d7db5..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/print_help.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * @file print_help.hpp - * @author Ryan Curtin - * - * Print help for a command-line program. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_PRINT_HELP_HPP -#define MLPACK_BINDINGS_CLI_PRINT_HELP_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Print the help for the given parameter. If no parameter is specified, then - * help will be printed for all parameters. - * - * @param param Parameter name to print help for. - */ -void PrintHelp(const std::string& param = ""); - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/set_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/set_param.hpp deleted file mode 100644 index 8370a62b5..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/set_param.hpp +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file get_param.hpp - * @author Ryan Curtin - * - * Use template metaprogramming to get the right type of parameter. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_SET_PARAM_HPP -#define MLPACK_BINDINGS_CLI_SET_PARAM_HPP - -#include -#include "parameter_type.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * This overload is called when nothing special needs to happen to the name of - * the parameter. - */ -template -void SetParam( - util::ParamData& d, - const boost::any& value, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - // No mapping is needed. - d.value = value; -} - -/** - * This overload is called to set a boolean. - */ -template -void SetParam( - util::ParamData& d, - const boost::any& /* value */, - const typename boost::enable_if>::type* = 0) -{ - // Force set to the value of whether or not this was passed. - d.value = d.wasPassed; -} - -/** - * Set a matrix parameter, a matrix/dataset info parameter, or a serializable - * object. These set the filename referring to the parameter. - */ -template -void SetParam( - util::ParamData& d, - const boost::any& value, - const typename std::enable_if::value || - std::is_same>::value>::type* = 0) -{ - // We're setting the string filename. - typedef std::tuple::type> TupleType; - TupleType& tuple = *boost::any_cast(&d.value); - std::get<1>(tuple) = boost::any_cast(value); -} - -/** - * Set a serializable object. This sets the filename referring to the - * parameter. - */ -template -void SetParam( - util::ParamData& d, - const boost::any& value, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // We're setting the string filename. - typedef std::tuple::type> TupleType; - TupleType& tuple = *boost::any_cast(&d.value); - std::get<1>(tuple) = boost::any_cast(value); -} - -/** - * Return a parameter casted to the given type. Type checking does not happen - * here! - * - * @param d Parameter information. - * @param input Unused parameter. - * @param output Place to store pointer to value. - */ -template -void SetParam(const util::ParamData& d, const void* input, void* /* output */) -{ - SetParam::type>( - const_cast(d), *((boost::any*) input)); -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/string_type_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/string_type_param.hpp deleted file mode 100644 index 28caa8991..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/string_type_param.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @file string_type_param.hpp - * @author Ryan Curtin - * - * Given a util::ParamData object, return a string containing the type of the input - * parameter as given on the command-line. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_STRING_TYPE_PARAM_HPP -#define MLPACK_BINDINGS_CLI_STRING_TYPE_PARAM_HPP - -#include -#include -#include - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Return a string containing the type of the parameter. - */ -template -std::string StringTypeParamImpl( - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0); - -/** - * Return a string containing the type of the parameter, for vector options. - */ -template -std::string StringTypeParamImpl( - const typename boost::enable_if>::type* = 0); - -/** - * Return a string containing the type of the parameter, - */ -template -std::string StringTypeParamImpl( - const typename boost::enable_if>::type* = 0); - -/** - * Return a string containing the type of a parameter. This overload is used if - * we don't have a primitive type. - */ -template -void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output) -{ - std::string* outstr = (std::string*) output; - *outstr = StringTypeParamImpl(); -} - -//! Return "int". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output); - -//! Return "bool". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output); - -//! Return "string". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output); - -//! Return "float". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output); - -//! Return "double". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output); - -//! Return "string"; -template<> -inline void StringTypeParam>( - const util::ParamData& /* data */, - const void* /* input */, - void* output); - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "string_type_param_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/cli/string_type_param_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/cli/string_type_param_impl.hpp deleted file mode 100644 index 01065086e..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/cli/string_type_param_impl.hpp +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @file string_type_param_impl.hpp - * @author Ryan Curtin - * - * Implementations of StringTypeParam(). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_STRING_TYPE_PARAM_IMPL_HPP -#define MLPACK_BINDINGS_CLI_STRING_TYPE_PARAM_IMPL_HPP - -#include "string_type_param.hpp" - -namespace mlpack { -namespace bindings { -namespace cli { - -/** - * Return a string containing the type of the parameter. - */ -template -std::string StringTypeParamImpl( - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */) -{ - // Don't know what type this is. - return "unknown"; -} - -/** - * Return a string containing the type of the parameter, for vector options. - */ -template -std::string StringTypeParamImpl( - const typename boost::enable_if>::type* /* junk */) -{ - return "vector"; -} - -/** - * Return a string containing the type of the parameter, - */ -template -std::string StringTypeParamImpl( - const typename boost::enable_if>::type* /* junk */) -{ - return "string"; -} - -//! Return "int". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output) -{ - std::string* outstr = (std::string*) output; - *outstr = "int"; -} - -//! Return "bool". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output) -{ - std::string* outstr = (std::string*) output; - *outstr = "bool"; -} - -//! Return "string". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output) -{ - std::string* outstr = (std::string*) output; - *outstr = "string"; -} - -//! Return "float". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output) -{ - std::string* outstr = (std::string*) output; - *outstr = "float"; -} - -//! Return "double". -template<> -inline void StringTypeParam(const util::ParamData& /* data */, - const void* /* input */, - void* output) -{ - std::string* outstr = (std::string*) output; - *outstr = "double"; -} - -//! Return "string"; -template<> -inline void StringTypeParam>( - const util::ParamData& /* data */, - const void* /* input */, - void* output) -{ - std::string* outstr = (std::string*) output; - *outstr = "string"; -} - -} // namespace cli -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/get_arma_type.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/get_arma_type.hpp deleted file mode 100644 index 1bdfa79cc..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/get_arma_type.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @file get_arma_type.hpp - * @author Ryan Curtin - * - * Return "mat", "col", or "row" depending on the type of the given Armadillo - * object. This is so that the correct overload of arma_numpy.numpy_to_() - * can be called. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_GET_ARMA_TYPE_HPP -#define MLPACK_BINDINGS_PYTHON_GET_ARMA_TYPE_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * This is used for arma::Mat<> types; it will return "mat" for matrices, "row" - * for row vectors, and "col" for column vectors. - */ -template -inline std::string GetArmaType() -{ - if (T::is_col) - return "col"; - else if (T::is_row) - return "row"; - else - return "mat"; -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/get_cython_type.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/get_cython_type.hpp deleted file mode 100644 index e44f4f70b..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/get_cython_type.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @file get_cython_type.hpp - * @author Ryan Curtin - * - * Template metaprogramming to return the string representation of the Cython - * type for a given Cython binding parameter. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_GET_CYTHON_TYPE_HPP -#define MLPACK_BINDINGS_PYTHON_GET_CYTHON_TYPE_HPP - -#include -#include - -namespace mlpack { -namespace bindings { -namespace python { - -template -inline std::string GetCythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - return "unknown"; -} - -template<> -inline std::string GetCythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "int"; -} - -template<> -inline std::string GetCythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "float"; -} - -template<> -inline std::string GetCythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "double"; -} - -template<> -inline std::string GetCythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "string"; -} - -template<> -inline std::string GetCythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "size_t"; -} - -template<> -inline std::string GetCythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "bool"; -} - -template -inline std::string GetCythonType( - const util::ParamData& d, - const typename boost::enable_if>::type* = 0) -{ - return "vector[" + GetCythonType(d) + "]"; -} - -template -inline std::string GetCythonType( - const util::ParamData& d, - const typename boost::enable_if>::type* = 0) -{ - std::string type = "Mat"; - if (T::is_row) - type = "Row"; - else if (T::is_col) - type = "Col"; - - return "arma." + type + "[" + GetCythonType(d) + "]"; -} - -template -inline std::string GetCythonType( - const util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - return d.cppType + "*"; -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/get_numpy_type.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/get_numpy_type.hpp deleted file mode 100644 index 8582eaf23..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/get_numpy_type.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @file get_numpy_type.hpp - * @author Ryan Curtin - * - * Given a C++ type, return the Python numpy dtype associated with that type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_GET_NUMPY_TYPE_HPP -#define MLPACK_BINDINGS_PYTHON_GET_NUMPY_TYPE_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -template -inline std::string GetNumpyType() -{ - return "unknown"; // Not sure... -} - -template<> -inline std::string GetNumpyType() -{ - return "np.double"; -} - -template<> -inline std::string GetNumpyType() -{ - return "np.intp"; -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/get_numpy_type_char.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/get_numpy_type_char.hpp deleted file mode 100644 index 76edd8394..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/get_numpy_type_char.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @file get_numpy_type_char.hpp - * @author Ryan Curtin - * - * Given a matrix type, return the letter we should append to get the right - * arma_numpy method call. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_GET_NUMPY_TYPE_CHAR_HPP -#define MLPACK_BINDINGS_PYTHON_GET_NUMPY_TYPE_CHAR_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -template -inline std::string GetNumpyTypeChar() -{ - return "?"; -} - -// size_t = s. -template<> -inline std::string GetNumpyTypeChar>() -{ - return "s"; -} - -template<> -inline std::string GetNumpyTypeChar>() -{ - return "s"; -} - -template<> -inline std::string GetNumpyTypeChar>() -{ - return "s"; -} - -// double = d. -template<> -inline std::string GetNumpyTypeChar() -{ - return "d"; -} - -template<> -inline std::string GetNumpyTypeChar() -{ - return "d"; -} - -template<> -inline std::string GetNumpyTypeChar() -{ - return "d"; -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/get_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/get_param.hpp deleted file mode 100644 index 95d7d21ef..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/get_param.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @file get_param.hpp - * @author Ryan Curtin - * - * Get a parameter for a Python binding. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_GET_PARAM_HPP -#define MLPACK_BINDINGS_PYTHON_GET_PARAM_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * All Python binding types are exactly what is held in the ParamData, so no - * special handling is necessary. - */ -template -void GetParam(const util::ParamData& d, - const void* /* input */, - void* output) -{ - *((T**) output) = const_cast(boost::any_cast(&d.value)); -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/get_printable_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/get_printable_param.hpp deleted file mode 100644 index 2e590efbd..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/get_printable_param.hpp +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @file get_printable_param.hpp - * @author Ryan Curtin - * - * Get a printable version of parameters. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_GET_PRINTABLE_PARAM_HPP -#define MLPACK_BINDINGS_PYTHON_GET_PRINTABLE_PARAM_HPP - -#include -#include - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Print an option of a simple type. - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0) -{ - std::ostringstream oss; - oss << boost::any_cast(data.value); - return oss.str(); -} - -/** - * Print a vector option, with spaces between it. - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0) -{ - const T& t = boost::any_cast(data.value); - - std::ostringstream oss; - for (size_t i = 0; i < t.size(); ++i) - oss << t[i] << " "; - return oss.str(); -} - -/** - * Print a matrix option (this prints its size). - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0) -{ - // Get the matrix. - const T& matrix = boost::any_cast(data.value); - - std::ostringstream oss; - oss << matrix.n_rows << "x" << matrix.n_cols << " matrix"; - return oss.str(); -} - -/** - * Print a serializable class option (this prints the class name). - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - std::ostringstream oss; - oss << data.cppType << " model at " << boost::any_cast(data.value); - return oss.str(); -} - -/** - * Print a combination DatasetInfo/matrix parameter. - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::enable_if>>::type* = 0) -{ - // Get the matrix. - const T& tuple = boost::any_cast(data.value); - const arma::mat& matrix = std::get<1>(tuple); - - std::ostringstream oss; - oss << matrix.n_rows << "x" << matrix.n_cols << " matrix with dimension type " - << "information"; - return oss.str(); -} - -/** - * Print an option into a std::string. This should print a short, one-line - * representation of the object. The string will be stored in the output - * pointer. - * - * @param data Parameter data struct. - * @param input Unused parameter. - * @param output Output storage for the string. - */ -template -void GetPrintableParam(const util::ParamData& data, - const void* /* input */, - void* output) -{ - *((std::string*) output) = - GetPrintableParam::type>(data); -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/get_python_type.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/get_python_type.hpp deleted file mode 100644 index d78e5c414..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/get_python_type.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @file get_python_type.hpp - * @author Ryan Curtin - * - * Template metaprogramming to return the string representation of the Python - * type for a given Python binding parameter. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_GET_PYTHON_TYPE_HPP -#define MLPACK_BINDINGS_PYTHON_GET_PYTHON_TYPE_HPP - -#include -#include - -namespace mlpack { -namespace bindings { -namespace python { - -template -inline std::string GetPythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - return "unknown"; -} - -template<> -inline std::string GetPythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "int"; -} - -template<> -inline std::string GetPythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "float"; -} - -template<> -inline std::string GetPythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "double"; -} - -template<> -inline std::string GetPythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "string"; -} - -template<> -inline std::string GetPythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "size_t"; -} - -template<> -inline std::string GetPythonType( - const util::ParamData& /* d */, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*, - const typename boost::disable_if>::type*) -{ - return "bool"; -} - -template -inline std::string GetPythonType( - const util::ParamData& d, - const typename boost::enable_if>::type* = 0) -{ - return "list of " + GetPythonType(d) + "s"; -} - -template -inline std::string GetPythonType( - const util::ParamData& /* d */, - const typename boost::enable_if>::type* = 0) -{ - std::string type = "matrix"; - if (T::is_row) - type = "row vector"; - else if (T::is_col) - type = "column vector"; - - return type; -} - -template -inline std::string GetPythonType( - const util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - return d.cppType + "Type"; -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/import_decl.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/import_decl.hpp deleted file mode 100644 index 473f3f759..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/import_decl.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file import_decl.hpp - * @author Ryan Curtin - * - * For a serializable model, print the class import. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_IMPORT_DECL_HPP -#define MLPACK_BINDINGS_PYTHON_IMPORT_DECL_HPP - -#include -#include "strip_type.hpp" - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * For a serializable type, print a cppclass definition. - */ -template -void ImportDecl( - const util::ParamData& d, - const size_t indent, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // First, we have to parse the type. If we have something like, e.g., - // 'LogisticRegression<>', we must convert this to 'LogisticRegression[T=*].' - std::string strippedType, printedType, defaultsType; - StripType(d.cppType, strippedType, printedType, defaultsType); - - /** - * This will give output of the form: - * - * cdef cppclass Type: - * Type() nogil - */ - const std::string prefix = std::string(indent, ' '); - std::cout << prefix << "cdef cppclass " << defaultsType << ":" << std::endl; - std::cout << prefix << " " << strippedType << "() nogil" << std::endl; - std::cout << prefix << std::endl; -} - -/** - * For a non-serializable type, print nothing. - */ -template -void ImportDecl( - const util::ParamData& /* d */, - const size_t /* indent */, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - // Print nothing. -} - -/** - * For a matrix type, print nothing. - */ -template -void ImportDecl( - const util::ParamData& /* d */, - const size_t /* indent */, - const typename boost::enable_if>::type* = 0) -{ - // Print nothing. -} - -/** - * Print the cppclass definition for a serializable model; print nothing for a - * non-serializable type. - * - * @param d Parameter info struct. - * @param input Pointer to size_t indicating indent. - * @param output Unused parameter. - */ -template -void ImportDecl(const util::ParamData& d, - const void* indent, - void* /* output */) -{ - ImportDecl::type>(d, *((size_t*) indent)); -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/arma_util.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/arma_util.hpp deleted file mode 100644 index c94a51e67..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/arma_util.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file arma_util.hpp - * @author Ryan Curtin - * - * Utility function for Cython to set the memory state of an Armadillo object. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_CYTHON_ARMA_UTIL_HPP -#define MLPACK_BINDINGS_PYTHON_CYTHON_ARMA_UTIL_HPP - -// Include Armadillo via mlpack. -#include - -/** - * Set the memory state of the given Armadillo object. - */ -template -void SetMemState(T& t, int state) -{ - const_cast(t.mem_state) = state; -} - -/** - * Get the memory state of the given Armadillo object. - */ -template -size_t GetMemState(T& t) -{ - // Fake the memory state if we are using preallocated memory---since we will - // end up copying that memory, NumPy can own it. - if (t.mem && t.n_elem <= arma::arma_config::mat_prealloc) - return 0; - - return (size_t) t.mem_state; -} - -/** - * Return the matrix's allocated memory pointer, unless the matrix is using its - * internal preallocated memory, in which case we copy that and return a - * pointer to the memory we just made. - */ -template -inline typename T::elem_type* GetMemory(T& m) -{ - if (m.mem && m.n_elem <= arma::arma_config::mat_prealloc) - { - // We need to allocate new memory. - typename T::elem_type* mem = - arma::memory::acquire(m.n_elem); - arma::arrayops::copy(mem, m.memptr(), m.n_elem); - return mem; - } - else - { - return m.memptr(); - } -} - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/cli_util.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/cli_util.hpp deleted file mode 100644 index c2873fcf3..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/cli_util.hpp +++ /dev/null @@ -1,169 +0,0 @@ -/** - * @file cli_util.hpp - * @author Ryan Curtin - * - * Simple function to work around Cython's lack of support for lvalue - * references. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_CYTHON_CLI_UTIL_HPP -#define MLPACK_BINDINGS_PYTHON_CYTHON_CLI_UTIL_HPP - -#include -#include - -namespace mlpack { -namespace util { - -/** - * Set the parameter to the given value. - * - * This function exists to work around Cython's lack of support for lvalue - * references. - * - * @param identifier Name of parameter. - * @param value Value to set parameter to. - */ -template -inline void SetParam(const std::string& identifier, T& value) -{ - CLI::GetParam(identifier) = std::move(value); -} - -/** - * Set the parameter to the given value, given that the type is a pointer. - * - * This function exists to work around both Cython's lack of support for lvalue - * references and also its seeming lack of support for template pointer types. - * - * @param identifier Name of parameter. - * @param value Value to set parameter to. - * @param copy Whether or not the object should be copied. - */ -template -inline void SetParamPtr(const std::string& identifier, - T* value, - const bool copy) -{ - CLI::GetParam(identifier) = copy ? new T(*value) : value; -} - -/** - * Set the parameter (which is a matrix/DatasetInfo tuple) to the given value. - */ -template -inline void SetParamWithInfo(const std::string& identifier, - T& matrix, - const bool* dims) -{ - typedef typename std::tuple TupleType; - typedef typename T::elem_type eT; - - // The true type of the parameter is std::tuple. - const size_t dimensions = matrix.n_rows; - std::get<1>(CLI::GetParam(identifier)) = std::move(matrix); - data::DatasetInfo& di = std::get<0>(CLI::GetParam(identifier)); - di = data::DatasetInfo(dimensions); - - bool hasCategoricals = false; - for (size_t i = 0; i < dimensions; ++i) - { - if (dims[i]) - { - di.Type(i) = data::Datatype::categorical; - hasCategoricals = true; - } - } - - // Do we need to find how many categories we have? - if (hasCategoricals) - { - arma::vec maxs = arma::max( - std::get<1>(CLI::GetParam(identifier)), 1); - - for (size_t i = 0; i < dimensions; ++i) - { - if (dims[i]) - { - // Map the right number of objects. - for (size_t j = 0; j < (size_t) maxs[i]; ++j) - { - std::ostringstream oss; - oss << j; - di.MapString(oss.str(), i); - } - } - } - } -} - -/** - * Return a pointer. This function exists to work around Cython's seeming lack - * of support for template pointer types. - */ -template -T* GetParamPtr(const std::string& paramName) -{ - return CLI::GetParam(paramName); -} - -/** - * Return the matrix part of a matrix + dataset info parameter. - */ -template -T& GetParamWithInfo(const std::string& paramName) -{ - // T will be the Armadillo type. - typedef std::tuple TupleType; - return std::get<1>(CLI::GetParam(paramName)); -} - -/** - * Turn verbose output on. - */ -inline void EnableVerbose() -{ - Log::Info.ignoreInput = false; -} - -/** - * Turn verbose output off. - */ -inline void DisableVerbose() -{ - Log::Info.ignoreInput = true; -} - -/** - * Disable backtraces. - */ -inline void DisableBacktrace() -{ - Log::Fatal.backtrace = false; -} - -/** - * Reset the status of all timers. - */ -inline void ResetTimers() -{ - // Just get a new object---removes all old timers. - CLI::GetSingleton().timer.Reset(); -} - -/** - * Enable timing. - */ -inline void EnableTimers() -{ - Timer::EnableTiming(); -} - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/serialization.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/serialization.hpp deleted file mode 100644 index dbb32ca05..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/mlpack/serialization.hpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @serialization.hpp - * @author Ryan Curtin - * - * Simple utilities for boost::serialization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_MLPACK_SERIALIZATION_HPP -#define MLPACK_BINDINGS_PYTHON_MLPACK_SERIALIZATION_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -template -std::string SerializeOut(T* t, const std::string& name) -{ - std::ostringstream oss; - { - boost::archive::binary_oarchive b(oss); - - b << boost::serialization::make_nvp(name.c_str(), *t); - } - return oss.str(); -} - -template -void SerializeIn(T* t, const std::string& str, const std::string& name) -{ - std::istringstream iss(str); - boost::archive::binary_iarchive b(iss); - - b >> boost::serialization::make_nvp(name.c_str(), *t); -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/print_class_defn.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/print_class_defn.hpp deleted file mode 100644 index a80b4b266..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/print_class_defn.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @file print_class_defn.hpp - * @author Ryan Curtin - * - * Print the class definition for generating a .pyx binding. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_PRINT_CLASS_DEFN_HPP -#define MLPACK_BINDINGS_PYTHON_PRINT_CLASS_DEFN_HPP - -#include "strip_type.hpp" - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Non-serializable models don't require any special definitions, so this prints - * nothing. - */ -template -void PrintClassDefn( - const util::ParamData& /* d */, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - // Do nothing. -} - -/** - * Matrices don't require any special definitions, so this prints nothing. - */ -template -void PrintClassDefn( - const util::ParamData& /* d */, - const typename boost::enable_if>::type* = 0) -{ - // Do nothing. -} - -/** - * Serializable models require a special class definition. - */ -template -void PrintClassDefn( - const util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // First, we have to parse the type. If we have something like, e.g., - // 'LogisticRegression<>', we must convert this to 'LogisticRegression[].' - std::string strippedType, printedType, defaultsType; - StripType(d.cppType, strippedType, printedType, defaultsType); - - /** - * This will produce code like: - * - * cdef class Type: - * cdef * modelptr - * - * def __cinit__(self): - * self.modelptr = new () - * - * def __dealloc__(self): - * del self.modelptr - * - * def __getstate__(self): - * return SerializeOut(self.modelptr, "") - * - * def __setstate__(self, state): - * SerializeIn(self.modelptr, state, "") - * - * def __reduce_ex__(self): - * return (self.__class__, (), self.__getstate__()) - */ - std::cout << "cdef class " << strippedType << "Type:" << std::endl; - std::cout << " cdef " << printedType << "* modelptr" << std::endl; - std::cout << std::endl; - std::cout << " def __cinit__(self):" << std::endl; - std::cout << " self.modelptr = new " << printedType << "()" << std::endl; - std::cout << std::endl; - std::cout << " def __dealloc__(self):" << std::endl; - std::cout << " del self.modelptr" << std::endl; - std::cout << std::endl; - std::cout << " def __getstate__(self):" << std::endl; - std::cout << " return SerializeOut(self.modelptr, \"" << printedType - << "\")" << std::endl; - std::cout << std::endl; - std::cout << " def __setstate__(self, state):" << std::endl; - std::cout << " SerializeIn(self.modelptr, state, \"" << printedType - << "\")" << std::endl; - std::cout << std::endl; - std::cout << " def __reduce_ex__(self, version):" << std::endl; - std::cout << " return (self.__class__, (), self.__getstate__())" - << std::endl; - std::cout << std::endl; -} - -/** - * Print the class definition to stdout. Only serializable models require a - * different class definition, so anything else does nothing. - * - * @param d Parameter data. - * @param input Unused parameter. - * @param output Unused parameter. - */ -template -void PrintClassDefn(const util::ParamData& d, - const void* /* input */, - void* /* output */) -{ - PrintClassDefn::type>(d); -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/print_defn.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/print_defn.hpp deleted file mode 100644 index 214c1f8f6..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/print_defn.hpp +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @file print_defn.hpp - * @author Ryan Curtin - * - * Print the definition of a Python parameter. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_PRINT_DEFN_HPP -#define MLPACK_BINDINGS_PYTHON_PRINT_DEFN_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Print the definition for a Python binding parameter to stdout. This is the - * definition in the function declaration. - */ -template -void PrintDefn(const util::ParamData& d, - const void* /* input */, - void* /* output */) -{ - // Make sure that we don't use names that are Python keywords. - std::string name = (d.name == "lambda") ? "lambda_" : d.name; - - std::cout << name; - if (std::is_same::value) - std::cout << "=False"; - else if (!d.required) - std::cout << "=None"; -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/print_doc.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/print_doc.hpp deleted file mode 100644 index 7a5a27781..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/print_doc.hpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file print_doc.hpp - * @author Ryan Curtin - * - * Print documentation (as part of a docstring) for a Python binding parameter. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_PRINT_DOC_HPP -#define MLPACK_BINDINGS_PYTHON_PRINT_DOC_HPP - -#include -#include -#include "get_python_type.hpp" - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Print the docstring documentation for a given parameter. You are responsible - * for setting up the line---this does not handle indentation or anything. This - * is meant to produce a line of documentation describing a single parameter. - * - * The indent parameter (void* input, which should be a pointer to a size_t) - * should be passed to know how much to indent for a new line. - * - * @param d Parameter data struct. - * @param input Pointer to size_t containing indent. - * @param output Unused parameter. - */ -template -void PrintDoc(const util::ParamData& d, - const void* input, - void* /* output */) -{ - const size_t indent = *((size_t*) input); - std::ostringstream oss; - oss << " - "; - if (d.name == "lambda") // Don't print Python keywords. - oss << d.name << "_ ("; - else - oss << d.name << " ("; - oss << GetPythonType::type>(d) << "): " - << d.desc; - - // Print a default, if possible. - if (!d.required) - { - if (d.cppType == "std::string") - { - oss << " Default value '" << boost::any_cast(d.value) - << "'."; - } - else if (d.cppType == "double") - { - oss << " Default value " << boost::any_cast(d.value) << "."; - } - else if (d.cppType == "int") - { - oss << " Default value " << boost::any_cast(d.value) << "."; - } - } - - std::cout << util::HyphenateString(oss.str(), indent + 4); -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/print_doc_functions.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/print_doc_functions.hpp deleted file mode 100644 index a9207c570..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/print_doc_functions.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @file print_doc_functions.hpp - * @author Ryan Curtin - * - * This file contains functions useful for printing documentation strings - * related to Python bindings. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_PRINT_DOC_FUNCTIONS_HPP -#define MLPACK_BINDINGS_PYTHON_PRINT_DOC_FUNCTIONS_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Given a parameter type, print the corresponding value. - */ -template -inline std::string PrintValue(const T& value, bool quotes); - -// Special overload for booleans. -template<> -inline std::string PrintValue(const bool& value, bool quotes); - -// Recursion base case. -inline std::string PrintInputOptions(); - -/** - * Print an input option. This will throw an exception if the parameter does - * not exist in CLI. For a parameter 'x' with value '5', this will print - * something like x=5. - */ -template -std::string PrintInputOptions(const std::string& paramName, - const T& value, - Args... args); - -// Recursion base case. -inline std::string PrintOutputOptions(); - -template -std::string PrintOutputOptions(const std::string& paramName, - const T& value, - Args... args); - -/** - * Given a name of a binding and a variable number of arguments (and their - * contents), print the corresponding function call. - */ -template -std::string ProgramCall(const std::string& programName, Args... args); - -/** - * Given the name of a model, print it. Here we do not need to modify anything. - */ -inline std::string PrintModel(const std::string& modelName); - -/** - * Given the name of a matrix, print it. Here we do not need to modify - * anything. - */ -inline std::string PrintDataset(const std::string& datasetName); - -/** - * Given the parameter name, determine what it would actually be when passed to - * the command line. - */ -inline std::string ParamString(const std::string& paramName); - -/** - * Print whether or not we should ignore a check on the given parameter. For - * Python bindings, we ignore any checks on output parameters, so if paramName - * is an output parameter, this returns true. - */ -inline bool IgnoreCheck(const std::string& paramName); - -/** - * Print whether or not we should ignore a check on the given set of - * constraints. For Python bindings, we ignore any checks on output parameters, - * so if any parameter is an output parameter, this returns true. - */ -inline bool IgnoreCheck(const std::vector& constraints); - -/** - * Print whether or not we should ignore a check on the given set of - * constraints. For Python bindings, we ignore any checks on output parameters, - * so if any constraint parameter or the main parameter are output parameters, - * this returns true. - */ -inline bool IgnoreCheck( - const std::vector>& constraints, - const std::string& paramName); - -} // namespace python -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "print_doc_functions_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/print_doc_functions_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/print_doc_functions_impl.hpp deleted file mode 100644 index c27e88609..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/print_doc_functions_impl.hpp +++ /dev/null @@ -1,266 +0,0 @@ -/** - * @file print_doc_functions_impl.hpp - * @author Ryan Curtin - * - * This file contains functions useful for printing documentation strings - * related to Python bindings. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_PRINT_DOC_FUNCTIONS_IMPL_HPP -#define MLPACK_BINDINGS_PYTHON_PRINT_DOC_FUNCTIONS_IMPL_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Given a parameter type, print the corresponding value. - */ -template -inline std::string PrintValue(const T& value, bool quotes) -{ - std::ostringstream oss; - if (quotes) - oss << "'"; - oss << value; - if (quotes) - oss << "'"; - return oss.str(); -} - -// Special overload for booleans. -template<> -inline std::string PrintValue(const bool& value, bool quotes) -{ - if (quotes && value) - return "'True'"; - else if (quotes && !value) - return "'False'"; - else if (!quotes && value) - return "True"; - else - return "False"; -} - -// Recursion base case. -std::string PrintInputOptions() { return ""; } - -/** - * Print an input option. This will throw an exception if the parameter does - * not exist in CLI. For a parameter 'x' with value '5', this will print - * something like x=5. - */ -template -std::string PrintInputOptions(const std::string& paramName, - const T& value, - Args... args) -{ - // See if this is part of the program. - std::string result = ""; - if (CLI::Parameters().count(paramName) > 0) - { - const util::ParamData& d = CLI::Parameters()[paramName]; - if (d.input) - { - // Print the input option. - std::ostringstream oss; - if (paramName != "lambda") // Don't print Python keywords. - oss << paramName << "="; - else - oss << paramName << "_="; - oss << PrintValue(value, d.tname == TYPENAME(std::string)); - result = oss.str(); - } - } - else - { - // Unknown parameter! - throw std::runtime_error("Unknown parameter '" + paramName + "' " + - "encountered while assembling documentation! Check PROGRAM_INFO() " + - "declaration."); - } - - // Continue recursion. - std::string rest = PrintInputOptions(args...); - if (rest != "" && result != "") - result += ", " + rest; - else if (result == "") - result = rest; - - return result; -} - -// Recursion base case. -inline std::string PrintOutputOptions() { return ""; } - -template -std::string PrintOutputOptions(const std::string& paramName, - const T& value, - Args... args) -{ - // See if this is part of the program. - std::string result = ""; - if (CLI::Parameters().count(paramName) > 0) - { - const util::ParamData& d = CLI::Parameters()[paramName]; - if (!d.input) - { - // Print a new line for the output option. - std::ostringstream oss; - oss << ">>> " << value << " = output['" << paramName << "']"; - result = oss.str(); - } - } - else - { - // Unknown parameter! - throw std::runtime_error("Unknown parameter '" + paramName + "' " + - "encountered while assembling documentation! Check PROGRAM_INFO() " + - "declaration."); - } - - // Continue recursion. - std::string rest = PrintOutputOptions(args...); - if (rest != "" && result != "") - result += '\n'; - result += rest; - - return result; -} - -/** - * Given a name of a binding and a variable number of arguments (and their - * contents), print the corresponding function call. - */ -template -std::string ProgramCall(const std::string& programName, Args... args) -{ - std::ostringstream oss; - oss << ">>> "; - - // Find out if we have any output options first. - std::ostringstream ossOutput; - ossOutput << PrintOutputOptions(args...); - if (ossOutput.str() != "") - oss << "output = "; - oss << programName << "("; - - // Now process each input option. - oss << PrintInputOptions(args...); - oss << ")"; - - std::string call = oss.str(); - oss.str(""); // Reset it. - - // Now process each output option. - oss << PrintOutputOptions(args...); - if (oss.str() == "") - return util::HyphenateString(call, 2); - else - return util::HyphenateString(call, 2) + "\n" + oss.str(); -} - -/** - * Given the name of a model, print it. Here we do not need to modify anything. - */ -inline std::string PrintModel(const std::string& modelName) -{ - return "'" + modelName + "'"; -} - -/** - * Given the name of a matrix, print it. Here we do not need to modify - * anything. - */ -inline std::string PrintDataset(const std::string& datasetName) -{ - return "'" + datasetName + "'"; -} - -/** - * Given the name of a binding, print its invocation. - */ -inline std::string ProgramCall(const std::string& programName) -{ - return ">>> " + programName + "("; -} - -/** - * Print any closing call to a program. For a Python binding this is a closing - * brace. - */ -inline std::string ProgramCallClose() -{ - return ")"; -} - -/** - * Given the parameter name, determine what it would actually be when passed to - * the command line. - */ -inline std::string ParamString(const std::string& paramName) -{ - // For a Python binding we don't need to know the type. - - // Make sure that we don't print reserved keywords. - if (paramName == "lambda") - return "'" + paramName + "_'"; - else - return "'" + paramName + "'"; -} - -/** - * Given the parameter name and an argument, return what should be written as - * documentation when referencing that argument. - */ -template -inline std::string ParamString(const std::string& paramName, const T& value) -{ - std::ostringstream oss; - if (paramName == "lambda") // Don't print reserved keywords. - oss << paramName << "_=" << value; - else - oss << paramName << "=" << value; - return oss.str(); -} - -inline bool IgnoreCheck(const std::string& paramName) -{ - return !CLI::Parameters()[paramName].input; -} - -inline bool IgnoreCheck(const std::vector& constraints) -{ - for (size_t i = 0; i < constraints.size(); ++i) - { - if (!CLI::Parameters()[constraints[i]].input) - return true; - } - - return false; -} - -inline bool IgnoreCheck( - const std::vector>& constraints, - const std::string& paramName) -{ - for (size_t i = 0; i < constraints.size(); ++i) - { - if (!CLI::Parameters()[constraints[i].first].input) - return true; - } - - return !CLI::Parameters()[paramName].input; -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/print_input_processing.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/print_input_processing.hpp deleted file mode 100644 index e271906cb..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/print_input_processing.hpp +++ /dev/null @@ -1,317 +0,0 @@ -/** - * @file print_input_processing.hpp - * @author Ryan Curtin - * - * Print input processing for a Python binding option. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_PRINT_INPUT_PROCESSING_HPP -#define MLPACK_BINDINGS_PYTHON_PRINT_INPUT_PROCESSING_HPP - -#include -#include "get_arma_type.hpp" -#include "get_numpy_type.hpp" -#include "get_numpy_type_char.hpp" -#include "get_cython_type.hpp" -#include "get_python_type.hpp" -#include "strip_type.hpp" - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Print input processing for a standard option type. - */ -template -void PrintInputProcessing( - const util::ParamData& d, - const size_t indent, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0) -{ - // The copy_all_inputs parameter must be handled first, and therefore is - // outside the scope of this code. - if (d.name == "copy_all_inputs") - return; - - const std::string prefix(indent, ' '); - - std::string def = "None"; - if (std::is_same::value) - def = "False"; - - // Make sure that we don't use names that are Python keywords. - std::string name = (d.name == "lambda") ? "lambda_" : d.name; - - /** - * This gives us code like: - * - * # Detect if the parameter was passed; set if so. - * if param_name is not None: - * SetParam[int]( 'param_name', param_name) - * CLI.SetPassed( 'param_name') - */ - std::cout << prefix << "# Detect if the parameter was passed; set if so." - << std::endl; - if (!d.required) - { - std::cout << prefix << "if " << name << " is not " << def << ":" - << std::endl; - - std::cout << prefix << " SetParam[" << GetCythonType(d) << "]( '" << d.name << "', "; - if (GetCythonType(d) == "string") - std::cout << name << ".encode(\"UTF-8\")"; - else if (GetCythonType(d) == "vector[string]") - std::cout << "[i.encode(\"UTF-8\") for i in " << name << "]"; - else - std::cout << name; - std::cout << ")" << std::endl; - std::cout << prefix << " CLI.SetPassed( '" << d.name - << "')" << std::endl; - - // If this parameter is "verbose", then enable verbose output. - if (d.name == "verbose") - std::cout << prefix << " EnableVerbose()" << std::endl; - } - else - { - std::cout << prefix << "SetParam[" << GetCythonType(d) << "]( '" << d.name << "', "; - if (GetCythonType(d) == "string") - std::cout << name << ".encode(\"UTF-8\")"; - else if (GetCythonType(d) == "vector[string]") - std::cout << "[i.encode(\"UTF-8\") for i in " << name << "]"; - else - std::cout << name; - std::cout << ")" << std::endl; - std::cout << prefix << "CLI.SetPassed( '" << d.name << "')" - << std::endl; - } - std::cout << std::endl; // Extra line is to clear up the code a bit. -} - -/** - * Print input processing for a matrix type. - */ -template -void PrintInputProcessing( - const util::ParamData& d, - const size_t indent, - const typename boost::enable_if>::type* = 0) -{ - const std::string prefix(indent, ' '); - - /** - * This gives us code like: - * - * # Detect if the parameter was passed; set if so. - * if param_name is not None: - * param_name_tuple = to_matrix(param_name) - * param_name_mat = arma_numpy.numpy_to_mat_d(param_name_tuple[0], - * param_name_tuple[1]) - * SetParam[mat]( 'param_name', dereference(param_name_mat)) - * CLI.SetPassed( 'param_name') - */ - std::cout << prefix << "# Detect if the parameter was passed; set if so." - << std::endl; - if (!d.required) - { - std::cout << prefix << "if " << d.name << " is not None:" << std::endl; - - std::cout << prefix << " " << d.name << "_tuple = to_matrix(" << d.name - << ", dtype=" << GetNumpyType() << ", " - << "copy=CLI.HasParam('copy_all_inputs'))" << std::endl; - std::cout << prefix << " " << d.name << "_mat = arma_numpy.numpy_to_" - << GetArmaType() << "_" << GetNumpyTypeChar() << "(" << d.name - << "_tuple[0], " << d.name << "_tuple[1])" << std::endl; - std::cout << prefix << " SetParam[" << GetCythonType(d) << "]( '" << d.name << "', dereference(" << d.name << "_mat))" - << std::endl; - std::cout << prefix << " CLI.SetPassed( '" << d.name << "')" - << std::endl; - std::cout << prefix << " del " << d.name << "_mat"; - } - else - { - std::cout << prefix << d.name << "_tuple = to_matrix(" << d.name - << ", dtype=" << GetNumpyType() << ", " - << "copy=CLI.HasParam('copy_all_inputs'))" << std::endl; - std::cout << prefix << d.name << "_mat = arma_numpy.numpy_to_" - << GetArmaType() << "_" << GetNumpyTypeChar() << "(" << d.name - << "_tuple[0], " << d.name << "_tuple[1])" << std::endl; - std::cout << prefix << "SetParam[" << GetCythonType(d) << "]( '" << d.name << "', dereference(" << d.name << "_mat))" - << std::endl; - std::cout << prefix << "CLI.SetPassed( '" << d.name << "')" - << std::endl; - std::cout << prefix << "del " << d.name << "_mat"; - } - std::cout << std::endl; -} - -/** - * Print input processing for a serializable type. - */ -template -void PrintInputProcessing( - const util::ParamData& d, - const size_t indent, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // First, get the correct class name if needed. - std::string strippedType, printedType, defaultsType; - StripType(d.cppType, strippedType, printedType, defaultsType); - - const std::string prefix(indent, ' '); - - /** - * This gives us code like: - * - * # Detect if the parameter was passed; set if so. - * if param_name is not None: - * try: - * SetParamPtr[Model]('param_name', ( param_name).modelptr, - * CLI.HasParam('copy_all_inputs')) - * except TypeError as e: - * if type(param_name).__name__ == "ModelType": - * SetParamPtr[Model]('param_name', ( param_name).modelptr, - * CLI.HasParam('copy_all_inputs')) - * else: - * raise e - * CLI.SetPassed( 'param_name') - */ - std::cout << prefix << "# Detect if the parameter was passed; set if so." - << std::endl; - if (!d.required) - { - std::cout << prefix << "if " << d.name << " is not None:" << std::endl; - std::cout << prefix << " try:" << std::endl; - std::cout << prefix << " SetParamPtr[" << strippedType << "]('" << d.name - << "', (<" << strippedType << "Type?> " << d.name << ").modelptr, " - << "CLI.HasParam('copy_all_inputs'))" << std::endl; - std::cout << prefix << " except TypeError as e:" << std::endl; - std::cout << prefix << " if type(" << d.name << ").__name__ == '" - << strippedType << "Type':" << std::endl; - std::cout << prefix << " SetParamPtr[" << strippedType << "]('" - << d.name << "', (<" << strippedType << "Type> " << d.name - << ").modelptr, CLI.HasParam('copy_all_inputs'))" << std::endl; - std::cout << prefix << " else:" << std::endl; - std::cout << prefix << " raise e" << std::endl; - std::cout << prefix << " CLI.SetPassed( '" << d.name << "')" - << std::endl; - } - else - { - std::cout << prefix << "try:" << std::endl; - std::cout << prefix << " SetParamPtr[" << strippedType << "]('" << d.name - << "', (<" << strippedType << "Type?> " << d.name << ").modelptr, " - << "CLI.HasParam('copy_all_inputs'))" << std::endl; - std::cout << prefix << "except TypeError as e:" << std::endl; - std::cout << prefix << " if type(" << d.name << ").__name__ == '" - << strippedType << "Type':" << std::endl; - std::cout << prefix << " SetParamPtr[" << strippedType << "]('" << d.name - << "', (<" << strippedType << "Type> " << d.name << ").modelptr, " - << "CLI.HasParam('copy_all_inputs'))" << std::endl; - std::cout << prefix << " else:" << std::endl; - std::cout << prefix << " raise e" << std::endl; - std::cout << prefix << "CLI.SetPassed( '" << d.name << "')" - << std::endl; - } - std::cout << std::endl; -} - -/** - * Print input processing for a matrix/DatasetInfo type. - */ -template -void PrintInputProcessing( - const util::ParamData& d, - const size_t indent, - const typename boost::enable_if>>::type* = 0) -{ - // The user should pass in a matrix type of some sort. - const std::string prefix(indent, ' '); - - /** We want to generate code like the following: - * - * if param_name is not None: - * param_name_tuple = to_matrix_with_info(param_name) - * param_name_mat = arma_numpy.numpy_to_matrix_d(param_name_tuple[0]) - * SetParamWithInfo[mat]( 'param_name', - * dereference(param_name_mat), ¶m_name_tuple[1][0]) - * CLI.SetPassed( 'param_name') - */ - std::cout << prefix << "cdef np.ndarray " << d.name << "_dims" << std::endl; - std::cout << prefix << "# Detect if the parameter was passed; set if so." - << std::endl; - if (!d.required) - { - std::cout << prefix << "if " << d.name << " is not None:" << std::endl; - std::cout << prefix << " " << d.name << "_tuple = to_matrix_with_info(" - << d.name << ", dtype=np.double, copy=CLI.HasParam('copy_all_inputs'))" - << std::endl; - std::cout << prefix << " " << d.name << "_mat = arma_numpy.numpy_to_mat_d(" - << d.name << "_tuple[0], " << d.name << "_tuple[1])" << std::endl; - std::cout << prefix << " " << d.name << "_dims = " << d.name << "_tuple[2]" - << std::endl; - std::cout << prefix << " SetParamWithInfo[arma.Mat[double]](" - << " '" << d.name << "', dereference(" << d.name << "_mat), " << d.name << "_dims.data)" << std::endl; - std::cout << prefix << " CLI.SetPassed( '" << d.name << "')" - << std::endl; - std::cout << prefix << " del " << d.name << "_mat" << std::endl; - } - else - { - std::cout << prefix << d.name << "_tuple = to_matrix_with_info(" << d.name - << ", dtype=np.double, copy=CLI.HasParam('copy_all_inputs'))" - << std::endl; - std::cout << prefix << d.name << "_mat = arma_numpy.numpy_to_mat_d(" - << d.name << "_tuple[0], " << d.name << "_tuple[1])" << std::endl; - std::cout << prefix << d.name << "_dims = " << d.name << "_tuple[2]" - << std::endl; - std::cout << prefix << "SetParamWithInfo[arma.Mat[double]](" - << " '" << d.name << "', dereference(" << d.name << "_mat), " << d.name << "_dims.data)" << std::endl; - std::cout << prefix << "CLI.SetPassed( '" << d.name << "')" - << std::endl; - std::cout << prefix << "del " << d.name << "_mat" << std::endl; - } - std::cout << std::endl; -} - -/** - * Given parameter information and the current number of spaces for indentation, - * print the code to process the input to cout. This code assumes that - * data.input is true, and should not be called when data.input is false. - * - * The number of spaces to indent should be passed through the input pointer. - * - * @param d Parameter data struct. - * @param input Pointer to size_t holding the indentation. - * @param output Unused parameter. - */ -template -void PrintInputProcessing(const util::ParamData& d, - const void* input, - void* /* output */) -{ - PrintInputProcessing::type>(d, - *((size_t*) input)); -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/print_output_processing.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/print_output_processing.hpp deleted file mode 100644 index 08e58fcdf..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/print_output_processing.hpp +++ /dev/null @@ -1,312 +0,0 @@ -/** - * @file print_output_processing.hpp - * @author Ryan Curtin - * - * Print the output processing in a Python binding .pyx file for a given - * parameter. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_PRINT_OUTPUT_PROCESSING_HPP -#define MLPACK_BINDINGS_PYTHON_PRINT_OUTPUT_PROCESSING_HPP - -#include -#include "get_arma_type.hpp" -#include "get_numpy_type_char.hpp" -#include "get_cython_type.hpp" - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Print output processing for a regular parameter type. - */ -template -void PrintOutputProcessing( - const util::ParamData& d, - const size_t indent, - const bool onlyOutput, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0) -{ - const std::string prefix(indent, ' '); - - if (onlyOutput) - { - /** - * This gives us code like: - * - * result = CLI.GetParam[int]('param_name') - */ - std::cout << prefix << "result = " << "CLI.GetParam[" << GetCythonType(d) - << "](\"" << d.name << "\")"; - if (GetCythonType(d) == "string") - { - std::cout << std::endl << prefix << "result = result.decode(\"UTF-8\")"; - } - else if (GetCythonType(d) == "vector[string]") - { - std::cout << std::endl << prefix - << "result = [x.decode(\"UTF-8\") for x in result]"; - } - } - else - { - /** - * This gives us code like: - * - * result['param_name'] = CLI.GetParam[int]('param_name') - */ - std::cout << prefix << "result['" << d.name << "'] = CLI.GetParam[" - << GetCythonType(d) << "](\"" << d.name << "\")" << std::endl; - if (GetCythonType(d) == "string") - { - std::cout << prefix << "result['" << d.name << "'] = result['" << d.name - << "'].decode(\"UTF-8\")" << std::endl; - } - else if (GetCythonType(d) == "vector[string]") - { - std::cout << prefix << "result['" << d.name << "'] = [x.decode(\"UTF-8\")" - << " for x in result['" << d.name << "']]" << std::endl; - } - } -} - -/** - * Print output processing for a matrix type. - */ -template -void PrintOutputProcessing( - const util::ParamData& d, - const size_t indent, - const bool onlyOutput, - const typename boost::enable_if>::type* = 0) -{ - const std::string prefix(indent, ' '); - - if (onlyOutput) - { - /** - * This gives us code like: - * - * result = arma_numpy.mat_to_numpy_X(CLI.GetParam[mat]("name")) - * - * where X indicates the type to convert to. - */ - std::cout << prefix << "result = arma_numpy." << GetArmaType() - << "_to_numpy_" << GetNumpyTypeChar() << "(CLI.GetParam[" - << GetCythonType(d) << "](\"" << d.name << "\"))" << std::endl; - } - else - { - /** - * This gives us code like: - * - * result['param_name'] = - * arma_numpy.mat_to_numpy_X(CLI.GetParam[mat]('name') - * - * where X indicates the type to convert to. - */ - std::cout << prefix << "result['" << d.name - << "'] = arma_numpy." << GetArmaType() << "_to_numpy_" - << GetNumpyTypeChar() << "(CLI.GetParam[" << GetCythonType(d) - << "]('" << d.name << "'))" << std::endl; - } -} - -/** - * Print output processing for a dataset info / matrix combination. - */ -template -void PrintOutputProcessing( - const util::ParamData& d, - const size_t indent, - const bool onlyOutput, - const typename boost::enable_if>>::type* = 0) -{ - const std::string prefix(indent, ' '); - - // Print the output with the matrix type. The dimension information doesn't - // need to go back. - if (onlyOutput) - { - /** - * This gives us code like: - * - * result = arma_numpy.mat_to_numpy_X(GetParamWithInfo[mat]('name')) - */ - std::cout << prefix << "result = arma_numpy.mat_to_numpy_" - << GetNumpyTypeChar() - << "(GetParamWithInfo[arma.Mat[double]]('" << d.name << "'))" - << std::endl; - } - else - { - /** - * This gives us code like: - * - * result['param_name'] = - * arma_numpy.mat_to_numpy_X(GetParamWithInfo[mat]('name')) - */ - std::cout << prefix << "result['" << d.name - << "'] = arma_numpy.mat_to_numpy_" << GetNumpyTypeChar() - << "(GetParamWithInfo[arma.Mat[double]]('" << d.name << "'))" - << std::endl; - } -} - -/** - * Print output processing for a serializable model. - */ -template -void PrintOutputProcessing( - const util::ParamData& d, - const size_t indent, - const bool onlyOutput, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // Get the type names we need to use. - std::string strippedType, printedType, defaultsType; - StripType(d.cppType, strippedType, printedType, defaultsType); - - const std::string prefix(indent, ' '); - - if (onlyOutput) - { - /** - * This gives us code like: - * - * result = ModelType() - * ( result).modelptr = GetParamPtr[Model]('name') - */ - std::cout << prefix << "result = " << strippedType << "Type()" << std::endl; - std::cout << prefix << "(<" << strippedType << "Type?> result).modelptr = " - << "GetParamPtr[" << strippedType << "]('" << d.name << "')" - << std::endl; - - /** - * But we also have to check to ensure there aren't any input model - * parameters of the same type that could have the same model pointer. - * So we need to loop through all input parameters that have the same type, - * and double-check. - */ - std::map& parameters = CLI::Parameters(); - for (auto it = parameters.begin(); it != parameters.end(); ++it) - { - // Is it an input parameter of the same type? - const util::ParamData& data = it->second; - if (data.input && data.cppType == d.cppType && data.required) - { - std::cout << prefix << "if (<" << strippedType - << "Type> result).modelptr" << d.name << " == (<" << strippedType - << "Type> " << data.name << ").modelptr:" << std::endl; - std::cout << prefix << " (<" << strippedType - << "Type> result).modelptr = <" << strippedType << "*> 0" - << std::endl; - std::cout << prefix << " result = " << data.name << std::endl; - } - else if (data.input && data.cppType == d.cppType) - { - std::cout << prefix << "if " << data.name << " is not None:" - << std::endl; - std::cout << prefix << " if (<" << strippedType - << "Type> result).modelptr" << d.name << " == (<" << strippedType - << "Type> " << data.name << ").modelptr:" << std::endl; - std::cout << prefix << " (<" << strippedType - << "Type> result).modelptr = <" << strippedType << "*> 0" - << std::endl; - std::cout << prefix << " result = " << data.name << std::endl; - } - } - } - else - { - /** - * This gives us code like: - * - * result['name'] = ModelType() - * ( result['name']).modelptr = GetParamPtr[Model]('name')) - */ - std::cout << prefix << "result['" << d.name << "'] = " << strippedType - << "Type()" << std::endl; - std::cout << prefix << "(<" << strippedType << "Type?> result['" << d.name - << "']).modelptr = GetParamPtr[" << strippedType << "]('" << d.name - << "')" << std::endl; - - /** - * But we also have to check to ensure there aren't any input model - * parameters of the same type that could have the same model pointer. - * So we need to loop through all input parameters that have the same type, - * and double-check. - */ - std::map& parameters = CLI::Parameters(); - for (auto it = parameters.begin(); it != parameters.end(); ++it) - { - // Is it an input parameter of the same type? - const util::ParamData& data = it->second; - if (data.input && data.cppType == d.cppType && data.required) - { - std::cout << prefix << "if (<" << strippedType << "Type> result['" - << d.name << "']).modelptr == (<" << strippedType << "Type> " - << data.name << ").modelptr:" << std::endl; - std::cout << prefix << " (<" << strippedType << "Type> result['" - << d.name << "']).modelptr = <" << strippedType << "*> 0" - << std::endl; - std::cout << prefix << " result['" << d.name << "'] = " << data.name - << std::endl; - } - else if (data.input && data.cppType == d.cppType) - { - std::cout << prefix << "if " << data.name << " is not None:" - << std::endl; - std::cout << prefix << " if (<" << strippedType << "Type> result['" - << d.name << "']).modelptr == (<" << strippedType << "Type> " - << data.name << ").modelptr:" << std::endl; - std::cout << prefix << " (<" << strippedType << "Type> result['" - << d.name << "']).modelptr = <" << strippedType << "*> 0" - << std::endl; - std::cout << prefix << " result['" << d.name << "'] = " << data.name - << std::endl; - } - } - } -} - -/** - * Given parameter information and the current number of spaces for indentation, - * print the code to process the output to cout. This code assumes that - * data.input is false, and should not be called when data.input is true. If - * this is the only output, the results will be different. - * - * The input pointer should be a pointer to a std::tuple where the - * first element is the indentation and the second element is a boolean - * representing whether or not this is the only output parameter. - * - * @param d Parameter data struct. - * @param input Pointer to size_t holding the indentation. - * @param output Unused parameter. - */ -template -void PrintOutputProcessing(const util::ParamData& d, - const void* input, - void* /* output */) -{ - std::tuple* tuple = (std::tuple*) input; - - PrintOutputProcessing::type>(d, - std::get<0>(*tuple), std::get<1>(*tuple)); -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/print_pyx.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/print_pyx.hpp deleted file mode 100644 index 80c336c34..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/print_pyx.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file generate_pyx.hpp - * @author Ryan Curtin - * - * Given a list of ParamData structures, emit a .pyx file defining the Cython - * binding. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_GENERATE_PYX_HPP -#define MLPACK_BINDINGS_PYTHON_GENERATE_PYX_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Given a list of parameter definition and program documentation, print a - * generated .pyx file to stdout. - * - * @param parameters List of parameters the program will use (from CLI). - * @param programInfo Documentation for the program. - * @param mainFilename Filename of the main program (i.e. - * "/path/to/pca_main.cpp"). - * @param functionName Name of the function (i.e. "pca"). - */ -void PrintPYX(const util::ProgramDoc& programInfo, - const std::string& mainFilename, - const std::string& functionName); - - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/py_option.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/py_option.hpp deleted file mode 100644 index 98bba2dd5..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/py_option.hpp +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @file py_option.hpp - * @author Ryan Curtin - * - * The Python option type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_PY_OPTION_HPP -#define MLPACK_BINDINGS_PYTHON_PY_OPTION_HPP - -#include -#include "get_param.hpp" -#include "get_printable_param.hpp" -#include "print_class_defn.hpp" -#include "print_defn.hpp" -#include "print_doc.hpp" -#include "print_input_processing.hpp" -#include "print_output_processing.hpp" -#include "import_decl.hpp" - -namespace mlpack { -namespace bindings { -namespace python { - -// Defined in mlpack_main.hpp. -extern std::string programName; - -/** - * The Python option class. - */ -template -class PyOption -{ - public: - /** - * Construct a PyOption object. When constructed, it will register itself - * with CLI. The testName parameter is not used and added for compatibility - * reasons. - */ - PyOption(const T defaultValue, - const std::string& identifier, - const std::string& description, - const std::string& alias, - const std::string& cppName, - const bool required = false, - const bool input = true, - const bool noTranspose = false, - const std::string& /*testName*/ = "") - { - // Create the ParamData object to give to CLI. - util::ParamData data; - - data.desc = description; - data.name = identifier; - data.tname = TYPENAME(T); - data.alias = alias[0]; - data.wasPassed = false; - data.noTranspose = noTranspose; - data.required = required; - data.input = input; - data.loaded = false; - // Only "verbose" and "copy_all_inputs" will be persistent. - if (identifier == "verbose" || identifier == "copy_all_inputs") - data.persistent = true; - else - data.persistent = false; - data.cppType = cppName; - - // Every parameter we'll get from Python will have the correct type. - data.value = boost::any(defaultValue); - - // Restore the parameters for this program. - if (identifier != "verbose" && identifier != "copy_all_inputs") - CLI::RestoreSettings(programName, false); - - // Set the function pointers that we'll need. All of these function - // pointers will be used by both the program that generates the pyx, and - // also the binding itself. (The binding itself will only use GetParam, - // GetPrintableParam, and GetRawParam.) - CLI::GetSingleton().functionMap[data.tname]["GetParam"] = &GetParam; - CLI::GetSingleton().functionMap[data.tname]["GetPrintableParam"] = - &GetPrintableParam; - - // These are used by the pyx generator. - CLI::GetSingleton().functionMap[data.tname]["PrintClassDefn"] = - &PrintClassDefn; - CLI::GetSingleton().functionMap[data.tname]["PrintDefn"] = &PrintDefn; - CLI::GetSingleton().functionMap[data.tname]["PrintDoc"] = &PrintDoc; - CLI::GetSingleton().functionMap[data.tname]["PrintOutputProcessing"] = - &PrintOutputProcessing; - CLI::GetSingleton().functionMap[data.tname]["PrintInputProcessing"] = - &PrintInputProcessing; - CLI::GetSingleton().functionMap[data.tname]["ImportDecl"] = &ImportDecl; - - // Add the ParamData object, then store. This is necessary because we may - // import more than one .so that uses CLI, so we have to keep the options - // separate. programName is a global variable from mlpack_main.hpp. - CLI::Add(std::move(data)); - if (identifier != "verbose" && identifier != "copy_all_inputs") - CLI::StoreSettings(programName); - CLI::ClearSettings(); - } -}; - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/python/strip_type.hpp b/src/sdk/mlpack/include/mlpack/bindings/python/strip_type.hpp deleted file mode 100644 index e345633d2..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/python/strip_type.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @file strip_type.hpp - * @author Ryan Curtin - * - * Given a C++ typename that may have template parameters, return stripped and - * printable versions to be used in Python bindings. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_PYTHON_STRIP_TYPE_HPP -#define MLPACK_BINDINGS_PYTHON_STRIP_TYPE_HPP - -namespace mlpack { -namespace bindings { -namespace python { - -/** - * Given an input type like, e.g., "LogisticRegression<>", return three types - * that can be used in Python code. strippedType will be a type with no - * template parameters (e.g. "LogisticRegression"), printedType will be a - * printable type with the template parameters (e.g. "LogisticRegression[]"), - * and defaultsType will be a printable type with a default template parameter - * (e.g. "LogisticRegression[T=*]") that can be used for class definitions. - */ -inline void StripType(const std::string& inputType, - std::string& strippedType, - std::string& printedType, - std::string& defaultsType) -{ - // First, we have to parse the type. If we have something like, e.g., - // 'LogisticRegression<>', we must convert this to 'LogisticRegression[T=*].' - printedType = inputType; - strippedType = inputType; - defaultsType = inputType; - if (printedType.find("<") != std::string::npos) - { - // Are there any template parameters? Or is it the default? - const size_t loc = printedType.find("<>"); - if (loc != std::string::npos) - { - // Convert it from "<>". - strippedType.replace(loc, 2, ""); - printedType.replace(loc, 2, "[]"); - defaultsType.replace(loc, 2, "[T=*]"); - } - } -} - -} // namespace python -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/tests/clean_memory.hpp b/src/sdk/mlpack/include/mlpack/bindings/tests/clean_memory.hpp deleted file mode 100644 index 97ac0191e..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/tests/clean_memory.hpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @file clean_memory.hpp - * @author Ryan Curtin - * - * Delete any unique pointers that are held by the CLI object. This is similar - * to the code in end_program.hpp. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_TESTS_CLEAN_MEMORY_HPP -#define MLPACK_BINDINGS_TESTS_CLEAN_MEMORY_HPP - -namespace mlpack { -namespace bindings { -namespace tests { - -/** - * Delete any unique pointers that are held by the CLI object. - */ -void CleanMemory(); - -} // namespace tests -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/tests/delete_allocated_memory.hpp b/src/sdk/mlpack/include/mlpack/bindings/tests/delete_allocated_memory.hpp deleted file mode 100644 index f4cf055ce..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/tests/delete_allocated_memory.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @file delete_allocated_memory.hpp - * @author Ryan Curtin - * - * If any memory has been allocated by the parameter, delete it. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_DELETE_ALLOCATED_MEMORY_HPP -#define MLPACK_BINDINGS_CLI_DELETE_ALLOCATED_MEMORY_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace tests { - -template -void DeleteAllocatedMemoryImpl( - const util::ParamData& /* d */, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - // Do nothing. -} - -template -void DeleteAllocatedMemoryImpl( - const util::ParamData& /* d */, - const typename boost::enable_if>::type* = 0) -{ - // Do nothing. -} - -template -void DeleteAllocatedMemoryImpl( - const util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // Delete the allocated memory (hopefully we actually own it). - delete *boost::any_cast(&d.value); -} - -template -void DeleteAllocatedMemory( - const util::ParamData& d, - const void* /* input */, - void* /* output */) -{ - DeleteAllocatedMemoryImpl::type>(d); -} - -} // namespace tests -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/tests/get_allocated_memory.hpp b/src/sdk/mlpack/include/mlpack/bindings/tests/get_allocated_memory.hpp deleted file mode 100644 index 852e926b3..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/tests/get_allocated_memory.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file get_allocated_memory.hpp - * @author Ryan Curtin - * - * If the parameter has a type that may need to be deleted, return the address - * of that object. Otherwise return NULL. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_CLI_GET_ALLOCATED_MEMORY_HPP -#define MLPACK_BINDINGS_CLI_GET_ALLOCATED_MEMORY_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace tests { - -template -void* GetAllocatedMemory( - const util::ParamData& /* d */, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0) -{ - return NULL; -} - -template -void* GetAllocatedMemory( - const util::ParamData& /* d */, - const typename boost::enable_if>::type* = 0) -{ - return NULL; -} - -template -void* GetAllocatedMemory( - const util::ParamData& d, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0) -{ - // Here we have a model; return its memory location. - return *boost::any_cast(&d.value); -} - -template -void GetAllocatedMemory(const util::ParamData& d, - const void* /* input */, - void* output) -{ - *((void**) output) = - GetAllocatedMemory::type>(d); -} - -} // namespace tests -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/tests/get_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/tests/get_param.hpp deleted file mode 100644 index 175d48804..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/tests/get_param.hpp +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @file get_param.hpp - * @author Ryan Curtin - * - * Use template metaprogramming to get the right type of parameter. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_TESTS_GET_PARAM_HPP -#define MLPACK_BINDINGS_TESTS_GET_PARAM_HPP - -#include - -namespace mlpack { -namespace bindings { -namespace tests { - -/** - * This overload is called when nothing special needs to happen to the name of - * the parameter. - */ -template -T& GetParam(util::ParamData& d) -{ - // No mapping is needed, so just cast it directly. - return *boost::any_cast(&d.value); -} - -/** - * Return a parameter casted to the given type. Type checking does not happen - * here! - * - * @param d Parameter information. - * @param input Unused parameter. - * @param output Place to store pointer to value. - */ -template -void GetParam(const util::ParamData& d, const void* /* input */, void* output) -{ - // Cast to the correct type. - *((T**) output) = &GetParam(const_cast(d)); -} - -} // namespace tests -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/tests/get_printable_param.hpp b/src/sdk/mlpack/include/mlpack/bindings/tests/get_printable_param.hpp deleted file mode 100644 index a8357261c..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/tests/get_printable_param.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file get_printable_param.hpp - * @author Ryan Curtin - * - * Print the parameter to stdout, using template metaprogramming to enforce - * different behavior for different parameter types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_TESTS_GET_PRINTABLE_PARAM_HPP -#define MLPACK_BINDINGS_TESTS_GET_PRINTABLE_PARAM_HPP - -#include -#include -#include - -namespace mlpack { -namespace bindings { -namespace tests { - -/** - * Print an option. - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>::type* = 0, - const typename boost::disable_if>>::type* = 0); - -/** - * Print a vector option, with spaces between it. - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0); - -/** - * Print a matrix option (this just prints the filename). - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::enable_if>::type* = 0); - -/** - * Print a serializable class option (this just prints the filename). - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* = 0, - const typename boost::enable_if>::type* = 0); - -/** - * Print a mapped matrix option (this just prints the filename). - */ -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::enable_if>>::type* = 0); - -/** - * Print an option into a std::string. This should print a short, one-line - * representation of the object. The string will be stored in the output - * pointer. - */ -template -void GetPrintableParam(const util::ParamData& data, - const void* /* input */, - void* output) -{ - *((std::string*) output) = - GetPrintableParam::type>(data); -} - -} // namespace tests -} // namespace bindings -} // namespace mlpack - -// Include implementation. -#include "get_printable_param_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/tests/get_printable_param_impl.hpp b/src/sdk/mlpack/include/mlpack/bindings/tests/get_printable_param_impl.hpp deleted file mode 100644 index f02898e23..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/tests/get_printable_param_impl.hpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file get_printable_param_impl.hpp - * @author Ryan Curtin - * - * Implementation of parameter printing functions. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_TESTS_GET_PRINTABLE_PARAM_IMPL_HPP -#define MLPACK_BINDINGS_TESTS_GET_PRINTABLE_PARAM_IMPL_HPP - -#include "get_printable_param.hpp" - -namespace mlpack { -namespace bindings { -namespace tests { - -//! Print an option. -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>::type* /* junk */, - const typename boost::disable_if>>::type* /* junk */) -{ - std::ostringstream oss; - oss << boost::any_cast(data.value); - return oss.str(); -} - -//! Print a vector option. -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::enable_if>::type* /* junk */) -{ - const T& t = boost::any_cast(data.value); - - std::ostringstream oss; - for (size_t i = 0; i < t.size(); ++i) - oss << t[i] << " "; - return oss.str(); -} - -//! Print a matrix option (this just prints 'matrix type'). -template -std::string GetPrintableParam( - const util::ParamData& /* data */, - const typename boost::enable_if>::type* /* junk */) -{ - return "matrix type"; -} - -//! Print a model option (this just prints the filename). -template -std::string GetPrintableParam( - const util::ParamData& data, - const typename boost::disable_if>::type* /* junk */, - const typename boost::enable_if>::type* /* junk */) -{ - // Extract the string from the tuple that's being held. - std::ostringstream oss; - oss << data.cppType << " model"; - return oss.str(); -} - -//! Print a mapped matrix option (this just prints 'matrix/DatasetInfo tuple'). -template -std::string GetPrintableParam( - const util::ParamData& /* data */, - const typename boost::enable_if>>::type* /* junk */) -{ - return "matrix/DatatsetInfo tuple"; -} - -} // namespace tests -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/tests/ignore_check.hpp b/src/sdk/mlpack/include/mlpack/bindings/tests/ignore_check.hpp deleted file mode 100644 index 65a7ce32c..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/tests/ignore_check.hpp +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @file ignore_check.hpp - * @author Ryan Curtin - * - * Implementation of IgnoreCheck() for Python bindings. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_BINDINGS_TEST_IGNORE_CHECK_HPP -#define MLPACK_BINDINGS_TEST_IGNORE_CHECK_HPP - -namespace mlpack { -namespace bindings { -namespace tests { - -/** - * Return whether or not a parameter check should be ignored. For test - * bindings, we do not ignore any checks, so this always returns false. - */ -template -inline bool IgnoreCheck(const T& /* t */) { return false; } - -} // namespace tests -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/bindings/tests/test_option.hpp b/src/sdk/mlpack/include/mlpack/bindings/tests/test_option.hpp deleted file mode 100644 index 32f2fd422..000000000 --- a/src/sdk/mlpack/include/mlpack/bindings/tests/test_option.hpp +++ /dev/null @@ -1,144 +0,0 @@ -/** - * @file test_option.hpp - * @author Ryan Curtin - * - * Definition of the TestOption class, which is used to define parameters for - * CLI for use inside of mlpack_test. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_BINDINGS_TESTS_TEST_OPTION_HPP -#define MLPACK_CORE_BINDINGS_TESTS_TEST_OPTION_HPP - -#include - -#include -#include "get_printable_param.hpp" -#include "get_param.hpp" -#include "get_allocated_memory.hpp" -#include "delete_allocated_memory.hpp" - -namespace mlpack { -namespace bindings { -namespace tests { - -// Defined in mlpack_main.hpp. -extern std::string programName; - -/** - * A static object whose constructor registers a parameter with the CLI class. - * This should not be used outside of CLI itself, and you should use the - * PARAM_FLAG(), PARAM_DOUBLE(), PARAM_INT(), PARAM_STRING(), or other similar - * macros to declare these objects instead of declaring them directly. - * - * @see core/util/cli.hpp, mlpack::CLI - */ -template -class TestOption -{ - public: - /** - * Construct an Option object. When constructed, it will register - * itself with CLI. - * - * @param defaultValue Default value this parameter will be initialized to - * (for flags, this should be false, for instance). - * @param identifier The name of the option (no dashes in front; for --help, - * we would pass "help"). - * @param description A short string describing the option. - * @param alias Short name of the parameter. "" for no alias. - * @param cppName Name of the C++ type of this parameter (i.e. "int"). - * @param required Whether or not the option is required at runtime. - * @param input Whether or not the option is an input option. - * @param noTranspose If the parameter is a matrix and this is true, then the - * matrix will not be transposed on loading. - * @param testName Name of the test (used for identifiying which binding test - * this option belongs to) - */ - TestOption(const N defaultValue, - const std::string& identifier, - const std::string& description, - const std::string& alias, - const std::string& cppName, - const bool required = false, - const bool input = true, - const bool noTranspose = false, - const std::string& testName = "") - { - // Create the ParamData object to give to CLI. - util::ParamData data; - - data.desc = description; - data.name = identifier; - data.tname = TYPENAME(N); - data.alias = alias[0]; - data.wasPassed = false; - data.noTranspose = noTranspose; - data.required = required; - data.input = input; - data.loaded = false; - data.cppType = cppName; - data.value = boost::any(defaultValue); - data.persistent = false; - - const std::string tname = data.tname; - - CLI::RestoreSettings(testName, false); - - // Set some function pointers that we need. - CLI::GetSingleton().functionMap[tname]["GetPrintableParam"] = - &GetPrintableParam; - CLI::GetSingleton().functionMap[tname]["GetParam"] = &GetParam; - CLI::GetSingleton().functionMap[tname]["GetAllocatedMemory"] = - &GetAllocatedMemory; - CLI::GetSingleton().functionMap[tname]["DeleteAllocatedMemory"] = - &DeleteAllocatedMemory; - - CLI::Add(std::move(data)); - - // If this is an output option, set it as passed. - if (!input) - CLI::SetPassed(identifier); - - CLI::StoreSettings(testName); - CLI::ClearSettings(); - } -}; - -/** - * A static object whose constructor registers program documentation with the - * CLI class. This should not be used outside of CLI itself, and you should use - * the PROGRAM_INFO() macro to declare these objects. Only one ProgramDoc - * object should ever exist. - * - * @see core/util/cli.hpp, mlpack::CLI - */ -class ProgramDoc -{ - public: - /** - * Construct a ProgramDoc object. When constructed, it will register itself - * with CLI. - * - * @param programName Short string representing the name of the program. - * @param documentation Long string containing documentation on how to use the - * program and what it is. No newline characters are necessary; this is - * taken care of by CLI later. - */ - ProgramDoc(const std::string& programName, - const std::string& documentation); - - //! The name of the program. - std::string programName; - //! Documentation for what the program does. - std::string documentation; -}; - -} // namespace tests -} // namespace bindings -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core.hpp b/src/sdk/mlpack/include/mlpack/core.hpp deleted file mode 100644 index 9de5b4b4b..000000000 --- a/src/sdk/mlpack/include/mlpack/core.hpp +++ /dev/null @@ -1,307 +0,0 @@ -/** - * @file core.hpp - * - * Include all of the base components required to write mlpack methods, and the - * main mlpack Doxygen documentation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_HPP -#define MLPACK_CORE_HPP - -/** - * @mainpage mlpack Documentation - * - * @section intro_sec Introduction - * - * mlpack is an intuitive, fast, and flexible C++ machine learning library with - * bindings to other languages. It is meant to be a machine learning analog to - * LAPACK, and aims to implement a wide array of machine learning methods and - * function as a "swiss army knife" for machine learning researchers. The - * mlpack development website can be found at http://mlpack.org. - * - * mlpack uses the Armadillo C++ matrix library (http://arma.sourceforge.net) - * for general matrix, vector, and linear algebra support. mlpack also uses the - * program_options, math_c99, and unit_test_framework components of the Boost - * library, and optionally uses libbfd and libdl to give backtraces when - * compiled with debugging symbols on some platforms. - * - * @section howto How To Use This Documentation - * - * This documentation is API documentation similar to Javadoc. It isn't - * necessarily a tutorial, but it does provide detailed documentation on every - * namespace, method, and class. - * - * Each mlpack namespace generally refers to one machine learning method, so - * browsing the list of namespaces provides some insight as to the breadth of - * the methods contained in the library. - * - * To generate this documentation in your own local copy of mlpack, you can - * simply use Doxygen, from the root directory of the project: - * - * @code - * $ doxygen - * @endcode - * - * @section executables Executables - * - * mlpack provides several executables so that mlpack methods can be used - * without any need for knowledge of C++. These executables are all - * self-documented, and that documentation can be accessed by running the - * executables with the '-h' or '--help' flag. - * - * A full list of executables is given below: - * - * - mlpack_adaboost - * - mlpack_approx_kfn - * - mlpack_cf - * - mlpack_decision_stump - * - mlpack_decision_tree - * - mlpack_det - * - mlpack_emst - * - mlpack_fastmks - * - mlpack_gmm_train - * - mlpack_gmm_generate - * - mlpack_gmm_probability - * - mlpack_hmm_train - * - mlpack_hmm_loglik - * - mlpack_hmm_viterbi - * - mlpack_hmm_generate - * - mlpack_hoeffding_tree - * - mlpack_kernel_pca - * - mlpack_kfn - * - mlpack_kmeans - * - mlpack_knn - * - mlpack_krann - * - mlpack_lars - * - mlpack_linear_regression - * - mlpack_local_coordinate_coding - * - mlpack_logistic_regression - * - mlpack_lsh - * - mlpack_mean_shift - * - mlpack_nbc - * - mlpack_nca - * - mlpack_pca - * - mlpack_perceptron - * - mlpack_radical - * - mlpack_range_search - * - mlpack_softmax_regression - * - mlpack_sparse_coding - * - * @section tutorial Tutorials - * - * A few short tutorials on how to use mlpack are given below. - * - * - @ref build - * - @ref build_windows - * - @ref matrices - * - @ref iodoc - * - @ref timer - * - @ref sample - * - @ref sample_ml_app - * - @ref cv - * - @ref hpt - * - @ref verinfo - * - * Tutorials on specific methods are also available. - * - * - @ref nstutorial - * - @ref lrtutorial - * - @ref rstutorial - * - @ref dettutorial - * - @ref emst_tutorial - * - @ref kmtutorial - * - @ref fmkstutorial - * - @ref amftutorial - * - * @section methods Methods in mlpack - * - * The following methods are included in mlpack: - * - * - Density Estimation Trees - mlpack::det::DTree - * - Euclidean Minimum Spanning Trees - mlpack::emst::DualTreeBoruvka - * - Gaussian Mixture Models (GMMs) - mlpack::gmm::GMM - * - Hidden Markov Models (HMMs) - mlpack::hmm::HMM - * - Kernel PCA - mlpack::kpca::KernelPCA - * - K-Means Clustering - mlpack::kmeans::KMeans - * - Least-Angle Regression (LARS/LASSO) - mlpack::regression::LARS - * - Local Coordinate Coding - mlpack::lcc::LocalCoordinateCoding - * - Locality-Sensitive Hashing - mlpack::neighbor::LSHSearch - * - Naive Bayes Classifier - mlpack::naive_bayes::NaiveBayesClassifier - * - Neighborhood Components Analysis (NCA) - mlpack::nca::NCA - * - Principal Components Analysis (PCA) - mlpack::pca::PCA - * - RADICAL (ICA) - mlpack::radical::Radical - * - Simple Least-Squares Linear Regression - - * mlpack::regression::LinearRegression - * - Sparse Coding - mlpack::sparse_coding::SparseCoding - * - Tree-based neighbor search (KNN, KFN) - mlpack::neighbor::NeighborSearch - * - Tree-based range search - mlpack::range::RangeSearch - * - * @section remarks Final Remarks - * - * mlpack contributors include: - * - * - Ryan Curtin - * - James Cline - * - Neil Slagle - * - Matthew Amidon - * - Vlad Grantcharov - * - Ajinkya Kale - * - Bill March - * - Dongryeol Lee - * - Nishant Mehta - * - Parikshit Ram - * - Rajendran Mohan - * - Trironk Kiatkungwanglai - * - Patrick Mason - * - Chip Mappus - * - Hua Ouyang - * - Long Quoc Tran - * - Noah Kauffman - * - Guillermo Colon - * - Wei Guan - * - Ryan Riegel - * - Nikolaos Vasiloglou - * - Garry Boyer - * - Andreas Löf - * - Marcus Edel - * - Mudit Raj Gupta - * - Sumedh Ghaisas - * - Michael Fox - * - Ryan Birmingham - * - Siddharth Agrawal - * - Saheb Motiani - * - Yash Vadalia - * - Abhishek Laddha - * - Vahab Akbarzadeh - * - Andrew Wells - * - Zhihao Lou - * - Udit Saxena - * - Stephen Tu - * - Jaskaran Singh - * - Shangtong Zhang - * - Hritik Jain - * - Vladimir Glazachev - * - QiaoAn Chen - * - Janzen Brewer - * - Trung Dinh - * - Tham Ngap Wei - * - Grzegorz Krajewski - * - Joseph Mariadassou - * - Pavel Zhigulin - * - Andy Fang - * - Barak Pearlmutter - * - Ivari Horm - * - Dhawal Arora - * - Alexander Leinoff - * - Palash Ahuja - * - Yannis Mentekidis - * - Ranjan Mondal - * - Mikhail Lozhnikov - * - Marcos Pividori - * - Keon Kim - * - Nilay Jain - * - Peter Lehner - * - Anuraj Kanodia - * - Ivan Georgiev - * - Shikhar Bhardwaj - * - Yashu Seth - * - Mike Izbicki - * - Sudhanshu Ranjan - * - Piyush Jaiswal - * - Dinesh Raj - * - Prasanna Patil - * - Lakshya Agrawal - * - Vivek Pal - * - Praveen Ch - * - Kirill Mishchenko - * - Abhinav Moudgil - * - Thyrix Yang - * - Sagar B Hathwar - * - Nishanth Hegde - * - Parminder Singh - * - CodeAi (deep learning bug detector) - * - Franciszek Stokowacki - * - Samikshya Chand - * - N Rajiv Vaidyanathan - * - Kartik Nighania - * - Eugene Freyman - * - Manish Kumar - * - Haritha Sreedharan Nair - * - Sourabh Varshney - * - Projyal Dev - * - Nikhil Goel - * - Shikhar Jaiswal - * - B Kartheek Reddy - * - Atharva Khandait - * - Wenhao Huang - * - Roberto Hueso - * - Prabhat Sharma - * - Tan Jun An - * - Moksh Jain - * - Manthan-R-Sheth - * - Namrata Mukhija - * - Rohan Raj - * - Conrad Sanderson - * - Thanasis Mattas - * - Shashank Shekhar - * - Yasmine Dumouchel - * - German Lancioni - */ - -// First, include all of the prerequisites. -#include - -// Now the core mlpack classes. -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// mlpack::backtrace only for linux -#ifdef HAS_BFD_DL - #include -#endif - -// Include kernel traits. -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Use OpenMP if compiled with -DHAS_OPENMP. -#ifdef HAS_OPENMP - #include -#endif - -// Use Armadillo's C++ version detection. -#ifdef ARMA_USE_CXX11 - #define MLPACK_USE_CX11 -#endif - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/Cube_extra_bones.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/Cube_extra_bones.hpp deleted file mode 100644 index 23a079947..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/Cube_extra_bones.hpp +++ /dev/null @@ -1,3 +0,0 @@ -//! Add a serialization operator. -template -void serialize(Archive& ar, const unsigned int version); diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/Cube_extra_meat.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/Cube_extra_meat.hpp deleted file mode 100644 index a2ebd94cb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/Cube_extra_meat.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// Add a serialization operator. -template -template -void Cube::serialize(Archive& ar, const unsigned int /* version */) -{ - using boost::serialization::make_nvp; - using boost::serialization::make_array; - - const uword old_n_elem = n_elem; - - // This is accurate from Armadillo 3.6.0 onwards. - // We can't use BOOST_SERIALIZATION_NVP() because of the access::rw() call. - ar & make_nvp("n_rows", access::rw(n_rows)); - ar & make_nvp("n_cols", access::rw(n_cols)); - ar & make_nvp("n_elem_slice", access::rw(n_elem_slice)); - ar & make_nvp("n_slices", access::rw(n_slices)); - ar & make_nvp("n_elem", access::rw(n_elem)); - - // mem_state will always be 0 on load, so we don't need to save it. - if (Archive::is_loading::value) - { - // Don't free if local memory is being used. - if (mem_state == 0 && mem != NULL && old_n_elem > arma_config::mat_prealloc) - { - memory::release(access::rw(mem)); - } - - access::rw(mem_state) = 0; - - // We also need to allocate the memory we're using. - init_cold(); - } - - ar & make_array(access::rwp(mem), n_elem); -} diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/Mat_extra_bones.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/Mat_extra_bones.hpp deleted file mode 100644 index 05299fc2e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/Mat_extra_bones.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (C) 2008-2016 National ICT Australia (NICTA) -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------- -// -// Written by Conrad Sanderson - http://conradsanderson.id.au -// Written by Ryan Curtin - -//! Add a serialization operator. -template -void serialize(Archive& ar, const unsigned int version); - -/** - * These will help us refer the proper vector / column types, only with - * specifying the matrix type we want to use. - */ - -typedef Col vec_type; -typedef Col col_type; -typedef Row row_type; - -/* - * Add row_col_iterator and row_col_const_iterator to arma::Mat. - */ \ No newline at end of file diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/Mat_extra_meat.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/Mat_extra_meat.hpp deleted file mode 100644 index 477171607..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/Mat_extra_meat.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (C) 2008-2016 National ICT Australia (NICTA) -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------- -// -// Written by Conrad Sanderson - http://conradsanderson.id.au -// Written by Ryan Curtin - -// Add a serialization operator. -template -template -void Mat::serialize(Archive& ar, const unsigned int /* version */) -{ - using boost::serialization::make_nvp; - using boost::serialization::make_array; - - const uword old_n_elem = n_elem; - - // This is accurate from Armadillo 3.6.0 onwards. - // We can't use BOOST_SERIALIZATION_NVP() because of the access::rw() call. - ar & make_nvp("n_rows", access::rw(n_rows)); - ar & make_nvp("n_cols", access::rw(n_cols)); - ar & make_nvp("n_elem", access::rw(n_elem)); - ar & make_nvp("vec_state", access::rw(vec_state)); - - // mem_state will always be 0 on load, so we don't need to save it. - if (Archive::is_loading::value) - { - // Don't free if local memory is being used. - if (mem_state == 0 && mem != NULL && old_n_elem > arma_config::mat_prealloc) - { - memory::release(access::rw(mem)); - } - - access::rw(mem_state) = 0; - - // We also need to allocate the memory we're using. - init_cold(); - } - - ar & make_array(access::rwp(mem), n_elem); -} \ No newline at end of file diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/SpMat_extra_bones.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/SpMat_extra_bones.hpp deleted file mode 100644 index 8f2bcabb2..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/SpMat_extra_bones.hpp +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (C) 2008-2015 National ICT Australia (NICTA) -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------- -// -// Written by Conrad Sanderson - http://conradsanderson.id.au -// Written by Ryan Curtin -// Written by Matthew Amidon - -/** - * Add a batch constructor for SpMat, if the version is older than 3.810.0, and - * also a serialize() function for Armadillo. - */ -template -void serialize(Archive& ar, const unsigned int version); - -/** - * These will help us refer the proper vector / column types, only with - * specifying the matrix type we want to use. - */ -typedef SpCol vec_type; -typedef SpCol col_type; -typedef SpRow row_type; \ No newline at end of file diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/SpMat_extra_meat.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/SpMat_extra_meat.hpp deleted file mode 100644 index f21a4f672..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/SpMat_extra_meat.hpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (C) 2008-2015 National ICT Australia (NICTA) -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------- -// -// Written by Conrad Sanderson - http://conradsanderson.id.au -// Written by Ryan Curtin -// Written by Matthew Amidon - -/** - * Add a serialization function. - */ -template -template -void SpMat::serialize(Archive& ar, const unsigned int /* version */) -{ - using boost::serialization::make_nvp; - using boost::serialization::make_array; - - // This is accurate from Armadillo 3.6.0 onwards. - // We can't use BOOST_SERIALIZATION_NVP() because of the access::rw() call. - ar & make_nvp("n_rows", access::rw(n_rows)); - ar & make_nvp("n_cols", access::rw(n_cols)); - ar & make_nvp("n_elem", access::rw(n_elem)); - ar & make_nvp("n_nonzero", access::rw(n_nonzero)); - ar & make_nvp("vec_state", access::rw(vec_state)); - - // Now we have to serialize the values, row indices, and column pointers. - // If we are loading, we need to initialize space for these things. - if (Archive::is_loading::value) - { - const uword new_n_nonzero = n_nonzero; // Save this; we're about to nuke it. - init(n_rows, n_cols); // Allocate column pointers. - mem_resize(new_n_nonzero); // Allocate storage. - // These calls will set the sentinel values at the end of the storage and - // column pointers, if necessary, so we don't need to worry about them. - } - - ar & make_array(access::rwp(values), n_nonzero); - ar & make_array(access::rwp(row_indices), n_nonzero); - ar & make_array(access::rwp(col_ptrs), n_cols + 1); -} \ No newline at end of file diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/arma_extend.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/arma_extend.hpp deleted file mode 100644 index bcf6088a4..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/arma_extend.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/*** - * @file arma_extend.hpp - * @author Ryan Curtin - * - * Include Armadillo extensions which currently are not part of the main - * Armadillo codebase. - * - * This will allow the use of the ccov() function (which performs the same - * function as cov(trans(X)) but without the cost of computing trans(X)). This - * also gives sparse matrix support, if it is necessary. - */ -#ifndef MLPACK_CORE_ARMA_EXTEND_ARMA_EXTEND_HPP -#define MLPACK_CORE_ARMA_EXTEND_ARMA_EXTEND_HPP - -// Add batch constructor for sparse matrix (if version <= 3.810.0). -#define ARMA_EXTRA_SPMAT_PROTO mlpack/core/arma_extend/SpMat_extra_bones.hpp -#define ARMA_EXTRA_SPMAT_MEAT mlpack/core/arma_extend/SpMat_extra_meat.hpp - -// Add row_col_iterator and row_col_const_iterator for Mat. -#define ARMA_EXTRA_MAT_PROTO mlpack/core/arma_extend/Mat_extra_bones.hpp -#define ARMA_EXTRA_MAT_MEAT mlpack/core/arma_extend/Mat_extra_meat.hpp - -// Add boost serialization for Cube. -#define ARMA_EXTRA_CUBE_PROTO mlpack/core/arma_extend/Cube_extra_bones.hpp -#define ARMA_EXTRA_CUBE_MEAT mlpack/core/arma_extend/Cube_extra_meat.hpp - -// Manually set ARMA_{64,32}BIT_WORD for _WIN64 or win32 -#if defined(_MSC_VER) - #ifdef _WIN64 - #define ARMA_64BIT_WORD - #ifdef ARMA_32BIT_WORD - #undef ARMA_32BIT_WORD - #endif - #else - #define ARMA_32BIT_WORD - #ifdef ARMA_64BIT_WORD - #undef ARMA_64BIT_WORD - #endif - #endif -#endif - -// Make sure that U64 and S64 support is enabled. -#ifndef ARMA_USE_U64S64 - #define ARMA_USE_U64S64 -#endif - -// Include everything we'll need for serialize(). -#include -#include -#include - -#include - -namespace arma { - // u64/s64 - #include "hdf5_misc.hpp" - - // ccov() - #include "op_ccov_proto.hpp" - #include "op_ccov_meat.hpp" - #include "glue_ccov_proto.hpp" - #include "glue_ccov_meat.hpp" - #include "fn_ccov.hpp" - - // inplace_reshape() - #include "fn_inplace_reshape.hpp" -}; - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/fn_ccov.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/fn_ccov.hpp deleted file mode 100644 index 86f3ecb81..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/fn_ccov.hpp +++ /dev/null @@ -1,34 +0,0 @@ -//! \addtogroup fn_ccov -//! @{ - - - -template -inline -const Op -ccov(const Base& X, const uword norm_type = 0) - { - arma_extra_debug_sigprint(); - - arma_debug_check( (norm_type > 1), "ccov(): norm_type must be 0 or 1"); - - return Op(X.get_ref(), norm_type, 0); - } - - - -template -inline -const Glue -cov(const Base& A, const Base& B, const uword norm_type = 0) - { - arma_extra_debug_sigprint(); - - arma_debug_check( (norm_type > 1), "ccov(): norm_type must be 0 or 1"); - - return Glue(A.get_ref(), B.get_ref(), norm_type); - } - - - -//! @} diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/fn_inplace_reshape.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/fn_inplace_reshape.hpp deleted file mode 100644 index 8c098f068..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/fn_inplace_reshape.hpp +++ /dev/null @@ -1,33 +0,0 @@ -//! \addtogroup fn_inplace_reshape -//! @{ - - - -/** - * This does not handle column vectors or row vectors entirely correctly. You - * should be able to do multiplication or other basic operations with the - * resulting matrix, but it may have other problems. So if you are using this - * on vectors (arma::Col<> or arma::Row<>), be careful, and be warned that - * bizarre behavior may occur. - */ -template -inline -Mat& -inplace_reshape(Mat& X, - const uword new_n_rows, - const uword new_n_cols) - { - arma_extra_debug_sigprint(); - - arma_debug_check((new_n_rows * new_n_cols) != X.n_elem, - "inplace_reshape(): cannot add or remove elements"); - - access::rw(X.n_rows) = new_n_rows; - access::rw(X.n_cols) = new_n_cols; - - return X; - } - - - -//! @} diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/glue_ccov_meat.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/glue_ccov_meat.hpp deleted file mode 100644 index c3589c368..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/glue_ccov_meat.hpp +++ /dev/null @@ -1,144 +0,0 @@ -//! \addtogroup glue_cov -//! @{ - - - -template -inline -void -glue_ccov::direct_ccov(Mat& out, const Mat& A, const Mat& B, const uword norm_type) - { - arma_extra_debug_sigprint(); - - if(A.is_vec() && B.is_vec()) - { - arma_debug_check( (A.n_elem != B.n_elem), "ccov(): the number of elements in A and B must match" ); - - const eT* A_ptr = A.memptr(); - const eT* B_ptr = B.memptr(); - - eT A_acc = eT(0); - eT B_acc = eT(0); - eT out_acc = eT(0); - - const uword N = A.n_elem; - - for(uword i=0; i 1) ? eT(N-1) : eT(1) ) : eT(N); - - out.set_size(1,1); - out[0] = out_acc/norm_val; - } - else - { - arma_debug_assert_same_size(A, B, "ccov()"); - - const uword N = A.n_cols; - const eT norm_val = (norm_type == 0) ? ( (N > 1) ? eT(N-1) : eT(1) ) : eT(N); - - out = A * trans(B); - out -= (sum(A) * trans(sum(B))) / eT(N); - out /= norm_val; - } - } - - - -template -inline -void -glue_ccov::direct_ccov(Mat< std::complex >& out, const Mat< std::complex >& A, const Mat< std::complex >& B, const uword norm_type) - { - arma_extra_debug_sigprint(); - - typedef typename std::complex eT; - - if(A.is_vec() && B.is_vec()) - { - arma_debug_check( (A.n_elem != B.n_elem), "cov(): the number of elements in A and B must match" ); - - const eT* A_ptr = A.memptr(); - const eT* B_ptr = B.memptr(); - - eT A_acc = eT(0); - eT B_acc = eT(0); - eT out_acc = eT(0); - - const uword N = A.n_elem; - - for(uword i=0; i 1) ? eT(N-1) : eT(1) ) : eT(N); - - out.set_size(1,1); - out[0] = out_acc/norm_val; - } - else - { - arma_debug_assert_same_size(A, B, "ccov()"); - - const uword N = A.n_cols; - const eT norm_val = (norm_type == 0) ? ( (N > 1) ? eT(N-1) : eT(1) ) : eT(N); - - out = A * trans(conj(B)); - out -= (sum(A) * trans(conj(sum(B)))) / eT(N); - out /= norm_val; - } - } - - - -template -inline -void -glue_ccov::apply(Mat& out, const Glue& X) - { - arma_extra_debug_sigprint(); - - typedef typename T1::elem_type eT; - - const unwrap_check A_tmp(X.A, out); - const unwrap_check B_tmp(X.B, out); - - const Mat& A = A_tmp.M; - const Mat& B = B_tmp.M; - - const uword norm_type = X.aux_uword; - - if(&A != &B) - { - glue_ccov::direct_ccov(out, A, B, norm_type); - } - else - { - op_ccov::direct_ccov(out, A, norm_type); - } - - } - - - -//! @} diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/glue_ccov_proto.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/glue_ccov_proto.hpp deleted file mode 100644 index f5531175d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/glue_ccov_proto.hpp +++ /dev/null @@ -1,15 +0,0 @@ -//! \addtogroup glue_ccov -//! @{ - -class glue_ccov - { - public: - - template inline static void direct_ccov(Mat& out, const Mat& A, const Mat& B, const uword norm_type); - template inline static void direct_ccov(Mat< std::complex >& out, const Mat< std::complex >& A, const Mat< std::complex >& B, const uword norm_type); - - template inline static void apply(Mat& out, const Glue& X); - }; - -//! @} - diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/hdf5_misc.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/hdf5_misc.hpp deleted file mode 100644 index 6cd42dab8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/hdf5_misc.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2012-2013 National ICT Australia (NICTA) -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------- -// -// Written by Conrad Sanderson - http://conradsanderson.id.au -// Written by Ryan Curtin -// Written by Szabolcs Horvat - -// To hack in u64/s64 support to Armadillo when it is not compiled with -// ARMA_64BIT_WORD. -namespace hdf5_misc { - -#if defined(ARMA_USE_HDF5) - #if !(defined(ARMA_64BIT_WORD) || defined(ARMA_USE_U64S64)) - #if defined(ULLONG_MAX) - template<> - inline - hid_t - get_hdf5_type< long long >() - { - return H5Tcopy(H5T_NATIVE_LLONG); - } - - template<> - inline - hid_t - get_hdf5_type< unsigned long long >() - { - return H5Tcopy(H5T_NATIVE_ULLONG); - } - #endif - #endif -#endif - -} // namespace hdf5_misc diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/op_ccov_meat.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/op_ccov_meat.hpp deleted file mode 100644 index 93c09f280..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/op_ccov_meat.hpp +++ /dev/null @@ -1,97 +0,0 @@ -//! \addtogroup op_cov -//! @{ - - - -template -inline -void -op_ccov::direct_ccov(Mat& out, const Mat& A, const uword norm_type) - { - arma_extra_debug_sigprint(); - - if(A.is_vec()) - { - if(A.n_rows == 1) - { - out = var(trans(A), norm_type); - } - else - { - out = var(A, norm_type); - } - } - else - { - const uword N = A.n_cols; - const eT norm_val = (norm_type == 0) ? ( (N > 1) ? eT(N-1) : eT(1) ) : eT(N); - - const Col acc = sum(A, 1); - - out = A * trans(A); - out -= (acc * trans(acc)) / eT(N); - out /= norm_val; - } - } - - - -template -inline -void -op_ccov::direct_ccov(Mat< std::complex >& out, const Mat< std::complex >& A, const uword norm_type) - { - arma_extra_debug_sigprint(); - - typedef typename std::complex eT; - - if(A.is_vec()) - { - if(A.n_rows == 1) - { - const Mat tmp_mat = var(trans(A), norm_type); - out.set_size(1,1); - out[0] = tmp_mat[0]; - } - else - { - const Mat tmp_mat = var(A, norm_type); - out.set_size(1,1); - out[0] = tmp_mat[0]; - } - } - else - { - const uword N = A.n_cols; - const eT norm_val = (norm_type == 0) ? ( (N > 1) ? eT(N-1) : eT(1) ) : eT(N); - - const Col acc = sum(A, 1); - - out = A * trans(conj(A)); - out -= (acc * trans(conj(acc))) / eT(N); - out /= norm_val; - } - } - - - -template -inline -void -op_ccov::apply(Mat& out, const Op& in) - { - arma_extra_debug_sigprint(); - - typedef typename T1::elem_type eT; - - const unwrap_check tmp(in.m, out); - const Mat& A = tmp.M; - - const uword norm_type = in.aux_uword_a; - - op_ccov::direct_ccov(out, A, norm_type); - } - - - -//! @} diff --git a/src/sdk/mlpack/include/mlpack/core/arma_extend/op_ccov_proto.hpp b/src/sdk/mlpack/include/mlpack/core/arma_extend/op_ccov_proto.hpp deleted file mode 100644 index 4fb49eb65..000000000 --- a/src/sdk/mlpack/include/mlpack/core/arma_extend/op_ccov_proto.hpp +++ /dev/null @@ -1,18 +0,0 @@ -//! \addtogroup op_cov -//! @{ - - - -class op_ccov - { - public: - - template inline static void direct_ccov(Mat& out, const Mat& X, const uword norm_type); - template inline static void direct_ccov(Mat< std::complex >& out, const Mat< std::complex >& X, const uword norm_type); - - template inline static void apply(Mat& out, const Op& in); - }; - - - -//! @} diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/bernoulli.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/bernoulli.hpp deleted file mode 100644 index 4e8ee6f92..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/bernoulli.hpp +++ /dev/null @@ -1,176 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////// -// Copyright 2013 Nikhar Agrawal -// Copyright 2013 Christopher Kormanyos -// Copyright 2013 John Maddock -// Copyright 2013 Paul Bristow -// Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _BOOST_BERNOULLI_B2N_2013_05_30_HPP_ -#define _BOOST_BERNOULLI_B2N_2013_05_30_HPP_ - -#include "math_fwd.hpp" - -// Forward declarations from math_fwd -namespace boost { namespace math{ - template - T unchecked_bernoulli_b2n(const std::size_t n); - template - T bernoulli_b2n(const int i, const Policy &pol); - template - T bernoulli_b2n(const int i); - template - OutputIterator bernoulli_b2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it, - const Policy& pol); - template - OutputIterator bernoulli_b2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it); - template - T tangent_t2n(const int i, const Policy &pol); - template - T tangent_t2n(const int i); - template - OutputIterator tangent_t2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it, - const Policy& pol); - template - OutputIterator tangent_t2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it); -}} - -#include "detail/unchecked_bernoulli.hpp" -#include "detail/bernoulli_details.hpp" - -namespace boost { namespace math { - -namespace detail { - -template -OutputIterator bernoulli_number_imp(OutputIterator out, std::size_t start, std::size_t n, const Policy& pol, const mpl::int_& tag) -{ - for(std::size_t i = start; (i <= max_bernoulli_b2n::value) && (i < start + n); ++i) - { - *out = unchecked_bernoulli_imp(i, tag); - ++out; - } - - for(std::size_t i = (std::max)(static_cast(max_bernoulli_b2n::value + 1), start); i < start + n; ++i) - { - // We must overflow: - *out = (i & 1 ? 1 : -1) * policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(n)", 0, T(i), pol); - ++out; - } - return out; -} - -template -OutputIterator bernoulli_number_imp(OutputIterator out, std::size_t start, std::size_t n, const Policy& pol, const mpl::int_<0>& tag) -{ - for(std::size_t i = start; (i <= max_bernoulli_b2n::value) && (i < start + n); ++i) - { - *out = unchecked_bernoulli_imp(i, tag); - ++out; - } - // - // Short circuit return so we don't grab the mutex below unless we have to: - // - if(start + n <= max_bernoulli_b2n::value) - return out; - - return get_bernoulli_numbers_cache().copy_bernoulli_numbers(out, start, n, pol); -} - -} // namespace detail - -template -inline T bernoulli_b2n(const int i, const Policy &pol) -{ - typedef mpl::int_::value> tag_type; - if(i < 0) - return policies::raise_domain_error("boost::math::bernoulli_b2n<%1%>", "Index should be >= 0 but got %1%", T(i), pol); - - T result = static_cast(0); // The = 0 is just to silence compiler warnings :-( - boost::math::detail::bernoulli_number_imp(&result, static_cast(i), 1u, pol, tag_type()); - return result; -} - -template -inline T bernoulli_b2n(const int i) -{ - return boost::math::bernoulli_b2n(i, policies::policy<>()); -} - -template -inline OutputIterator bernoulli_b2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it, - const Policy& pol) -{ - typedef mpl::int_::value> tag_type; - if(start_index < 0) - { - *out_it = policies::raise_domain_error("boost::math::bernoulli_b2n<%1%>", "Index should be >= 0 but got %1%", T(start_index), pol); - return ++out_it; - } - - return boost::math::detail::bernoulli_number_imp(out_it, start_index, number_of_bernoullis_b2n, pol, tag_type()); -} - -template -inline OutputIterator bernoulli_b2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it) -{ - return boost::math::bernoulli_b2n(start_index, number_of_bernoullis_b2n, out_it, policies::policy<>()); -} - -template -inline T tangent_t2n(const int i, const Policy &pol) -{ - if(i < 0) - return policies::raise_domain_error("boost::math::tangent_t2n<%1%>", "Index should be >= 0 but got %1%", T(i), pol); - - T result; - boost::math::detail::get_bernoulli_numbers_cache().copy_tangent_numbers(&result, i, 1, pol); - return result; -} - -template -inline T tangent_t2n(const int i) -{ - return boost::math::tangent_t2n(i, policies::policy<>()); -} - -template -inline OutputIterator tangent_t2n(const int start_index, - const unsigned number_of_tangent_t2n, - OutputIterator out_it, - const Policy& pol) -{ - if(start_index < 0) - { - *out_it = policies::raise_domain_error("boost::math::tangent_t2n<%1%>", "Index should be >= 0 but got %1%", T(start_index), pol); - return ++out_it; - } - - return boost::math::detail::get_bernoulli_numbers_cache().copy_tangent_numbers(out_it, start_index, number_of_tangent_t2n, pol); -} - -template -inline OutputIterator tangent_t2n(const int start_index, - const unsigned number_of_tangent_t2n, - OutputIterator out_it) -{ - return boost::math::tangent_t2n(start_index, number_of_tangent_t2n, out_it, policies::policy<>()); -} - -} } // namespace boost::math - -#endif // _BOOST_BERNOULLI_B2N_2013_05_30_HPP_ diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/boost_backport_math.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/boost_backport_math.hpp deleted file mode 100644 index f3d7f3cc3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/boost_backport_math.hpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @file boost_backport.hpp - * @author Yannis Mentekidis - * - * Centralized control of what boost files to include. We have backported the - * following boost functionality here: - * - * * trigamma and polygamma function evaluation (added in boost 1.58.0) - * - * For versions 1.56, 1.57 we include the backported polygamma and trigamma - * functions. Anything newer, we include from Boost. - */ -#ifndef MLPACK_CORE_BOOST_BACKPORT_MATH_HPP -#define MLPACK_CORE_BOOST_BACKPORT_MATH_HPP - -#include - -#if BOOST_VERSION < 105800 - // Backported trigamma and polygamma. - #include "mlpack/core/boost_backport/trigamma.hpp" - #include "mlpack/core/boost_backport/polygamma.hpp" -#else - // Boost's version. - #include - #include -#endif - -#endif // MLPACK_CORE_BOOST_BACKPORT_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/boost_backport_serialization.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/boost_backport_serialization.hpp deleted file mode 100644 index 173761f5f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/boost_backport_serialization.hpp +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @file boost_backport.hpp - * @author Yannis Mentekidis - * - * Centralized control of what boost files to include. We have backported the - * following boost functionality here: - * - * * unordered_set serialization support (added in boost 1.56.0) - * * vector serialization (changed after boost 1.58.0) - * - * If the detected boost version is greater than 1.58.0, we include the normal - * serialization functions (not the backported ones). For all older versions we - * include the backported headers. - */ -#ifndef MLPACK_CORE_BOOST_BACKPORT_SERIALIZATION_HPP -#define MLPACK_CORE_BOOST_BACKPORT_SERIALIZATION_HPP - -#include - -#if BOOST_VERSION < 105600 - // Backported unordered_map. - #include "mlpack/core/boost_backport/unordered_map.hpp" -#else - // Boost's version. - #include -#endif - -#if BOOST_VERSION == 105800 - /** - * Boost versions 1.58.0 and earlier have a different vector serialization - * behaivor as compared to later versions. Notably, loading a - * std::vector does not clear the vector before the load - * in v1.58 and earlier; while in the later versions, the vector is cleared - * before loading. This causes some tests related to serialization to fail - * with versions 1.58. This backport solves the issue. - */ - #ifdef BOOST_SERIALIZATION_VECTOR_HPP - #pragma message "Detected Boost version is 1.58. Including\ - boost/serialization/vector.hpp before mlpack/core.hpp can cause problems. It\ - should only be necessary to include mlpack/core.hpp and not\ - boost/serialization/vector.hpp." - #endif - #include "mlpack/core/boost_backport/collections_load_imp.hpp" - #include "mlpack/core/boost_backport/collections_save_imp.hpp" - #include "mlpack/core/boost_backport/vector.hpp" -#else - #include -#endif - -#endif // MLPACK_CORE_BOOST_BACKPORT_SERIALIZATION_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/collections_load_imp.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/collections_load_imp.hpp deleted file mode 100644 index 93d64d72b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/collections_load_imp.hpp +++ /dev/null @@ -1,105 +0,0 @@ -#ifndef BOOST_SERIALIZATION_COLLECTIONS_LOAD_IMP_HPP -#define BOOST_SERIALIZATION_COLLECTIONS_LOAD_IMP_HPP - -// MS compatible compilers support #pragma once -#if defined(_MSC_VER) -# pragma once -#endif - -#if defined(_MSC_VER) && (_MSC_VER <= 1020) -# pragma warning (disable : 4786) // too long name, harmless warning -#endif - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// collections_load_imp.hpp: serialization for loading stl collections - -// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . -// Use, modification and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for updates, documentation, and revision history. - -// helper function templates for serialization of collections - -#include -#include // size_t -#include // msvc 6.0 needs this for warning suppression -#if defined(BOOST_NO_STDC_NAMESPACE) -namespace std{ - using ::size_t; -} // namespace std -#endif -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace serialization { -namespace stl { - -////////////////////////////////////////////////////////////////////// -// implementation of serialization for STL containers -// - -template< - class Archive, - class T -> -typename boost::enable_if< - typename detail::is_default_constructible< - typename T::value_type - >, - void ->::type -collection_load_impl( - Archive & ar, - T & t, - collection_size_type count, - item_version_type -){ - t.resize(count); - typename T::iterator hint; - hint = t.begin(); - while(count-- > 0){ - ar >> boost::serialization::make_nvp("item", *hint++); - } -} - -template< - class Archive, - class T -> -typename boost::disable_if< - typename detail::is_default_constructible< - typename T::value_type - >, - void ->::type -collection_load_impl( - Archive & ar, - T & t, - collection_size_type count, - item_version_type item_version -){ - t.clear(); - while(count-- > 0){ - detail::stack_construct u(ar, item_version); - ar >> boost::serialization::make_nvp("item", u.reference()); - t.push_back(u.reference()); - ar.reset_object_address(& t.back() , & u.reference()); - } -} - -} // namespace stl -} // namespace serialization -} // namespace boost - -#endif //BOOST_SERIALIZATION_COLLECTIONS_LOAD_IMP_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/collections_save_imp.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/collections_save_imp.hpp deleted file mode 100644 index f3cabfcf3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/collections_save_imp.hpp +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP -#define BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP - -// MS compatible compilers support #pragma once -#if defined(_MSC_VER) -# pragma once -#endif - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// collections_save_imp.hpp: serialization for stl collections - -// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . -// Use, modification and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for updates, documentation, and revision history. - -// helper function templates for serialization of collections - -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace serialization { -namespace stl { - -////////////////////////////////////////////////////////////////////// -// implementation of serialization for STL containers -// - -template -inline void save_collection( - Archive & ar, - const Container &s, - collection_size_type count) -{ - ar << BOOST_SERIALIZATION_NVP(count); - // record number of elements - const item_version_type item_version( - version::value - ); - #if 0 - boost::archive::library_version_type library_version( - ar.get_library_version() - ); - if(boost::archive::library_version_type(3) < library_version){ - ar << BOOST_SERIALIZATION_NVP(item_version); - } - #else - ar << BOOST_SERIALIZATION_NVP(item_version); - #endif - - typename Container::const_iterator it = s.begin(); - while(count-- > 0){ - // note borland emits a no-op without the explicit namespace - boost::serialization::save_construct_data_adl( - ar, - &(*it), - item_version - ); - ar << boost::serialization::make_nvp("item", *it++); - } -} - -template -inline void save_collection(Archive & ar, const Container &s) -{ - // record number of elements - collection_size_type count(s.size()); - save_collection(ar, s, count); -} - -} // namespace stl -} // namespace serialization -} // namespace boost - -#endif //BOOST_SERIALIZATION_COLLECTIONS_SAVE_IMP_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/bernoulli_details.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/bernoulli_details.hpp deleted file mode 100644 index d07d796b1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/bernoulli_details.hpp +++ /dev/null @@ -1,660 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// Copyright 2013 John Maddock -// Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#ifndef BOOST_MATH_BERNOULLI_DETAIL_HPP_ -#define BOOST_MATH_BERNOULLI_DETAIL_HPP_ - -#include "../math_fwd.hpp" -#include -#include -#include -#include - -#ifdef BOOST_HAS_THREADS - -#ifndef BOOST_NO_CXX11_HDR_ATOMIC -# include -# define BOOST_MATH_ATOMIC_NS std -#if ATOMIC_INT_LOCK_FREE == 2 -typedef std::atomic atomic_counter_type; -typedef int atomic_integer_type; -#elif ATOMIC_SHORT_LOCK_FREE == 2 -typedef std::atomic atomic_counter_type; -typedef short atomic_integer_type; -#elif ATOMIC_LONG_LOCK_FREE == 2 -typedef std::atomic atomic_counter_type; -typedef long atomic_integer_type; -#elif ATOMIC_LLONG_LOCK_FREE == 2 -typedef std::atomic atomic_counter_type; -typedef long long atomic_integer_type; -#else -# define BOOST_MATH_NO_ATOMIC_INT -#endif - -#else // BOOST_NO_CXX11_HDR_ATOMIC -// -// We need Boost.Atomic, but on any platform that supports auto-linking we do -// not need to link against a separate library: -// -#define BOOST_ATOMIC_NO_LIB -#include -# define BOOST_MATH_ATOMIC_NS boost - -namespace boost{ namespace math{ namespace detail{ - -// -// We need a type to use as an atomic counter: -// -#if BOOST_ATOMIC_INT_LOCK_FREE == 2 -typedef boost::atomic atomic_counter_type; -typedef int atomic_integer_type; -#elif BOOST_ATOMIC_SHORT_LOCK_FREE == 2 -typedef boost::atomic atomic_counter_type; -typedef short atomic_integer_type; -#elif BOOST_ATOMIC_LONG_LOCK_FREE == 2 -typedef boost::atomic atomic_counter_type; -typedef long atomic_integer_type; -#elif BOOST_ATOMIC_LLONG_LOCK_FREE == 2 -typedef boost::atomic atomic_counter_type; -typedef long long atomic_integer_type; -#else -# define BOOST_MATH_NO_ATOMIC_INT -#endif - -}}} // namespaces - -#endif // BOOST_NO_CXX11_HDR_ATOMIC - -#endif // BOOST_HAS_THREADS - -namespace boost{ namespace math{ namespace detail{ -// -// Asymptotic expansion for B2n due to -// Luschny LogB3 formula (http://www.luschny.de/math/primes/bernincl.html) -// -template -T b2n_asymptotic(int n) -{ - BOOST_MATH_STD_USING - const T nx = static_cast(n); - const T nx2(nx * nx); - - const T approximate_log_of_bernoulli_bn = - ((boost::math::constants::half() + nx) * log(nx)) - + ((boost::math::constants::half() - nx) * log(boost::math::constants::pi())) - + (((T(3) / 2) - nx) * boost::math::constants::ln_two()) - + ((nx * (T(2) - (nx2 * 7) * (1 + ((nx2 * 30) * ((nx2 * 12) - 1))))) / (((nx2 * nx2) * nx2) * 2520)); - return ((n / 2) & 1 ? 1 : -1) * (approximate_log_of_bernoulli_bn > tools::log_max_value() - ? policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, nx, Policy()) - : static_cast(exp(approximate_log_of_bernoulli_bn))); -} - -template -T t2n_asymptotic(int n) -{ - BOOST_MATH_STD_USING - // Just get B2n and convert to a Tangent number: - T t2n = fabs(b2n_asymptotic(2 * n)) / (2 * n); - T p2 = ldexp(T(1), n); - if(tools::max_value() / p2 < t2n) - return policies::raise_overflow_error("boost::math::tangent_t2n<%1%>(std::size_t)", 0, T(n), Policy()); - t2n *= p2; - p2 -= 1; - if(tools::max_value() / p2 < t2n) - return policies::raise_overflow_error("boost::math::tangent_t2n<%1%>(std::size_t)", 0, Policy()); - t2n *= p2; - return t2n; -} -// -// We need to know the approximate value of /n/ which will -// cause bernoulli_b2n(n) to return infinity - this allows -// us to elude a great deal of runtime checking for values below -// n, and only perform the full overflow checks when we know that we're -// getting close to the point where our calculations will overflow. -// We use Luschny's LogB3 formula (http://www.luschny.de/math/primes/bernincl.html) -// to find the limit, and since we're dealing with the log of the Bernoulli numbers -// we need only perform the calculation at double precision and not with T -// (which may be a multiprecision type). The limit returned is within 1 of the true -// limit for all the types tested. Note that although the code below is basically -// the same as b2n_asymptotic above, it has been recast as a continuous real-valued -// function as this makes the root finding go smoother/faster. It also omits the -// sign of the Bernoulli number. -// -struct max_bernoulli_root_functor -{ - max_bernoulli_root_functor(long long t) : target(static_cast(t)) {} - double operator()(double n) - { - BOOST_MATH_STD_USING - - // Luschny LogB3(n) formula. - - const double nx2(n * n); - - const double approximate_log_of_bernoulli_bn - = ((boost::math::constants::half() + n) * log(n)) - + ((boost::math::constants::half() - n) * log(boost::math::constants::pi())) - + (((double(3) / 2) - n) * boost::math::constants::ln_two()) - + ((n * (2 - (nx2 * 7) * (1 + ((nx2 * 30) * ((nx2 * 12) - 1))))) / (((nx2 * nx2) * nx2) * 2520)); - - return approximate_log_of_bernoulli_bn - target; - } -private: - double target; -}; - -template -inline std::size_t find_bernoulli_overflow_limit(const mpl::false_&) -{ - long long t = lltrunc(boost::math::tools::log_max_value()); - max_bernoulli_root_functor fun(t); - boost::math::tools::equal_floor tol; - boost::uintmax_t max_iter = boost::math::policies::get_max_root_iterations(); - return static_cast(boost::math::tools::toms748_solve(fun, sqrt(double(t)), double(t), tol, max_iter).first) / 2; -} - -template -inline std::size_t find_bernoulli_overflow_limit(const mpl::true_&) -{ - return max_bernoulli_index::value>::value; -} - -template -std::size_t b2n_overflow_limit() -{ - // This routine is called at program startup if it's called at all: - // that guarantees safe initialization of the static variable. - typedef mpl::bool_<(bernoulli_imp_variant::value >= 1) && (bernoulli_imp_variant::value <= 3)> tag_type; - static const std::size_t lim = find_bernoulli_overflow_limit(tag_type()); - return lim; -} - -// -// The tangent numbers grow larger much more rapidly than the Bernoulli numbers do.... -// so to compute the Bernoulli numbers from the tangent numbers, we need to avoid spurious -// overflow in the calculation, we can do this by scaling all the tangent number by some scale factor: -// -template -inline typename enable_if_c::is_specialized && (std::numeric_limits::radix == 2), T>::type tangent_scale_factor() -{ - BOOST_MATH_STD_USING - return ldexp(T(1), std::numeric_limits::min_exponent + 5); -} -template -inline typename disable_if_c::is_specialized && (std::numeric_limits::radix == 2), T>::type tangent_scale_factor() -{ - return tools::min_value() * 16; -} -// -// Initializer: ensure all our constants are initialized prior to the first call of main: -// -template -struct bernoulli_initializer -{ - struct init - { - init() - { - // - // We call twice, once to initialize our static table, and once to - // initialize our dymanic table: - // - boost::math::bernoulli_b2n(2, Policy()); -#ifndef BOOST_NO_EXCEPTIONS - try{ -#endif - boost::math::bernoulli_b2n(max_bernoulli_b2n::value + 1, Policy()); -#ifndef BOOST_NO_EXCEPTIONS - } catch(const std::overflow_error&){} -#endif - boost::math::tangent_t2n(2, Policy()); - } - void force_instantiate()const{} - }; - static const init initializer; - static void force_instantiate() - { - initializer.force_instantiate(); - } -}; - -template -const typename bernoulli_initializer::init bernoulli_initializer::initializer; - -// -// We need something to act as a cache for our calculated Bernoulli numbers. In order to -// ensure both fast access and thread safety, we need a stable table which may be extended -// in size, but which never reallocates: that way values already calculated may be accessed -// concurrently with another thread extending the table with new values. -// -// Very very simple vector class that will never allocate more than once, we could use -// boost::container::static_vector here, but that allocates on the stack, which may well -// cause issues for the amount of memory we want in the extreme case... -// -template -struct fixed_vector : private std::allocator -{ - typedef unsigned size_type; - typedef T* iterator; - typedef const T* const_iterator; - fixed_vector() : m_used(0) - { - std::size_t overflow_limit = 5 + b2n_overflow_limit >(); - m_capacity = static_cast((std::min)(overflow_limit, static_cast(100000u))); - m_data = this->allocate(m_capacity); - } - ~fixed_vector() - { - for(unsigned i = 0; i < m_used; ++i) - this->destroy(&m_data[i]); - this->deallocate(m_data, m_capacity); - } - T& operator[](unsigned n) { BOOST_ASSERT(n < m_used); return m_data[n]; } - const T& operator[](unsigned n)const { BOOST_ASSERT(n < m_used); return m_data[n]; } - unsigned size()const { return m_used; } - unsigned size() { return m_used; } - void resize(unsigned n, const T& val) - { - if(n > m_capacity) - { - BOOST_THROW_EXCEPTION(std::runtime_error("Exhausted storage for Bernoulli numbers.")); - } - for(unsigned i = m_used; i < n; ++i) - new (m_data + i) T(val); - m_used = n; - } - void resize(unsigned n) { resize(n, T()); } - T* begin() { return m_data; } - T* end() { return m_data + m_used; } - T* begin()const { return m_data; } - T* end()const { return m_data + m_used; } - unsigned capacity()const { return m_capacity; } -private: - T* m_data; - unsigned m_used, m_capacity; -}; - -template -class bernoulli_numbers_cache -{ -public: - bernoulli_numbers_cache() : m_overflow_limit((std::numeric_limits::max)()) -#if defined(BOOST_HAS_THREADS) && !defined(BOOST_MATH_NO_ATOMIC_INT) - , m_counter(0) -#endif - {} - - typedef fixed_vector container_type; - - void tangent(std::size_t m) - { - static const std::size_t min_overflow_index = b2n_overflow_limit() - 1; - tn.resize(static_cast(m), T(0U)); - - BOOST_MATH_INSTRUMENT_VARIABLE(min_overflow_index); - - std::size_t prev_size = m_intermediates.size(); - m_intermediates.resize(m, T(0U)); - - if(prev_size == 0) - { - m_intermediates[1] = tangent_scale_factor() /*T(1U)*/; - tn[0U] = T(0U); - tn[1U] = tangent_scale_factor()/* T(1U)*/; - BOOST_MATH_INSTRUMENT_VARIABLE(tn[0]); - BOOST_MATH_INSTRUMENT_VARIABLE(tn[1]); - } - - for(std::size_t i = std::max(2, prev_size); i < m; i++) - { - bool overflow_check = false; - if(i >= min_overflow_index && (boost::math::tools::max_value() / (i-1) < m_intermediates[1]) ) - { - std::fill(tn.begin() + i, tn.end(), boost::math::tools::max_value()); - break; - } - m_intermediates[1] = m_intermediates[1] * (i-1); - for(std::size_t j = 2; j <= i; j++) - { - overflow_check = - (i >= min_overflow_index) && ( - (boost::math::tools::max_value() / (i - j) < m_intermediates[j]) - || (boost::math::tools::max_value() / (i - j + 2) < m_intermediates[j-1]) - || (boost::math::tools::max_value() - m_intermediates[j] * (i - j) < m_intermediates[j-1] * (i - j + 2)) - || ((boost::math::isinf)(m_intermediates[j])) - ); - - if(overflow_check) - { - std::fill(tn.begin() + i, tn.end(), boost::math::tools::max_value()); - break; - } - m_intermediates[j] = m_intermediates[j] * (i - j) + m_intermediates[j-1] * (i - j + 2); - } - if(overflow_check) - break; // already filled the tn... - tn[static_cast(i)] = m_intermediates[i]; - BOOST_MATH_INSTRUMENT_VARIABLE(i); - BOOST_MATH_INSTRUMENT_VARIABLE(tn[static_cast(i)]); - } - } - - void tangent_numbers_series(const std::size_t m) - { - BOOST_MATH_STD_USING - static const std::size_t min_overflow_index = b2n_overflow_limit() - 1; - - typename container_type::size_type old_size = bn.size(); - - tangent(m); - bn.resize(static_cast(m)); - - if(!old_size) - { - bn[0] = 1; - old_size = 1; - } - - T power_two(ldexp(T(1), static_cast(2 * old_size))); - - for(std::size_t i = old_size; i < m; i++) - { - T b(static_cast(i * 2)); - // - // Not only do we need to take care to avoid spurious over/under flow in - // the calculation, but we also need to avoid overflow altogether in case - // we're calculating with a type where "bad things" happen in that case: - // - b = b / (power_two * tangent_scale_factor()); - b /= (power_two - 1); - bool overflow_check = (i >= min_overflow_index) && (tools::max_value() / tn[static_cast(i)] < b); - if(overflow_check) - { - m_overflow_limit = i; - while(i < m) - { - b = std::numeric_limits::has_infinity ? std::numeric_limits::infinity() : tools::max_value(); - bn[static_cast(i)] = ((i % 2U) ? b : T(-b)); - ++i; - } - break; - } - else - { - b *= tn[static_cast(i)]; - } - - power_two = ldexp(power_two, 2); - - const bool b_neg = i % 2 == 0; - - bn[static_cast(i)] = ((!b_neg) ? b : T(-b)); - } - } - - template - OutputIterator copy_bernoulli_numbers(OutputIterator out, std::size_t start, std::size_t n, const Policy& pol) - { - // - // There are basically 3 thread safety options: - // - // 1) There are no threads (BOOST_HAS_THREADS is not defined). - // 2) There are threads, but we do not have a true atomic integer type, - // in this case we just use a mutex to guard against race conditions. - // 3) There are threads, and we have an atomic integer: in this case we can - // use the double-checked locking pattern to avoid thread synchronisation - // when accessing values already in the cache. - // - // First off handle the common case for overflow and/or asymptotic expansion: - // - if(start + n > bn.capacity()) - { - if(start < bn.capacity()) - { - out = copy_bernoulli_numbers(out, start, bn.capacity() - start, pol); - n -= bn.capacity() - start; - start = static_cast(bn.capacity()); - } - if(start < b2n_overflow_limit() + 2u) - { - for(; n; ++start, --n) - { - *out = b2n_asymptotic(static_cast(start * 2U)); - ++out; - } - } - for(; n; ++start, --n) - { - *out = policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(start), pol); - ++out; - } - return out; - } - #if !defined(BOOST_HAS_THREADS) - // - // Single threaded code, very simple: - // - if(start + n >= bn.size()) - { - std::size_t new_size = (std::min)((std::max)((std::max)(std::size_t(start + n), std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity())); - tangent_numbers_series(new_size); - } - - for(std::size_t i = (std::max)(std::size_t(max_bernoulli_b2n::value + 1), start); i < start + n; ++i) - { - *out = (i >= m_overflow_limit) ? policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol) : bn[i]; - ++out; - } - #elif defined(BOOST_MATH_NO_ATOMIC_INT) - // - // We need to grab a mutex every time we get here, for both readers and writers: - // - boost::detail::lightweight_mutex::scoped_lock l(m_mutex); - if(start + n >= bn.size()) - { - std::size_t new_size = (std::min)((std::max)((std::max)(std::size_t(start + n), std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity())); - tangent_numbers_series(new_size); - } - - for(std::size_t i = (std::max)(std::size_t(max_bernoulli_b2n::value + 1), start); i < start + n; ++i) - { - *out = (i >= m_overflow_limit) ? policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol) : bn[i]; - ++out; - } - - #else - // - // Double-checked locking pattern, lets us access cached already cached values - // without locking: - // - // Get the counter and see if we need to calculate more constants: - // - if(static_cast(m_counter.load(BOOST_MATH_ATOMIC_NS::memory_order_consume)) < start + n) - { - boost::detail::lightweight_mutex::scoped_lock l(m_mutex); - - if(static_cast(m_counter.load(BOOST_MATH_ATOMIC_NS::memory_order_consume)) < start + n) - { - if(start + n >= bn.size()) - { - std::size_t new_size = (std::min)((std::max)((std::max)(std::size_t(start + n), std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity())); - tangent_numbers_series(new_size); - } - m_counter.store(static_cast(bn.size()), BOOST_MATH_ATOMIC_NS::memory_order_release); - } - } - - for(std::size_t i = (std::max)(static_cast(max_bernoulli_b2n::value + 1), start); i < start + n; ++i) - { - *out = (i >= m_overflow_limit) ? policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol) : bn[static_cast(i)]; - ++out; - } - - #endif - return out; - } - - template - OutputIterator copy_tangent_numbers(OutputIterator out, std::size_t start, std::size_t n, const Policy& pol) - { - // - // There are basically 3 thread safety options: - // - // 1) There are no threads (BOOST_HAS_THREADS is not defined). - // 2) There are threads, but we do not have a true atomic integer type, - // in this case we just use a mutex to guard against race conditions. - // 3) There are threads, and we have an atomic integer: in this case we can - // use the double-checked locking pattern to avoid thread synchronisation - // when accessing values already in the cache. - // - // - // First off handle the common case for overflow and/or asymptotic expansion: - // - if(start + n > bn.capacity()) - { - if(start < bn.capacity()) - { - out = copy_tangent_numbers(out, start, bn.capacity() - start, pol); - n -= bn.capacity() - start; - start = static_cast(bn.capacity()); - } - if(start < b2n_overflow_limit() + 2u) - { - for(; n; ++start, --n) - { - *out = t2n_asymptotic(static_cast(start)); - ++out; - } - } - for(; n; ++start, --n) - { - *out = policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(start), pol); - ++out; - } - return out; - } - #if !defined(BOOST_HAS_THREADS) - // - // Single threaded code, very simple: - // - if(start + n >= bn.size()) - { - std::size_t new_size = (std::min)((std::max)((std::max)(start + n, std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity())); - tangent_numbers_series(new_size); - } - - for(std::size_t i = start; i < start + n; ++i) - { - if(i >= m_overflow_limit) - *out = policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol); - else - { - if(tools::max_value() * tangent_scale_factor() < tn[static_cast(i)]) - *out = policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol); - else - *out = tn[static_cast(i)] / tangent_scale_factor(); - } - ++out; - } - #elif defined(BOOST_MATH_NO_ATOMIC_INT) - // - // We need to grab a mutex every time we get here, for both readers and writers: - // - boost::detail::lightweight_mutex::scoped_lock l(m_mutex); - if(start + n >= bn.size()) - { - std::size_t new_size = (std::min)((std::max)((std::max)(start + n, std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity())); - tangent_numbers_series(new_size); - } - - for(std::size_t i = start; i < start + n; ++i) - { - if(i >= m_overflow_limit) - *out = policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol); - else - { - if(tools::max_value() * tangent_scale_factor() < tn[static_cast(i)]) - *out = policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol); - else - *out = tn[static_cast(i)] / tangent_scale_factor(); - } - ++out; - } - - #else - // - // Double-checked locking pattern, lets us access cached already cached values - // without locking: - // - // Get the counter and see if we need to calculate more constants: - // - if(static_cast(m_counter.load(BOOST_MATH_ATOMIC_NS::memory_order_consume)) < start + n) - { - boost::detail::lightweight_mutex::scoped_lock l(m_mutex); - - if(static_cast(m_counter.load(BOOST_MATH_ATOMIC_NS::memory_order_consume)) < start + n) - { - if(start + n >= bn.size()) - { - std::size_t new_size = (std::min)((std::max)((std::max)(start + n, std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity())); - tangent_numbers_series(new_size); - } - m_counter.store(static_cast(bn.size()), BOOST_MATH_ATOMIC_NS::memory_order_release); - } - } - - for(std::size_t i = start; i < start + n; ++i) - { - if(i >= m_overflow_limit) - *out = policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol); - else - { - if(tools::max_value() * tangent_scale_factor() < tn[static_cast(i)]) - *out = policies::raise_overflow_error("boost::math::bernoulli_b2n<%1%>(std::size_t)", 0, T(i), pol); - else - *out = tn[static_cast(i)] / tangent_scale_factor(); - } - ++out; - } - - #endif - return out; - } - -private: - // - // The caches for Bernoulli and tangent numbers, once allocated, - // these must NEVER EVER reallocate as it breaks our thread - // safety guarentees: - // - fixed_vector bn, tn; - std::vector m_intermediates; - // The value at which we know overflow has already occurred for the Bn: - std::size_t m_overflow_limit; -#if !defined(BOOST_HAS_THREADS) -#elif defined(BOOST_MATH_NO_ATOMIC_INT) - boost::detail::lightweight_mutex m_mutex; -#else - boost::detail::lightweight_mutex m_mutex; - atomic_counter_type m_counter; -#endif -}; - -template -inline bernoulli_numbers_cache& get_bernoulli_numbers_cache() -{ - // - // Force this function to be called at program startup so all the static variables - // get initailzed then (thread safety). - // - bernoulli_initializer::force_instantiate(); - static bernoulli_numbers_cache data; - return data; -} - -}}} - -#endif // BOOST_MATH_BERNOULLI_DETAIL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/polygamma.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/polygamma.hpp deleted file mode 100644 index 201f81929..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/polygamma.hpp +++ /dev/null @@ -1,558 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////// -// Copyright 2013 Nikhar Agrawal -// Copyright 2013 Christopher Kormanyos -// Copyright 2014 John Maddock -// Copyright 2013 Paul Bristow -// Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_ - #define _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_ - - #include "../policy.hpp" - #include "../bernoulli.hpp" - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - // Forward declarations. - namespace boost { namespace math { - - // Forward declaration of boost::math::polygamma. - template - inline typename tools::promote_args::type polygamma(const int n, T x, const Policy& pol); - template - inline typename tools::promote_args::type polygamma(const int n, T x); - - namespace policies { - - template - inline int digits_base10(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) - { - return boost::math::policies::digits() * 301 / 1000L; - } - } - - }} - - namespace boost { namespace math { namespace detail{ - - template - T polygamma_atinfinityplus(const int n, const T& x, const Policy& pol, const char* function) // for large values of x such as for x> 400 - { - // See http://functions.wolfram.com/GammaBetaErf/PolyGamma2/06/02/0001/ - BOOST_MATH_STD_USING - // - // sum == current value of accumulated sum. - // term == value of current term to be added to sum. - // part_term == value of current term excluding the Bernoulli number part - // - if(n + x == x) - { - // x is crazy large, just concentrate on the first part of the expression and use logs: - if(n == 1) return 1 / x; - T nlx = n * log(x); - if((nlx < tools::log_max_value()) && (n < (int)max_factorial::value)) - return ((n & 1) ? 1 : -1) * boost::math::factorial(n - 1) * pow(x, -n); - else - return ((n & 1) ? 1 : -1) * exp(boost::math::lgamma(T(n), pol) - n * log(x)); - } - T term, sum, part_term; - T x_squared = x * x; - // - // Start by setting part_term to: - // - // (n-1)! / x^(n+1) - // - // which is common to both the first term of the series (with k = 1) - // and to the leading part. - // We can then get to the leading term by: - // - // part_term * (n + 2 * x) / 2 - // - // and to the first term in the series - // (excluding the Bernoulli number) by: - // - // part_term n * (n + 1) / (2x) - // - // If either the factorial would overflow, - // or the power term underflows, this just gets set to 0 and then we - // know that we have to use logs for the initial terms: - // - part_term = ((n > (int)boost::math::max_factorial::value) && (T(n) * n > tools::log_max_value())) - ? T(0) : static_cast(boost::math::factorial(n - 1, pol) * pow(x, -n - 1)); - if(part_term == 0) - { - // Either n is very large, or the power term underflows, - // set the initial values of part_term, term and sum via logs: - part_term = static_cast(boost::math::lgamma(n, pol) - (n + 1) * log(x)); - sum = exp(part_term + log(n + 2 * x) - boost::math::constants::ln_two()); - part_term += log(T(n) * (n + 1)) - boost::math::constants::ln_two() - log(x); - part_term = exp(part_term); - } - else - { - sum = part_term * (n + 2 * x) / 2; - part_term *= (T(n) * (n + 1)) / 2; - part_term /= x; - } - // - // If the leading term is 0, so is the result: - // - if(sum == 0) - return sum; - - for(unsigned k = 1;;) - { - term = part_term * boost::math::bernoulli_b2n(k, pol); - sum += term; - // - // Normal termination condition: - // - if(fabs(term / sum) < tools::epsilon()) - break; - // - // Increment our counter, and move part_term on to the next value: - // - ++k; - part_term *= T(n + 2 * k - 2) * (n - 1 + 2 * k); - part_term /= (2 * k - 1) * 2 * k; - part_term /= x_squared; - // - // Emergency get out termination condition: - // - if(k > policies::get_max_series_iterations()) - { - return policies::raise_evaluation_error(function, "Series did not converge, closest value was %1%", sum, pol); - } - } - - if((n - 1) & 1) - sum = -sum; - - return sum; - } - - template - T polygamma_attransitionplus(const int n, const T& x, const Policy& pol, const char* function) - { - // See: http://functions.wolfram.com/GammaBetaErf/PolyGamma2/16/01/01/0017/ - - // Use N = (0.4 * digits) + (4 * n) for target value for x: - BOOST_MATH_STD_USING - const int d4d = static_cast(0.4F * policies::digits_base10()); - const int N = d4d + (4 * n); - const int m = n; - const int iter = N - itrunc(x); - - if(iter > (int)policies::get_max_series_iterations()) - return policies::raise_evaluation_error(function, ("Exceeded maximum series evaluations evaluating at n = " + boost::lexical_cast(n) + " and x = %1%").c_str(), x, pol); - - const int minus_m_minus_one = -m - 1; - - T z(x); - T sum0(0); - T z_plus_k_pow_minus_m_minus_one(0); - - // Forward recursion to larger x, need to check for overflow first though: - if(log(z + iter) * minus_m_minus_one > -tools::log_max_value()) - { - for(int k = 1; k <= iter; ++k) - { - z_plus_k_pow_minus_m_minus_one = pow(z, minus_m_minus_one); - sum0 += z_plus_k_pow_minus_m_minus_one; - z += 1; - } - sum0 *= boost::math::factorial(n); - } - else - { - for(int k = 1; k <= iter; ++k) - { - T log_term = log(z) * minus_m_minus_one + boost::math::lgamma(T(n + 1), pol); - sum0 += exp(log_term); - z += 1; - } - } - if((n - 1) & 1) - sum0 = -sum0; - - return sum0 + polygamma_atinfinityplus(n, z, pol, function); - } - - template - T polygamma_nearzero(int n, T x, const Policy& pol, const char* function) - { - BOOST_MATH_STD_USING - // - // If we take this expansion for polygamma: http://functions.wolfram.com/06.15.06.0003.02 - // and substitute in this expression for polygamma(n, 1): http://functions.wolfram.com/06.15.03.0009.01 - // we get an alternating series for polygamma when x is small in terms of zeta functions of - // integer arguments (which are easy to evaluate, at least when the integer is even). - // - // In order to avoid spurious overflow, save the n! term for later, and rescale at the end: - // - T scale = boost::math::factorial(n, pol); - // - // "factorial_part" contains everything except the zeta function - // evaluations in each term: - // - T factorial_part = 1; - // - // "prefix" is what we'll be adding the accumulated sum to, it will - // be n! / z^(n+1), but since we're scaling by n! it's just - // 1 / z^(n+1) for now: - // - T prefix = pow(x, n + 1); - if(prefix == 0) - return boost::math::policies::raise_overflow_error(function, 0, pol); - prefix = 1 / prefix; - // - // First term in the series is necessarily < zeta(2) < 2, so - // ignore the sum if it will have no effect on the result anyway: - // - if(prefix > 2 / policies::get_epsilon()) - return ((n & 1) ? 1 : -1) * - (tools::max_value() / prefix < scale ? policies::raise_overflow_error(function, 0, pol) : prefix * scale); - // - // As this is an alternating series we could accelerate it using - // "Convergence Acceleration of Alternating Series", - // Henri Cohen, Fernando Rodriguez Villegas, and Don Zagier, Experimental Mathematics, 1999. - // In practice however, it appears not to make any difference to the number of terms - // required except in some edge cases which are filtered out anyway before we get here. - // - T sum = prefix; - for(unsigned k = 0;;) - { - // Get the k'th term: - T term = factorial_part * boost::math::zeta(T(k + n + 1), pol); - sum += term; - // Termination condition: - if(fabs(term) < fabs(sum * boost::math::policies::get_epsilon())) - break; - // - // Move on k and factorial_part: - // - ++k; - factorial_part *= (-x * (n + k)) / k; - // - // Last chance exit: - // - if(k > policies::get_max_series_iterations()) - return policies::raise_evaluation_error(function, "Series did not converge, best value is %1%", sum, pol); - } - // - // We need to multiply by the scale, at each stage checking for oveflow: - // - if(boost::math::tools::max_value() / scale < sum) - return boost::math::policies::raise_overflow_error(function, 0, pol); - sum *= scale; - return n & 1 ? sum : T(-sum); - } - - // - // Helper function which figures out which slot our coefficient is in - // given an angle multiplier for the cosine term of power: - // - template - typename Table::value_type::reference dereference_table(Table& table, unsigned row, unsigned power) - { - return table[row][power / 2]; - } - - - - template - T poly_cot_pi(int n, T x, T xc, const Policy& pol, const char* function) - { - BOOST_MATH_STD_USING - // Return n'th derivative of cot(pi*x) at x, these are simply - // tabulated for up to n = 9, beyond that it is possible to - // calculate coefficients as follows: - // - // The general form of each derivative is: - // - // pi^n * SUM{k=0, n} C[k,n] * cos^k(pi * x) * csc^(n+1)(pi * x) - // - // With constant C[0,1] = -1 and all other C[k,n] = 0; - // Then for each k < n+1: - // C[k-1, n+1] -= k * C[k, n]; - // C[k+1, n+1] += (k-n-1) * C[k, n]; - // - // Note that there are many different ways of representing this derivative thanks to - // the many trigomonetric identies available. In particular, the sum of powers of - // cosines could be replaced by a sum of cosine multiple angles, and indeed if you - // plug the derivative into Mathematica this is the form it will give. The two - // forms are related via the Chebeshev polynomials of the first kind and - // T_n(cos(x)) = cos(n x). The polynomial form has the great advantage that - // all the cosine terms are zero at half integer arguments - right where this - // function has it's minumum - thus avoiding cancellation error in this region. - // - // And finally, since every other term in the polynomials is zero, we can save - // space by only storing the non-zero terms. This greatly complexifies - // subscripting the tables in the calculation, but halves the storage space - // (and complexity for that matter). - // - T s = fabs(x) < fabs(xc) ? boost::math::sin_pi(x, pol) : boost::math::sin_pi(xc, pol); - T c = boost::math::cos_pi(x, pol); - switch(n) - { - case 1: - return -constants::pi() / (s * s); - case 2: - { - return 2 * constants::pi() * constants::pi() * c / boost::math::pow<3>(s, pol); - } - case 3: - { - int P[] = { -2, -4 }; - return boost::math::pow<3>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<4>(s, pol); - } - case 4: - { - int P[] = { 16, 8 }; - return boost::math::pow<4>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<5>(s, pol); - } - case 5: - { - int P[] = { -16, -88, -16 }; - return boost::math::pow<5>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<6>(s, pol); - } - case 6: - { - int P[] = { 272, 416, 32 }; - return boost::math::pow<6>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<7>(s, pol); - } - case 7: - { - int P[] = { -272, -2880, -1824, -64 }; - return boost::math::pow<7>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<8>(s, pol); - } - case 8: - { - int P[] = { 7936, 24576, 7680, 128 }; - return boost::math::pow<8>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<9>(s, pol); - } - case 9: - { - int P[] = { -7936, -137216, -185856, -31616, -256 }; - return boost::math::pow<9>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<10>(s, pol); - } - case 10: - { - int P[] = { 353792, 1841152, 1304832, 128512, 512 }; - return boost::math::pow<10>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<11>(s, pol); - } - case 11: - { - int P[] = { -353792, -9061376, -21253376, -8728576, -518656, -1024}; - return boost::math::pow<11>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<12>(s, pol); - } - case 12: - { - int P[] = { 22368256, 175627264, 222398464, 56520704, 2084864, 2048 }; - return boost::math::pow<12>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<13>(s, pol); - } -#ifndef BOOST_NO_LONG_LONG - case 13: - { - long long P[] = { -22368256LL, -795300864LL, -2868264960LL, -2174832640LL, -357888000LL, -8361984LL, -4096 }; - return boost::math::pow<13>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<14>(s, pol); - } - case 14: - { - long long P[] = { 1903757312LL, 21016670208LL, 41731645440LL, 20261765120LL, 2230947840LL, 33497088LL, 8192 }; - return boost::math::pow<14>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<15>(s, pol); - } - case 15: - { - long long P[] = { -1903757312LL, -89702612992LL, -460858269696LL, -559148810240LL, -182172651520LL, -13754155008LL, -134094848LL, -16384 }; - return boost::math::pow<15>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<16>(s, pol); - } - case 16: - { - long long P[] = { 209865342976LL, 3099269660672LL, 8885192097792LL, 7048869314560LL, 1594922762240LL, 84134068224LL, 536608768LL, 32768 }; - return boost::math::pow<16>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<17>(s, pol); - } - case 17: - { - long long P[] = { -209865342976LL, -12655654469632LL, -87815735738368LL, -155964390375424LL, -84842998005760LL, -13684856848384LL, -511780323328LL, -2146926592LL, -65536 }; - return boost::math::pow<17>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<18>(s, pol); - } - case 18: - { - long long P[] = { 29088885112832LL, 553753414467584LL, 2165206642589696LL, 2550316668551168LL, 985278548541440LL, 115620218667008LL, 3100738912256LL, 8588754944LL, 131072 }; - return boost::math::pow<18>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<19>(s, pol); - } - case 19: - { - long long P[] = { -29088885112832LL, -2184860175433728LL, -19686087844429824LL, -48165109676113920LL, -39471306959486976LL, -11124607890751488LL, -965271355195392LL, -18733264797696LL, -34357248000LL, -262144 }; - return boost::math::pow<19>(constants::pi(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<20>(s, pol); - } - case 20: - { - long long P[] = { 4951498053124096LL, 118071834535526400LL, 603968063567560704LL, 990081991141490688LL, 584901762421358592LL, 122829335169859584LL, 7984436548730880LL, 112949304754176LL, 137433710592LL, 524288 }; - return boost::math::pow<20>(constants::pi(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<21>(s, pol); - } -#endif - } - - // - // We'll have to compute the coefficients up to n, - // complexity is O(n^2) which we don't worry about for now - // as the values are computed once and then cached. - // However, if the final evaluation would have too many - // terms just bail out right away: - // - if((unsigned)n / 2u > policies::get_max_series_iterations()) - return policies::raise_evaluation_error(function, "The value of n is so large that we're unable to compute the result in reasonable time, best guess is %1%", 0, pol); -#ifdef BOOST_HAS_THREADS - static boost::detail::lightweight_mutex m; - boost::detail::lightweight_mutex::scoped_lock l(m); -#endif - static std::vector > table(1, std::vector(1, T(-1))); - - int index = n - 1; - - if(index >= (int)table.size()) - { - for(int i = (int)table.size() - 1; i < index; ++i) - { - int offset = i & 1; // 1 if the first cos power is 0, otherwise 0. - int sin_order = i + 2; // order of the sin term - int max_cos_order = sin_order - 1; // largest order of the polynomial of cos terms - int max_columns = (max_cos_order - offset) / 2; // How many entries there are in the current row. - int next_offset = offset ? 0 : 1; - int next_max_columns = (max_cos_order + 1 - next_offset) / 2; // How many entries there will be in the next row - table.push_back(std::vector(next_max_columns + 1, T(0))); - - for(int column = 0; column <= max_columns; ++column) - { - int cos_order = 2 * column + offset; // order of the cosine term in entry "column" - BOOST_ASSERT(column < (int)table[i].size()); - BOOST_ASSERT((cos_order + 1) / 2 < (int)table[i + 1].size()); - table[i + 1][(cos_order + 1) / 2] += ((cos_order - sin_order) * table[i][column]) / (sin_order - 1); - if(cos_order) - table[i + 1][(cos_order - 1) / 2] += (-cos_order * table[i][column]) / (sin_order - 1); - } - } - - } - T sum = boost::math::tools::evaluate_even_polynomial(&table[index][0], c, table[index].size()); - if(index & 1) - sum *= c; // First coeffient is order 1, and really an odd polynomial. - if(sum == 0) - return sum; - // - // The remaining terms are computed using logs since the powers and factorials - // get real large real quick: - // - T power_terms = n * log(boost::math::constants::pi()); - if(s == 0) - return sum * boost::math::policies::raise_overflow_error(function, 0, pol); - power_terms -= log(fabs(s)) * (n + 1); - power_terms += boost::math::lgamma(T(n)); - power_terms += log(fabs(sum)); - - if(power_terms > boost::math::tools::log_max_value()) - return sum * boost::math::policies::raise_overflow_error(function, 0, pol); - - return exp(power_terms) * ((s < 0) && ((n + 1) & 1) ? -1 : 1) * boost::math::sign(sum); - } - - template - struct polygamma_initializer - { - struct init - { - init() - { - // Forces initialization of our table of coefficients and mutex: - boost::math::polygamma(30, T(-2.5f), Policy()); - } - void force_instantiate()const{} - }; - static const init initializer; - static void force_instantiate() - { - initializer.force_instantiate(); - } - }; - - template - const typename polygamma_initializer::init polygamma_initializer::initializer; - - template - inline T polygamma_imp(const int n, T x, const Policy &pol) - { - BOOST_MATH_STD_USING - static const char* function = "boost::math::polygamma<%1%>(int, %1%)"; - polygamma_initializer::initializer.force_instantiate(); - if(n < 0) - return policies::raise_domain_error(function, "Order must be >= 0, but got %1%", static_cast(n), pol); - if(x < 0) - { - if(floor(x) == x) - { - // - // Result is infinity if x is odd, and a pole error if x is even. - // - if(lltrunc(x) & 1) - return policies::raise_overflow_error(function, 0, pol); - else - return policies::raise_pole_error(function, "Evaluation at negative integer %1%", x, pol); - } - T z = 1 - x; - T result = polygamma_imp(n, z, pol) + constants::pi() * poly_cot_pi(n, z, x, pol, function); - return n & 1 ? T(-result) : result; - } - // - // Limit for use of small-x-series is chosen - // so that the series doesn't go too divergent - // in the first few terms. Ordinarily this - // would mean setting the limit to ~ 1 / n, - // but we can tolerate a small amount of divergence: - // - T small_x_limit = (std::min)(T(T(5) / n), T(0.25f)); - if(x < small_x_limit) - { - return polygamma_nearzero(n, x, pol, function); - } - else if(x > 0.4F * policies::digits_base10() + 4.0f * n) - { - return polygamma_atinfinityplus(n, x, pol, function); - } - else if(x == 1) - { - return (n & 1 ? 1 : -1) * boost::math::factorial(n, pol) * boost::math::zeta(T(n + 1), pol); - } - else if(x == 0.5f) - { - T result = (n & 1 ? 1 : -1) * boost::math::factorial(n, pol) * boost::math::zeta(T(n + 1), pol); - if(fabs(result) >= ldexp(tools::max_value(), -n - 1)) - return boost::math::sign(result) * policies::raise_overflow_error(function, 0, pol); - result *= ldexp(T(1), n + 1) - 1; - return result; - } - else - { - return polygamma_attransitionplus(n, x, pol, function); - } - } - -} } } // namespace boost::math::detail - -#endif // _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_ - diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/unchecked_bernoulli.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/unchecked_bernoulli.hpp deleted file mode 100644 index c61c08999..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/detail/unchecked_bernoulli.hpp +++ /dev/null @@ -1,700 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////// -// Copyright 2013 Nikhar Agrawal -// Copyright 2013 Christopher Kormanyos -// Copyright 2013 John Maddock -// Copyright 2013 Paul Bristow -// Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#ifndef BOOST_MATH_UNCHECKED_BERNOULLI_HPP_ -#define BOOST_MATH_UNCHECKED_BERNOULLI_HPP_ - -#include "../math_fwd.hpp" -#include -#include -#include -#include -#include -#include - -namespace boost { namespace math { - -namespace detail { - -template -struct max_bernoulli_index -{ - BOOST_STATIC_CONSTANT(unsigned, value = 17); -}; - -template <> -struct max_bernoulli_index<1> -{ - BOOST_STATIC_CONSTANT(unsigned, value = 32); -}; - -template <> -struct max_bernoulli_index<2> -{ - BOOST_STATIC_CONSTANT(unsigned, value = 129); -}; - -template <> -struct max_bernoulli_index<3> -{ - BOOST_STATIC_CONSTANT(unsigned, value = 1156); -}; - -template <> -struct max_bernoulli_index<4> -{ - BOOST_STATIC_CONSTANT(unsigned, value = 11); -}; - -template -struct bernoulli_imp_variant -{ - static const unsigned value = - (std::numeric_limits::max_exponent == 128) - && (std::numeric_limits::radix == 2) - && (std::numeric_limits::digits <= std::numeric_limits::digits) - && (boost::is_convertible::value) ? 1 : - ( - (std::numeric_limits::max_exponent == 1024) - && (std::numeric_limits::radix == 2) - && (std::numeric_limits::digits <= std::numeric_limits::digits) - && (boost::is_convertible::value) ? 2 : - ( - (std::numeric_limits::max_exponent == 16384) - && (std::numeric_limits::radix == 2) - && (std::numeric_limits::digits <= std::numeric_limits::digits) - && (boost::is_convertible::value) ? 3 : (!is_convertible::value ? 4 : 0) - ) - ); -}; - -} // namespace detail - -template -struct max_bernoulli_b2n : public detail::max_bernoulli_index::value>{}; - -namespace detail{ - -template -inline T unchecked_bernoulli_imp(std::size_t n, const mpl::int_<0>& ) -{ - static const boost::array::value> numerators = - {{ - boost::int64_t( +1LL), - boost::int64_t( +1LL), - boost::int64_t( -1LL), - boost::int64_t( +1LL), - boost::int64_t( -1LL), - boost::int64_t( +5LL), - boost::int64_t( -691LL), - boost::int64_t( +7LL), - boost::int64_t( -3617LL), - boost::int64_t( +43867LL), - boost::int64_t( -174611LL), - boost::int64_t( +854513LL), - boost::int64_t( -236364091LL), - boost::int64_t( +8553103LL), - boost::int64_t( -23749461029LL), - boost::int64_t(+8615841276005LL), - boost::int64_t(-7709321041217LL), - boost::int64_t(+2577687858367LL) - }}; - - static const boost::array::value> denominators = - {{ - boost::int64_t( 1LL), - boost::int64_t( 6LL), - boost::int64_t( 30LL), - boost::int64_t( 42LL), - boost::int64_t( 30LL), - boost::int64_t( 66LL), - boost::int64_t( 2730LL), - boost::int64_t( 6LL), - boost::int64_t( 510LL), - boost::int64_t( 798LL), - boost::int64_t( 330LL), - boost::int64_t( 138LL), - boost::int64_t( 2730LL), - boost::int64_t( 6LL), - boost::int64_t( 870LL), - boost::int64_t( 14322LL), - boost::int64_t( 510LL), - boost::int64_t( 6LL) - }}; - return T(numerators[n]) / denominators[n]; -} - -template -inline T unchecked_bernoulli_imp(std::size_t n, const mpl::int_<1>& ) -{ - static const boost::array::value> bernoulli_data = - {{ - +1.00000000000000000000000000000000000000000F, - +0.166666666666666666666666666666666666666667F, - -0.0333333333333333333333333333333333333333333F, - +0.0238095238095238095238095238095238095238095F, - -0.0333333333333333333333333333333333333333333F, - +0.0757575757575757575757575757575757575757576F, - -0.253113553113553113553113553113553113553114F, - +1.16666666666666666666666666666666666666667F, - -7.09215686274509803921568627450980392156863F, - +54.9711779448621553884711779448621553884712F, - -529.124242424242424242424242424242424242424F, - +6192.12318840579710144927536231884057971014F, - -86580.2531135531135531135531135531135531136F, - +1.42551716666666666666666666666666666666667e6F, - -2.72982310678160919540229885057471264367816e7F, - +6.01580873900642368384303868174835916771401e8F, - -1.51163157670921568627450980392156862745098e10F, - +4.29614643061166666666666666666666666666667e11F, - -1.37116552050883327721590879485616327721591e13F, - +4.88332318973593166666666666666666666666667e14F, - -1.92965793419400681486326681448632668144863e16F, - +8.41693047573682615000553709856035437430786e17F, - -4.03380718540594554130768115942028985507246e19F, - +2.11507486380819916056014539007092198581560e21F, - -1.20866265222965259346027311937082525317819e23F, - +7.50086674607696436685572007575757575757576e24F, - -5.03877810148106891413789303052201257861635e26F, - +3.65287764848181233351104308429711779448622e28F, - -2.84987693024508822262691464329106781609195e30F, - +2.38654274996836276446459819192192149717514e32F, - -2.13999492572253336658107447651910973926742e34F, - +2.05009757234780975699217330956723102516667e36F, - -2.09380059113463784090951852900279701847092e38F, - }}; - - return bernoulli_data[n]; -} - - -template -inline T unchecked_bernoulli_imp(std::size_t n, const mpl::int_<2>& ) -{ - static const boost::array::value> bernoulli_data = - {{ - +1.00000000000000000000000000000000000000000, - +0.166666666666666666666666666666666666666667, - -0.0333333333333333333333333333333333333333333, - +0.0238095238095238095238095238095238095238095, - -0.0333333333333333333333333333333333333333333, - +0.0757575757575757575757575757575757575757576, - -0.253113553113553113553113553113553113553114, - +1.16666666666666666666666666666666666666667, - -7.09215686274509803921568627450980392156863, - +54.9711779448621553884711779448621553884712, - -529.124242424242424242424242424242424242424, - +6192.12318840579710144927536231884057971014, - -86580.2531135531135531135531135531135531136, - +1.42551716666666666666666666666666666666667e6, - -2.72982310678160919540229885057471264367816e7, - +6.01580873900642368384303868174835916771401e8, - -1.51163157670921568627450980392156862745098e10, - +4.29614643061166666666666666666666666666667e11, - -1.37116552050883327721590879485616327721591e13, - +4.88332318973593166666666666666666666666667e14, - -1.92965793419400681486326681448632668144863e16, - +8.41693047573682615000553709856035437430786e17, - -4.03380718540594554130768115942028985507246e19, - +2.11507486380819916056014539007092198581560e21, - -1.20866265222965259346027311937082525317819e23, - +7.50086674607696436685572007575757575757576e24, - -5.03877810148106891413789303052201257861635e26, - +3.65287764848181233351104308429711779448622e28, - -2.84987693024508822262691464329106781609195e30, - +2.38654274996836276446459819192192149717514e32, - -2.13999492572253336658107447651910973926742e34, - +2.05009757234780975699217330956723102516667e36, - -2.09380059113463784090951852900279701847092e38, - +2.27526964884635155596492603527692645814700e40, - -2.62577102862395760473030497361582020814490e42, - +3.21250821027180325182047923042649852435219e44, - -4.15982781667947109139170744952623589366896e46, - +5.69206954820352800238834562191210586444805e48, - -8.21836294197845756922906534686173330145509e50, - +1.25029043271669930167323398297028955241772e53, - -2.00155832332483702749253291988132987687242e55, - +3.36749829153643742333966769033387530162196e57, - -5.94709705031354477186604968440515408405791e59, - +1.10119103236279775595641307904376916046305e62, - -2.13552595452535011886583850190410656789733e64, - +4.33288969866411924196166130593792062184514e66, - -9.18855282416693282262005552155018971389604e68, - +2.03468967763290744934550279902200200659751e71, - -4.70038339580357310785752555350060606545967e73, - +1.13180434454842492706751862577339342678904e76, - -2.83822495706937069592641563364817647382847e78, - +7.40642489796788506297508271409209841768797e80, - -2.00964548027566044834656196727153631868673e83, - +5.66571700508059414457193460305193569614195e85, - -1.65845111541362169158237133743199123014950e88, - +5.03688599504923774192894219151801548124424e90, - -1.58614682376581863693634015729664387827410e93, - +5.17567436175456269840732406825071225612408e95, - -1.74889218402171173396900258776181591451415e98, - +6.11605199949521852558245252642641677807677e100, - -2.21227769127078349422883234567129324455732e103, - +8.27227767987709698542210624599845957312047e105, - -3.19589251114157095835916343691808148735263e108, - +1.27500822233877929823100243029266798669572e111, - -5.25009230867741338994028246245651754469199e113, - +2.23018178942416252098692981988387281437383e116, - -9.76845219309552044386335133989802393011669e118, - +4.40983619784529542722726228748131691918758e121, - -2.05085708864640888397293377275830154864566e124, - +9.82144332797912771075729696020975210414919e126, - -4.84126007982088805087891967099634127611305e129, - +2.45530888014809826097834674040886903996737e132, - -1.28069268040847475487825132786017857218118e135, - +6.86761671046685811921018885984644004360924e137, - -3.78464685819691046949789954163795568144895e140, - +2.14261012506652915508713231351482720966602e143, - -1.24567271371836950070196429616376072194583e146, - +7.43457875510001525436796683940520613117807e148, - -4.55357953046417048940633332233212748767721e151, - +2.86121128168588683453638472510172325229190e154, - -1.84377235520338697276882026536287854875414e157, - +1.21811545362210466995013165065995213558174e160, - -8.24821871853141215484818457296893447301419e162, - +5.72258779378329433296516498142978615918685e165, - -4.06685305250591047267679693831158655602196e168, - +2.95960920646420500628752695815851870426379e171, - -2.20495225651894575090311752273445984836379e174, - +1.68125970728895998058311525151360665754464e177, - -1.31167362135569576486452806355817153004431e180, - +1.04678940094780380821832853929823089643829e183, - -8.54328935788337077185982546299082774593270e185, - +7.12878213224865423522884066771438224721245e188, - -6.08029314555358993000847118686477458461988e191, - +5.29967764248499239300942910043247266228490e194, - -4.71942591687458626443646229013379911103761e197, - +4.29284137914029810894168296541074669045521e200, - -3.98767449682322074434477655542938795106651e203, - +3.78197804193588827138944181161393327898220e206, - -3.66142336836811912436858082151197348755196e209, - +3.61760902723728623488554609298914089477541e212, - -3.64707726451913543621383088655499449048682e215, - +3.75087554364544090983452410104814189306842e218, - -3.93458672964390282694891288533713429355657e221, - +4.20882111481900820046571171111494898242731e224, - -4.59022962206179186559802940573325591059371e227, - +5.10317257726295759279198185106496768539760e230, - -5.78227623036569554015377271242917142512200e233, - +6.67624821678358810322637794412809363451080e236, - -7.85353076444504163225916259639312444428230e239, - +9.41068940670587255245443288258762485293948e242, - -1.14849338734651839938498599206805592548354e246, - +1.42729587428487856771416320087122499897180e249, - -1.80595595869093090142285728117654560926719e252, - +2.32615353076608052161297985184708876161736e255, - -3.04957517154995947681942819261542593785327e258, - +4.06858060764339734424012124124937318633684e261, - -5.52310313219743616252320044093186392324280e264, - +7.62772793964343924869949690204961215533859e267, - -1.07155711196978863132793524001065396932667e271, - +1.53102008959691884453440916153355334355847e274, - -2.22448916821798346676602348865048510824835e277, - +3.28626791906901391668189736436895275365183e280, - -4.93559289559603449020711938191575963496999e283, - +7.53495712008325067212266049779283956727824e286, - -1.16914851545841777278088924731655041783900e290, - +1.84352614678389394126646201597702232396492e293, - -2.95368261729680829728014917350525183485207e296, - +4.80793212775015697668878704043264072227967e299, - -7.95021250458852528538243631671158693036798e302, - +1.33527841873546338750122832017820518292039e306 - }}; - - return bernoulli_data[n]; -} - -template -inline T unchecked_bernoulli_imp(std::size_t n, const mpl::int_<3>& ) -{ - static const boost::array::value> bernoulli_data = - {{ - +1.00000000000000000000000000000000000000000L, - +0.166666666666666666666666666666666666666667L, - -0.0333333333333333333333333333333333333333333L, - +0.0238095238095238095238095238095238095238095L, - -0.0333333333333333333333333333333333333333333L, - +0.0757575757575757575757575757575757575757576L, - -0.253113553113553113553113553113553113553114L, - +1.16666666666666666666666666666666666666667L, - -7.09215686274509803921568627450980392156863L, - +54.9711779448621553884711779448621553884712L, - -529.124242424242424242424242424242424242424L, - +6192.12318840579710144927536231884057971014L, - -86580.2531135531135531135531135531135531136L, - +1.42551716666666666666666666666666666666667E6L, - -2.72982310678160919540229885057471264367816E7L, - +6.01580873900642368384303868174835916771401E8L, - -1.51163157670921568627450980392156862745098E10L, - +4.29614643061166666666666666666666666666667E11L, - -1.37116552050883327721590879485616327721591E13L, - +4.88332318973593166666666666666666666666667E14L, - -1.92965793419400681486326681448632668144863E16L, - +8.41693047573682615000553709856035437430786E17L, - -4.03380718540594554130768115942028985507246E19L, - +2.11507486380819916056014539007092198581560E21L, - -1.20866265222965259346027311937082525317819E23L, - +7.50086674607696436685572007575757575757576E24L, - -5.03877810148106891413789303052201257861635E26L, - +3.65287764848181233351104308429711779448622E28L, - -2.84987693024508822262691464329106781609195E30L, - +2.38654274996836276446459819192192149717514E32L, - -2.13999492572253336658107447651910973926742E34L, - +2.05009757234780975699217330956723102516667E36L, - -2.09380059113463784090951852900279701847092E38L, - +2.27526964884635155596492603527692645814700E40L, - -2.62577102862395760473030497361582020814490E42L, - +3.21250821027180325182047923042649852435219E44L, - -4.15982781667947109139170744952623589366896E46L, - +5.69206954820352800238834562191210586444805E48L, - -8.21836294197845756922906534686173330145509E50L, - +1.25029043271669930167323398297028955241772E53L, - -2.00155832332483702749253291988132987687242E55L, - +3.36749829153643742333966769033387530162196E57L, - -5.94709705031354477186604968440515408405791E59L, - +1.10119103236279775595641307904376916046305E62L, - -2.13552595452535011886583850190410656789733E64L, - +4.33288969866411924196166130593792062184514E66L, - -9.18855282416693282262005552155018971389604E68L, - +2.03468967763290744934550279902200200659751E71L, - -4.70038339580357310785752555350060606545967E73L, - +1.13180434454842492706751862577339342678904E76L, - -2.83822495706937069592641563364817647382847E78L, - +7.40642489796788506297508271409209841768797E80L, - -2.00964548027566044834656196727153631868673E83L, - +5.66571700508059414457193460305193569614195E85L, - -1.65845111541362169158237133743199123014950E88L, - +5.03688599504923774192894219151801548124424E90L, - -1.58614682376581863693634015729664387827410E93L, - +5.17567436175456269840732406825071225612408E95L, - -1.74889218402171173396900258776181591451415E98L, - +6.11605199949521852558245252642641677807677E100L, - -2.21227769127078349422883234567129324455732E103L, - +8.27227767987709698542210624599845957312047E105L, - -3.19589251114157095835916343691808148735263E108L, - +1.27500822233877929823100243029266798669572E111L, - -5.25009230867741338994028246245651754469199E113L, - +2.23018178942416252098692981988387281437383E116L, - -9.76845219309552044386335133989802393011669E118L, - +4.40983619784529542722726228748131691918758E121L, - -2.05085708864640888397293377275830154864566E124L, - +9.82144332797912771075729696020975210414919E126L, - -4.84126007982088805087891967099634127611305E129L, - +2.45530888014809826097834674040886903996737E132L, - -1.28069268040847475487825132786017857218118E135L, - +6.86761671046685811921018885984644004360924E137L, - -3.78464685819691046949789954163795568144895E140L, - +2.14261012506652915508713231351482720966602E143L, - -1.24567271371836950070196429616376072194583E146L, - +7.43457875510001525436796683940520613117807E148L, - -4.55357953046417048940633332233212748767721E151L, - +2.86121128168588683453638472510172325229190E154L, - -1.84377235520338697276882026536287854875414E157L, - +1.21811545362210466995013165065995213558174E160L, - -8.24821871853141215484818457296893447301419E162L, - +5.72258779378329433296516498142978615918685E165L, - -4.06685305250591047267679693831158655602196E168L, - +2.95960920646420500628752695815851870426379E171L, - -2.20495225651894575090311752273445984836379E174L, - +1.68125970728895998058311525151360665754464E177L, - -1.31167362135569576486452806355817153004431E180L, - +1.04678940094780380821832853929823089643829E183L, - -8.54328935788337077185982546299082774593270E185L, - +7.12878213224865423522884066771438224721245E188L, - -6.08029314555358993000847118686477458461988E191L, - +5.29967764248499239300942910043247266228490E194L, - -4.71942591687458626443646229013379911103761E197L, - +4.29284137914029810894168296541074669045521E200L, - -3.98767449682322074434477655542938795106651E203L, - +3.78197804193588827138944181161393327898220E206L, - -3.66142336836811912436858082151197348755196E209L, - +3.61760902723728623488554609298914089477541E212L, - -3.64707726451913543621383088655499449048682E215L, - +3.75087554364544090983452410104814189306842E218L, - -3.93458672964390282694891288533713429355657E221L, - +4.20882111481900820046571171111494898242731E224L, - -4.59022962206179186559802940573325591059371E227L, - +5.10317257726295759279198185106496768539760E230L, - -5.78227623036569554015377271242917142512200E233L, - +6.67624821678358810322637794412809363451080E236L, - -7.85353076444504163225916259639312444428230E239L, - +9.41068940670587255245443288258762485293948E242L, - -1.14849338734651839938498599206805592548354E246L, - +1.42729587428487856771416320087122499897180E249L, - -1.80595595869093090142285728117654560926719E252L, - +2.32615353076608052161297985184708876161736E255L, - -3.04957517154995947681942819261542593785327E258L, - +4.06858060764339734424012124124937318633684E261L, - -5.52310313219743616252320044093186392324280E264L, - +7.62772793964343924869949690204961215533859E267L, - -1.07155711196978863132793524001065396932667E271L, - +1.53102008959691884453440916153355334355847E274L, - -2.22448916821798346676602348865048510824835E277L, - +3.28626791906901391668189736436895275365183E280L, - -4.93559289559603449020711938191575963496999E283L, - +7.53495712008325067212266049779283956727824E286L, - -1.16914851545841777278088924731655041783900E290L, - +1.84352614678389394126646201597702232396492E293L, - -2.95368261729680829728014917350525183485207E296L, - +4.80793212775015697668878704043264072227967E299L, - -7.95021250458852528538243631671158693036798E302L, - +1.33527841873546338750122832017820518292039E306L, -#if LDBL_MAX_EXP == 16384 - // Entries 260 - 600 http://www.wolframalpha.com/input/?i=TABLE[N[Bernoulli[i]%2C40]%2C+{i%2C258%2C600%2C2}] - -2.277640649601959593875058983506938037019e309L, - 3.945184036046326234163525556422667595884e312L, - -6.938525772130602106071724989641405550473e315L, - 1.238896367577564823729057820219210929986e319L, - -2.245542599169309759499987966025604480745e322L, - 4.131213176073842359732511639489669404266e325L, - -7.713581346815269584960928069762882771369e328L, - 1.461536066837669600638613788471335541313e332L, - -2.809904606225532896862935642992712059631e335L, - 5.480957121318876639512096994413992284327e338L, - -1.084573284087686110518125291186079616320e342L, - 2.176980775647663539729165173863716459962e345L, - -4.431998786117553751947439433256752608068e348L, - 9.150625657715535047417756278073770096073e351L, - -1.915867353003157351316577579148683133613e355L, - 4.067256303542212258698836003682016040629e358L, - -8.754223791037736616228150209910348734629e361L, - 1.910173688735533667244373747124109379826e365L, - -4.225001320265091714631115064713174404607e368L, - 9.471959352547827678466770796787503034505e371L, - -2.152149973279986829719817376756088198573e375L, - 4.955485775334221051344839716507812871361e378L, - -1.156225941759134696630956889716381968142e382L, - 2.733406597646137698610991926705098514017e385L, - -6.546868135325176947099912523279938546333e388L, - 1.588524912441221472814692121069821695547e392L, - -3.904354800861715180218598151050191841308e395L, - 9.719938686092045781827273411668132975319e398L, - -2.450763621049522051234479737511375679283e402L, - 6.257892098396815305085674126334317095277e405L, - -1.618113552083806592527989531636955084420e409L, - 4.236528795217618357348618613216833722648e412L, - -1.123047068199051008086174989124136878992e416L, - 3.013971787525654770217283559392286666886e419L, - -8.188437573221553030375681429202969070420e422L, - 2.251910591336716809153958146725775718707e426L, - -6.268411292043789823075314151509139413399e429L, - 1.765990845202322642693572112511312471527e433L, - -5.035154436231331651259071296731160882240e436L, - 1.452779356460483245253765356664402207266e440L, - -4.241490890130137339052414960684151515166e443L, - 1.252966001692427774088293833338841893293e447L, - -3.744830047478272947978103227876747240343e450L, - 1.132315806695710930595876001089232216024e454L, - -3.463510845942701805991786197773934662578e457L, - 1.071643382649675572086865465873916611537e461L, - -3.353824475439933688957233489984711465335e464L, - 1.061594257145875875963152734129803268488e468L, - -3.398420969215528955528654193586189805265e471L, - 1.100192502000434096206138068020551065890e475L, - -3.601686379213993374332690210094863486472e478L, - 1.192235170430164900533187239994513019475e482L, - -3.990342751779668381699052942504119409180e485L, - 1.350281800938769780891258894167663309221e489L, - -4.619325443466054312873093650888507562249e492L, - 1.597522243968586548227514639959727696694e496L, - -5.584753729092155108530929002119620487652e499L, - 1.973443623104646193229794524759543752089e503L, - -7.048295441989615807045620880311201930244e506L, - 2.544236702499719094591873151590280263560e510L, - -9.281551595258615205927443367289948150345e513L, - 3.421757163154453657766296828520235351572e517L, - -1.274733639384538364282697627345068947433e521L, - 4.798524805311016034711205886780460173566e524L, - -1.825116948422858388787806917284878870034e528L, - 7.013667442807288452441777981425055613982e531L, - -2.723003862685989740898815670978399383114e535L, - 1.068014853917260290630122222858884658850e539L, - -4.231650952273697842269381683768681118533e542L, - 1.693650052202594386658903598564772900388e546L, - -6.846944855806453360616258582310883597678e549L, - 2.795809132238082267120232174243715559601e553L, - -1.153012972808983269106716828311318981951e557L, - 4.802368854268746357511997492039592697149e560L, - -2.019995255271910836389761734035403905781e564L, - 8.580207235032617856059250643095019760968e567L, - -3.680247942263468164408192134916355198549e571L, - 1.593924457586765331397457407661306895942e575L, - -6.970267175232643679233530367569943057501e578L, - 3.077528087427698518703282907890556154309e582L, - -1.371846760052887888926055417297342106614e586L, - 6.173627360829553396851763207025505289166e589L, - -2.804703130495506384463249394043486916669e593L, - 1.286250900087150126167490951216207186092e597L, - -5.954394420063617872366818601092036543220e600L, - 2.782297785278756426177542270854984091406e604L, - -1.312214674935307746141207680066262384215e608L, - 6.246299145383554153167974732783934504370e611L, - -3.000812007679574430883792565577444226490e615L, - 1.454904877136007844493861746476079537075e619L, - -7.118558521873800304612781121044077357278e622L, - 3.514739820897817389472822276832677887997e626L, - -1.751137068816377401163011262831890828437e630L, - 8.803498091818800678575314081978951179602e633L, - -4.465612911700593572269200981612564161010e637L, - 2.285494565287530681465757798517033542888e641L, - -1.180145168917737098025683613598595411329e645L, - 6.147941849198393232663105284575149616925e648L, - -3.231069156963603593233679426198974663352e652L, - 1.713042725635435041806895849197608270935e656L, - -9.161761363270648920537613435771882898051e659L, - 4.942675965960539112005679080810117766825e663L, - -2.689684712697383518131267222872386600031e667L, - 1.476320014229917759615308193449511534656e671L, - -8.173037740864781506597184122049453514594e674L, - 4.563462313190521363235182420178784459580e678L, - -2.569790015236158475703055501886439298708e682L, - 1.459410219452119981958355737832022375085e686L, - -8.358304882556983795372406183642486436653e689L, - 4.827305091483557818593092377664570208355e693L, - -2.811394311081493166793414157061950132403e697L, - 1.651026863340675349245561261339568827739e701L, - -9.776578579336866764167878646459810047899e704L, - 5.837207965197521880181236529616560780535e708L, - -3.513938957938032127105389702846371181520e712L, - 2.132747371360190507595748444536911078788e716L, - -1.305047363239192640729466563372665311602e720L, - 8.050825342678337497636292798039996484780e723L, - -5.006884161223862543665524155681082112689e727L, - 3.139016066011452177570812014513491361235e731L, - -1.983829535212711378291469356666001365873e735L, - 1.263822427649676371257598052486237628698e739L, - -8.115678659900522918802121684491754629503e742L, - 5.252995164972075271667364371449050412435e746L, - -3.427038125662404660056511738625477058135e750L, - 2.253446011834352733279946306835940729858e754L, - -1.493407341897034717876962786798831719683e758L, - 9.974681322653365118752729509398728354442e761L, - -6.714230142773850863927710112350816379426e765L, - 4.554668668931723346600337564274944733530e769L, - -3.113635386023220127834102980385275379533e773L, - 2.144945411287666204679363498162954050208e777L, - -1.488982121181387164932397544378555256016e781L, - 1.041537218854627455352298173588983048748e785L, - -7.341073881786613676177562822942175683993e788L, - 5.213524272587199574980117351016322518428e792L, - -3.730592531776514409283897139216167197989e796L, - 2.689592876341877079083449497724049500175e800L, - -1.953643788231947582529884602972233135002e804L, - 1.429691073080500563348668321308878246277e808L, - -1.054059177095488639836063073070536825675e812L, - 7.828919160938693948399336431565350676613e815L, - -5.857884457184396382550955498026762014753e819L, - 4.415401588264172474136969345712659422380e823L, - -3.352573884181287635796498822858109969161e827L, - 2.564210385719224000156548240934108974447e831L, - -1.975534392116037602837941409848663077528e835L, - 1.533062123975940045180943006948008486466e839L, - -1.198306160488763291730059994812781226903e843L, - 9.434034267770711698676321369174735725321e846L, - -7.480619200038505368468483892246806488879e850L, - 5.974161898439971564124576801455052907638e854L, - -4.805125663714699771668630995361572639386e858L, - 3.892332138028039952403812726744593073776e862L, - -3.175276505779699340738548328810180869575e866L, - 2.608608681939322393581069188271626122519e870L, - -2.158148554392732439392868052394994052628e874L, - 1.797993483301448477700600221980862686033e878L, - -1.508407575089108597171576068862286462909e882L, - 1.274273406242459482708930389008701147244e886L, - -1.083950475353171986748233157909397370193e890L, - 9.284292630726328432038470356821265395331e893L, - -8.007012115449516364480417355063446317414e897L, - 6.952871948429568933888979915833266241471e901L, - -6.078828929473797621198666799700739891205e905L, - 5.350908089710964244671334224708057812633e909L, - -4.742168072503284973969982758434401589090e913L, - 4.231149239401967697257534662010605751136e917L, - -3.800684612827828851942743291026898158947e921L, - 3.436984796314246158361599955909956583986e925L, - -3.128930718993658356398482705317381808301e929L, - // - // 602-1300: http://www.wolframalpha.com/input/?i=TABLE[N[Bernoulli[i]%2C40]%2C+{i%2C602%2C1300%2C2}] - 2.867524740577223817164663595437919813239e933L, -2.645462974939090580963101220449509725942e937L, 2.456800827789169780295419018499543141869e941L, -2.296690549725790064673528302231294870532e945L, 2.161174697699793265715182091764676666457e949L, -2.047023224586087259305754002882269123194e953L, 1.951604806042481282712736234132803700277e957L, -1.872785206668284042110390583158639495143e961L, 1.808847160923282257302788929692654262867e965L, -1.758427529634609613399327744595257497188e969L, 1.720468488019528147087036246754294757647e973L, -1.694180279355332648057740852839804839425e977L, 1.679013685251183870616469618951463869496e981L, -1.674640861433092946269144173974414945664e985L, 1.680943600147858322148767806987527412112e989L, -1.698008433134805056489370119323402510305e993L, 1.726128304411348354183882648263448448633e997L, -1.765810838736918108045764015629875016219e1001L, 1.817793526882665071123822455897912718293e1005L, -1.883066459765807128944897377914669600374e1009L, 1.962903588035940537938222992228124233567e1013L, -2.058903881920696086033171142046100185783e1017L, 2.173044241735786946064676598703393618281e1021L, -2.307746591425236218893160658331303115253e1025L, 2.465962312241418731528973526597433097256e1029L, -2.651278087802503406316742676403301581549e1033L, 2.868048395658440423778896607880692085708e1037L, -3.121561373094393453726645989392054731637e1041L, 3.418246710091027042099932753084126095820e1045L, -3.765936717592482928796920675282930034018e1049L, 4.174194967165213973474293718362757753877e1053L, -4.654731142471753017867105249805137855862e1057L, 5.221926310090434518253178454907900079787e1061L, -5.893500145664015254409680930288710794031e1065L, 6.691361332576333738130720616841706994101e1069L, -7.642695184575063524608775697714741180954e1073L, 8.781359617440634128952082759434723165820e1077L, -1.014968338800868135594698909567734048618e1082L, 1.180079105471061498849752479044520598414e1086L, -1.380162016721660241308046692646452732446e1090L, 1.623685158291375662775444238282343536948e1094L, -1.921404880943289359290531906131400049399e1098L, 2.287040419533950152851434188305457266969e1102L, -2.738162880206032093123060939173765335255e1106L, 3.297371307848643161532227459901386725801e1110L, -3.993854689967542662299211323085023297602e1114L, 4.865474805885735467044047308902313673643e1118L, -5.961554732739027308247618738765152679497e1122L, 7.346627151757492821447573639763873833441e1126L, -9.105493288459908620636712748727395637965e1130L, 1.135007867626164861991621396462821975167e1135L, -1.422876214067403769204874786137232627418e1139L, 1.793912271573925309173135913914667878908e1143L, -2.274542916104231188526120123855259514144e1147L, 2.900273688809987694128857655036783261991e1151L, -3.719022795563122339874875448447744493398e1155L, 4.795753420982845153626611023078973364321e1159L, -6.218937220186281310109009529226561379773e1163L, 8.109611247999584815668395828940708619394e1167L, -1.063412316303440216539797215354141158589e1172L, 1.402214363674117662460496032135704328989e1176L, -1.859223235464558752766840772026058694872e1180L, 2.478828203789903637835992128856742276028e1184L, -3.323169416193176673655321536761413885767e1188L, 4.479640207312477092938541546776915956580e1192L, -6.071721672924085739424644485636889518799e1196L, 8.274698015123579607850404326757887762270e1200L, -1.133855131459773018024052539697784205966e1205L, 1.562146222050424344025824344480153248984e1209L, -2.163904570724750459592352173471446831752e1213L, 3.013703210722669908901286635073603018696e1217L, -4.219903244242308803914269531001720703294e1221L, 5.940703220571043642186808904696174833998e1225L, -8.408147464216029127243257448169774333631e1229L, 1.196419999747411909144144315499654470715e1234L, -1.711518922741148710381740436694440587059e1238L, 2.461434539630850545757453894977350505251e1242L, -3.558748530932574002484841810677232366801e1246L, 5.172525606281917297657859608800373729529e1250L, -7.557850217376323621984784308774476917753e1254L, 1.110141075986004209769735296234549704181e1259L, -1.639216556732622481406083885926912451281e1263L, 2.433138328152562628385514545400044125983e1267L, -3.630476645219033020888837165221286413171e1271L, 5.445289518636306992942604775585977779418e1275L, -8.209806424989072060381590985042272020067e1279L, 1.244209849774134691374848390346442737613e1284L, -1.895384488692308848372754844910263931874e1288L, 2.902272596647764894203369746806169285113e1292L, -4.466944174025026625137032739317650862593e1296L, 6.910485739507636504313238347702354354916e1300L, -1.074550085668784170644854815272144687769e1305L, 1.679419258904938802199084915274175753529e1309L, -2.638155207645646220849795321076977230763e1313L, 4.165284786632654168563096850610185378233e1317L, -6.609774274649031371770290191295685774584e1321L, 1.054194100570841329575393359295845860860e1326L, -1.689822316104196916970708778265725885275e1330L, 2.722340957904912685605914893019783431164e1334L, -4.407776313964403233676810178851005163725e1338L, 7.172436210641903635864868181569129834361e1342L, -1.172947440100495955246356688225986736990e1347L, 1.927745674072824377954824961348211728006e1351L, -3.184013467435655962214317208087993711563e1355L, 5.285045125125832341263897233405196808096e1359L, -8.815883582819232027207118521581424783107e1363L, 1.477818368424505276711779171224799759099e1368L, -2.489482576496570159333357550363134602876e1372L, 4.214292881345076419678976329218843808204e1376L, -7.169068531615459070909644981451297906220e1380L, 1.225513133750594558180516896275774441895e1385L, -2.105160827387119480607950260289853896637e1389L, 3.633787605672960549893307203363402915249e1393L, -6.302830804027849515239463308430185990705e1397L, 1.098521433860299633481449685364914115468e1402L, -1.923858597401607622723144320370279518600e1406L, 3.385512828549942051667348582951554570164e1410L, -5.986286250836771248147827011780631183980e1414L, 1.063572794668186370728928272374836554300e1419L, -1.898666684876492795233907174493757572290e1423L, 3.405627002840442789235393111726609930533e1427L, -6.137724140284450036591063946055819333244e1431L, 1.111411024660941507986132154479364267486e1436L, -2.022060876221034821890406900217875915949e1440L, 3.696248025817144690840539132103538834108e1444L, -6.788448439024998306316860676030442691610e1448L, 1.252615233049059554031883468823648511657e1453L, -2.322190433141265975888955985950824418729e1457L, 4.325200102353909846882217732999001735342e1461L, -8.093531903011880118699218269369570178812e1465L, 1.521558881878323790120983450270946857209e1470L, -2.873780311010933807686415826253380907421e1474L, 5.452903697278823304173192839252276211670e1478L, -1.039457922537509500320638240809547113575e1483L, 1.990610112724715126895008793014214505760e1487L, -3.829667853173777076954453401761025071562e1491L, 7.401624504283011888971231756333356050310e1495L, -1.437075122764477911733220492562365990710e1500L, 2.802940275035867428066581228962104019228e1504L, -5.491938363067613321364335249495394164430e1508L, 1.080961960603953462180593404647115933651e1513L, -2.137290931892412298654741768897581319007e1517L, 4.245031321673807283498263276791307370788e1521L, -8.469499523038763989328773224520912663309e1525L, 1.697421812794203793865032206191322699261e1530L, -3.417217332563937242285349373774004020539e1534L, 6.910378594841763785923780822895851271770e1538L, -1.403696282437585785557998429691459557649e1543L, 2.864060533055333035232343601021192111053e1547L, -5.869818290384811353182423286543086530728e1551L, 1.208359745327224593486268988808338456906e1556L, -2.498576742140453770373914215325521001990e1560L, 5.189311407347546310078739863704346083861e1564L, -1.082537954843916294257278789980768336964e1569L, 2.268238255751421312559806122980932952706e1573L, -4.773557403917983369065731568732198697502e1577L, 1.009019097334998841920279535262007639746e1582L, -2.142181266523235177327239693359275472557e1586L, 4.567814904130855969979178320003286614868e1590L, -9.782550516204803195398428611221899469345e1594L, 2.104180123097086948576304557651398411373e1599L, -4.545658958087323864004652894518442709646e1603L, 9.862563944609427542603740078470901803131e1607L, -2.149105846582226970866569209122813809019e1612L, 4.703235567543888152049628411354542509156e1616L, -1.033719212601584878353206879472796545848e1621L, 2.281767401903848796732740825793310514456e1625L, -5.058236070813950229238666252351966279306e1629L, 1.126112519657857205642546937554224492775e1634L, -2.517766761987679577706779689880657777343e1638L, 5.653225190181653388317503182908983211029e1642L, -1.274735955461074142223278576503188429497e1647L, 2.886578974679460464298863945016671299242e1651L, -6.564203307141426181809363135003467581753e1655L, 1.499036144473064593308260681782048262301e1660L, -3.437714715599902386917108442954580869236e1664L, 7.916830957072777234152907034541325149479e1668L, -1.830850567422571420661248197094782575285e1673L, 4.251778280827419894527511469762091846660e1677L, -9.915182507286989818033146623995507108134e1681L, 2.321878208636697663781227497233334385222e1686L, -5.459879022461660582811365437190884471726e1690L, 1.289222044549922720398543474297554204559e1695L, -3.056819658344217799458557578658863826289e1699L, 7.277891759142725294172926258364455941365e1703L, -1.739928293433385104144012025546489673795e1708L, 4.176797408823713136137404972612780406904e1712L, -1.006788178307821554781930741698052910780e1717L, 2.436754569909644399766538111317379484511e1721L, -5.921896599028498715774458493117079340155e1725L, 1.445045688171565118619109316933316429671e1730L, -3.540547766876069233350621578795319652040e1734L, 8.710114552028472554054293344204504325978e1738L, -2.151484527880464463303897113553085899101e1743L, 5.335928195512405709733771642389502809087e1747L, -1.328726408335015910030370523083559660016e1752L, 3.322090527232917400247098823651437597786e1756L, -8.339387326241218096865362177688582376376e1760L, 2.101842203781264395369771906884644062395e1765L, -5.318704469415522036482913743767085545209e1769L, 1.351288005941730688647540059088127991581e1774L, -3.446853546858473171100748720136784228698e1778L, 8.827284762030783576089954173424852998700e1782L, -2.269642226090373319660782216907175419317e1787L, 5.858820683661708553422363777419430816755e1791L, -1.518385813684321665045387969920683656625e1796L, 3.950661327164595923092260035122668890334e1800L, -1.031976516347387969958181456058243183780e1805L, 2.706317892325103782207094286049104555552e1809L, -7.125140422584701175967252533378906957380e1813L, 1.883260203116768075569432925204868418472e1818L, -4.997193687108743666000994570700725873035e1822L, 1.331182722092654526185433799891693838871e1827L, -3.559930289076558484535632566755216035553e1831L, 9.557281027056970446117541983785660301558e1835L, -2.575805002229372523547972911961335317502e1840L, 6.969058431277067406841032797913179025984e1844L, -1.892842481279278678390672746902260183506e1849L, 5.160964211693777744707760614147460787285e1853L, -1.412602588198037643242529860614298968137e1858L, 3.881313379962387603749693387037174052146e1862L, -1.070542170988009009334148472388319844527e1867L, 2.964094312414144330805731101996829908435e1871L, -8.238350132106899955856124602934281976453e1875L, 2.298504171050560756192352106062598639825e1880L, -6.437303944649223478093890316531995121228e1884L, 1.809727811843121957353712606428292269805e1889L, -5.107047553992257935533518628886728031061e1893L, 1.446674478990385642488446075734631327506e1898L, -4.113513327511444762766719175770513771122e1902L, 1.174067517257431444028448391638451935667e1907L, -3.363630086409895071362533854123306097827e1911L, 9.672868956071838221096869293070568259792e1915L, -2.792101741911955365960369780457612630184e1920L, 8.089710604557382430162031502761771390568e1924L, -2.352650988877130983061761312962677887796e1929L, 6.867549079740051556501575104006222995568e1933L, -2.012161201632998475706904405535757516336e1938L, 5.917489529279588702317256137229398357271e1942L, -1.746718667239329545125902248821502764273e1947L, 5.175069416058975040990816515838893249437e1951L, -1.538913401594651457295303469904084052963e1956L, 4.593185746210984655636051293374195150815e1960L, -1.375981868450401919299150690829612124045e1965L, 4.137207965217520410530508053863759216958e1969L, -1.248518564582257710069294326648626362439e1974L, 3.781575291117895093413381897917341286951e1978L, -1.149575999691408110085856948595444100435e1983L, 3.507413095836612229403470531176947165451e1987L, -1.074032838410645352804690949680310176413e1992L, 3.300857202456564870338466973024760446263e1996L, -1.018149578840803516349758843017979498322e2001L, 3.151876950233613792531594490714752800621e2005L, -9.792574827376149360558532022944033224780e2009L, 3.053456145978161645823454710737904504036e2014L, -9.555442346102849014299990542596620094035e2018L, 3.001037449298122384017009412541525703002e2023L, -9.459120112371096268275049056229023773120e2027L, 2.992168042152196502453442556462819104060e2032L, -9.498922680869041470681858599915282791899e2036L, 3.026307717971075309746179763189393755074e2041L, -9.676079238806159594565350708123427510151e2045L, 3.104778286352798464772361361434013339088e2050L, -9.997786802782252742109475924344598057966e2054L, 3.230847952724856366943939804248186203776e2059L, -1.047769651900498931701604323213605884945e2064L, 3.409958102134053489747140426163802214042e2068L, -1.113687894644055086152064258459886518528e2073L, 3.650114509271160332136458711252217684956e2077L, -1.200536387553969483433239131469825141412e2082L, 3.962482337718333099498977337189304099484e2086L, -1.312441206957064803437100929905979391106e2091L, 4.362246723746013772563799740886664288515e2095L, -1.454975881895253548422481637083633839534e2100L, 4.869831412214692119172895822285084162147e2104L, -1.635618419512383251104125916207188960680e2109L, 5.512611314145041257838234038980389596534e2113L, -1.864392957231340288547618808749072127289e2118L, 6.327317613106621547060670091824665547127e2122L, -2.154772001506498703267302897994526372056e2127L, 7.363426139490286496267931634843475368903e2131L, -2.524950643808031915843604894357998905460e2136L, 8.687956390288096215918373666581638675156e2140L, -2.999656978200020459428228924242615592768e2145L, 1.039231328851609224822335039430898644149e2150L, -3.612742437616019936358910410005123924796e2154L, 1.260211309932738404790711574105022002093e2159L, -4.410916378453971105434385837025433805752e2163L, 1.549140617923265948720013792673729394719e2168L, -5.459173749226782924959103886664322964926e2172L, 1.930343307630952098252884031069043541182e2177L, -6.848749229218425353808144618581305978045e2181L, 2.438117138001365487681440577590059588102e2186L, -8.708873656769794358508423272379627581292e2190L, 3.121268068338199458891764932384819739714e2195L, -1.122430216307539309816165910733145404999e2200L, 4.049900779207199370582177687160985635615e2204L, -1.466167983141158219266077836130256565915e2209L, 5.325678718693772500250292767751070974887e2213L, -1.940955845102272053048140384364058448998e2218L, 7.097467198361219669927211698104447309186e2222L, -2.603968771680987683436428778397387110896e2227L, 9.585403285394812946713320044815117440444e2231L, -3.540176030547640510648455468270569908446e2236L, 1.311827683984025111744358347783996339730e2241L, -4.877124229155333857009747836542843294702e2245L, 1.819213075760490882591173222316749809951e2250L, -6.808221630329265915405178596748950929642e2254L, 2.556299969544109052724772800143396857058e2259L, -9.629763347675306704861859899230073979116e2263L, 3.639508580119285595844040783082958425575e2268L, -1.380037493555816309137481185927387732499e2273L, 5.249980712165216709135893538080020409581e2277L, -2.003737844109055078145975651407367170529e2282L, 7.672522280806944397358668566379646540213e2286L, -2.947454993639165318799389781921184991045e2291L, 1.135966912801707623489383623092951142963e2296L, -4.392293711194501621873299212059053651432e2300L, 1.703813210168560937608104155973968112409e2305L, -6.630636743874062041158387022015853902938e2309L, 2.588742636486379690203698247275411406029e2314L, -1.013959594068423546627946242481463893979e2319L, 3.984265821528043268586235974854766821078e2323L, -1.570614519682157047612769672066387881154e2328L, 6.211297381339606877062824459742129064477e2332L, -2.464246931985476159686671650962783785426e2337L, 9.807833742601662212615240518855757197483e2341L, -3.916036434571217691317276306031837539092e2346L, 1.568566392975837368624727722120313955274e2351L, -6.302885887601142677858008037129298948063e2355L, 2.540704455306077495480843691828334210014e2360L, -1.027412480318234348899627142408950111875e2365L, 4.167823618450297116765978030480648316769e2369L, -1.696076602731914277275203926124423530377e2374L, 6.923904505633301788461482786634220738504e2378L, -2.835463065742506394026733592206185459035e2383L, 1.164828772275756526225951620927486307632e2388L, -4.800242878545012539781545966693324656699e2392L, 1.984381759611877246529319121941597679107e2397L, -8.228979942542641498511023600269641046627e2401L, 3.423130231367101727862739208673375060101e2406L, -1.428418168129733054582191895023094524495e2411L, 5.979153801634459282232521647160044877770e2415L, -2.510581926948409809562349588087762800160e2420L, 1.057443785053915411991029410076722022815e2425L, -4.467723713549428749678277264414266162837e2429L, 1.893474116528533144079731251913008472748e2434L, -8.049601965052954947260081891142509464888e2438L, 3.432648527503971149009691133946275281368e2443L, -1.468324699963694393989960228042259134294e2448L, - // - // 1302-1600: http://www.wolframalpha.com/input/?i=TABLE[N[Bernoulli[i]%2C40]%2C+{i%2C1302%2C1600%2C2}] - 6.300146502435743791500010801885493871234e2452L, -2.711520667146768856688291798851999580833e2457L, 1.170595555513900137297344452318266434006e2462L, -5.069095411973246242900074508988493530542e2466L, 2.201819284807954055092117706033113168896e2471L, -9.593088725189386197503123561368325167085e2475L, 4.192362385909155628936230811010649614060e2480L, -1.837725836941968309866675158105812946762e2485L, 8.080201101491972605313807752565294881374e2489L, -3.563536075527215702966392543784039539240e2494L, 1.576361051321107275181955665159661781175e2499L, -6.994292466180175594372663323941761853364e2503L, 3.112744353537336702834647901141392426258e2508L, -1.389481328370627358752727485697345194612e2513L, 6.221134636655213696041740685131223999953e2517L, -2.793779613656947577224654924852010601105e2522L, 1.258399062987759035354039924686781081603e2527L, -5.685208194704131918461885165870560583895e2531L, 2.576167857759537340210434756292816456179e2536L, -1.170846052338591953257169251219597581763e2541L, 5.337296787116189575571202979672747140313e2545L, -2.440264475369219459038748840841422948951e2550L, 1.119037151526195093932933161706501865175e2555L, -5.146858829220973887154576240993607686435e2559L, 2.374259791963193693837576781321391741634e2564L, -1.098501215269400934956638118646657823799e2569L, 5.097500369683616795005376807036889542869e2573L, -2.372446971688020647583535886090779018865e2578L, 1.107430282014636546248612381377039463753e2583L, -5.184597227131050012643138079903381280471e2587L, 2.434392040100910394476893838832599310265e2592L, -1.146412753331162872665743308094817095949e2597L, 5.414578104816988124950636101250217797539e2601L, -2.564835392810685332173156758121489913946e2606L, 1.218495070518549208066544111736985586178e2611L, -5.805713573821806672815019495319510297824e2615L, 2.774298194574319430697819781128985128618e2620L, -1.329580186505564627453485444017911980430e2625L, 6.390545858902318479863947547243743500916e2629L, -3.080502542499571035376377703435361520427e2634L, 1.489236104239976282318361008292980814533e2639L, -7.220413839991892382038608955317126799684e2643L, 3.510874916591640642524021216241607185085e2648L, -1.712070118580404599831061485055269100525e2653L, 8.372956919832386730490070625622785478703e2657L, -4.106629146981883685523102256292669054596e2662L, 2.019945438530802964718619732330776495740e2667L, -9.964133277392242111939720494354938982970e2671L, 4.929278642971447854669801547226335041410e2676L, -2.445509657169810919463982615395074704130e2681L, 1.216734421265677299127016883839223226884e2686L, -6.071008437677720186241562251151490713584e2690L, 3.037824949882992896564570441252792097027e2695L, -1.524402878612630565501569310883356490225e2700L, 7.671320530781999359200097739951316234193e2704L, -3.871436167706734376478728954716915204399e2709L, 1.959313530432202158587932399068682252335e2714L, -9.944063618400630821320953821427307024297e2718L, 5.061161998202463346818982228476199873781e2723L, -2.583219090831132705328958245740715185448e2728L, 1.322193991367293532684189527174543501836e2733L, -6.786569982732483290873213417465458376706e2737L, 3.493212334804776543395067018414547811062e2742L, -1.803090099978261928508495412750404640933e2747L, 9.333100843930216567894508007158644926767e2751L, -4.844499031405982604449146511179496492045e2756L, 2.521648090959971240812330574936006906830e2761L, -1.316227870932708474838173333385377250286e2766L, 6.889488826832738674261056521130795910494e2770L, -3.616184242864384509259984293501533623932e2775L, 1.903356124758119137116543283603627028779e2780L, -1.004601544584640657081847200643996069583e2785L, 5.317043885597842225603585588404817559596e2789L, -2.821938866752488868682751438901900485500e2794L, 1.501842023003449590337997900945924161741e2799L, -8.014908048137216649348740300633172710524e2803L, 4.289126235121619907138036129192558937445e2808L, -2.301619137231461344870820700320913118444e2813L, 1.238485136850053215006962645111854705210e2818L, -6.682503731149007943059244518074044280490e2822L, 3.615572393938012932030234169574978859655e2827L, -1.961565108627429629104703146282982075623e2832L, 1.067123259692924564435881096382837264046e2837L, -5.821179870182035246401397327057170726418e2841L, 3.184127229476322727732208017279268211356e2846L, -1.746429902183019597973436257300843998825e2851L, 9.604873565299766333876882842813498685054e2855L, -5.296759978724702692134960752308186890356e2860L, 2.928906353338652198977536576170287112391e2865L, -1.623961162577704769945821804737884742792e2870L, 9.028574047002736235613238355032484299017e2874L, -5.033087486357905828950503441308068892610e2879L, 2.813325650062267479031371852434194635210e2884L, -1.576791132296320840138263753339056345362e2889L, 8.861258343945925667272164531504265693289e2893L, -4.993236404321511029440212686547068244002e2898L, 2.821192993950901287717082243608730217471e2903L, -1.598254169674379493385730199445427966752e2908L, 9.078617590346932363947095804057608979359e2912L, -5.170742114456472142154347566092068443393e2917L, 2.952866185102528847516095880416675972086e2922L, -1.690794578626103552690094140317813413244e2927L, 9.707168799669516048238542260085175133847e2931L, -5.587884732306715493795271931175883605707e2936L, 3.225179489154957423492905957887744116530e2941L, -1.866424419669188178697802576490431604300e2946L, 1.082967626854618222657109354056973072044e2951L, -6.300392007169862865282706277272018077291e2955L, 3.675066377245428685118763485986517510658e2960L, -2.149348371085132073107516253339849053182e2965L, 1.260349351812619395000600434630904474324e2970L, -7.409963623771231302980906971935254993610e2974L, 4.367980758467862686643231700861155889684e2979L, -2.581566823350789671250829457603555544100e2984L, 1.529757357568342629912560827243282062227e2989L, -9.088595394263364554625061567617375176719e2993L, 5.413829169254585648363594604231030415354e2998L, -3.233288119606092759447005827969216281573e3003L, 1.936042437734875803183915765854038424658e3008L, -1.162289934202291715747729318797398221667e3013L, 6.995870350500567071550614251287615697508e3017L, -4.221776496490106417392945233048068288503e3022L, 2.554309239868912570382343877718991746122e3027L, -1.549440871550119801225143558087410562418e3032L, 9.423199525954784955533959981278992475051e3036L, -5.745689660772387668861183913170050552119e3041L, 3.512407521007240798565045328376471603253e3046L, -2.152708113797517364614914569890010876143e3051L, 1.322761289733739440340237168659770154654e3056L, -8.148777388506488753591136948542248584098e3060L, 5.032880858479326069741729004270784264612e3065L, -3.116396010103058126269735274818345780360e3070L, 1.934634831148214353514796782480703021435e3075L, -1.204077166243116651938489240924641810276e3080L, 7.513065583444964704795707060501161621868e3084L, -4.699873512563164914493150520500838535415e3089L, 2.947541197349762411713872934523813866703e3094L, -1.853262416286420077763886100673646141885e3099L, 1.168196427912100545575264493997591040800e3104L, -7.382362285873345348505276546404015842875e3108L, 4.677071041058096429847797962954927487730e3113L, -2.970642034084362431442183248944824506476e3118L, 1.891572688282564476274920103912259755482e3123L, -1.207509963440193713810418554061532113326e3128L, 7.727731208240101791845515599659441557781e3132L, -4.957988488048495669466804712012179891532e3137L, 3.188965862446236259925047956715566822864e3142L, -2.056286895821370106507670239256782411337e3147L, 1.329246918771714093479509313343886287414e3152L, -8.614188519577835653765633797787633659253e3156L, - // - // 1602-1900: http://www.wolframalpha.com/input/?i=TABLE[N[Bernoulli[i]%2C40]%2C+{i%2C1602%2C1900%2C2}] - 5.596396533621874175909933615343145642161e3161L, -3.644908483469388437457938883454376864180e3166L, 2.379838409026860469990569665632800095988e3171L, -1.557720925267669865362152155022069166772e3176L, 1.022143420270029721682551084917730373739e3181L, -6.723767358891570842116651998814252095792e3185L, 4.433950491570308179905446963723780229747e3190L, -2.931196854668917448553150023532223509373e3195L, 1.942557068752664549549945921392100172355e3200L, -1.290553202978622786891265558106235068695e3205L, 8.595082329732118303768775883557789195136e3209L, -5.738453265222970049867280061719670658457e3214L, 3.840687915100689856736926915331157331684e3219L, -2.576862441955523551149886625900059307506e3224L, 1.733166107320377310388765047659987844208e3229L, -1.168569552450178559412843683052610870569e3234L, 7.898289836694980777809433306209459851871e3238L, -5.351485909164216694400535493924387979018e3243L, 3.634772439350395177931952925644409735777e3248L, -2.474801048002975145046569303233576339695e3253L, 1.689126939254790850063878942448569759390e3258L, -1.155691524500722774057997965355407962525e3263L, 7.926435404542361405718288670391575676323e3267L, -5.449654814183048796524718620178906854846e3272L, 3.755898589900254795894812942275711835138e3277L, -2.594843902682143854622514329649211211808e3282L, 1.797048752397789969347915328338360264536e3287L, -1.247551415074438712713815166107969504456e3292L, 8.681719521514448143910215886388510318746e3296L, -6.056203898213120922016159444227958572276e3301L, 4.234882876331814099029781995617143573641e3306L, -2.968432911643338866295929748049749932906e3311L, 2.085723508930484816454740610260790948864e3316L, -1.469023169879432026361623513301566735138e3321L, 1.037150346505052892302077637883522696572e3326L, -7.339977067836656769144838365069396168014e3330L, 5.206985412168234130596004552956337839140e3335L, -3.702673773319239583641029108403509825141e3340L, 2.639251227995760315076225206168354089692e3345L, -1.885736353072698581595150856674914203383e3350L, 1.350563292338261784288559687678302458996e3355L, -9.695749980998301526113046898985991802000e3359L, 6.977167462628398202151721319169989304520e3364L, -5.032768280399753942925624560483352299263e3369L, 3.638844963651800168080623511900705036698e3374L, -2.637228631269251606169613775399022890118e3379L, 1.915836351653767108720464847696767898597e3384L, -1.395064293615007319328267865803567670760e3389L, 1.018249052614943190644465556486933211307e3394L, -7.449662162606857550867922631658930320805e3398L, 5.463119632208085241594107781601567713991e3403L, -4.015736541676989144201935890497836963875e3408L, 2.958754190183866660901503059509579790900e3413L, -2.185096074054288399312733179064098492511e3418L, 1.617517444557020250864919655301189186103e3423L, -1.200170662015511746748935675940010250555e3428L, 8.925888349899029449015791684428724952411e3432L, -6.653851763691885517669938275618991145962e3437L, 4.971722031098457895973348076474071155918e3442L, -3.723500582577984967442020337848702786829e3447L, 2.795153783541721373364976034391375710110e3452L, -2.103141577212720698169118819883801186873e3457L, 1.586129575320959267959148073466004084241e3462L, -1.198988457279648730711646682156242973137e3467L, 9.084402368157025658430300252246526602197e3471L, -6.898927494435965163817354296023108913714e3476L, 5.251332286149361587885046891266325872375e3481L, -4.006442950956739933884502808470603581850e3486L, 3.063718202820270282280659950794978994604e3491L, -2.348215284130973783732145823834807395920e3496L, 1.803952490148087317330011096671019781340e3501L, -1.389022326803437345760911068933754707688e3506L, 1.071986115818329525986099441493200866389e3511L, -8.292085224650940719705699485423856363908e3515L, 6.428829064452939640541475198655560890344e3520L, -4.995654440302797445368056643032307686314e3525L, 3.890847042582299188849273838681034339406e3530L, -3.037288555751484681537442833929275697351e3535L, 2.376385803695694695338601696534348875191e3540L, -1.863527130251861900692886008704804849076e3545L, 1.464674913498036269270793715104706378182e3550L, -1.153804954579033578659954846698233083197e3555L, 9.109783835348935092264268296199541780964e3559L, -7.208869193983001804305451104827153729326e3564L, 5.717530734277611949162917337810749919265e3569L, -4.544970302634007326980094771330550661605e3574L, 3.621042850825283032134228901678636353355e3579L, -2.891447067949778492831490654980043715471e3584L, 2.314060419397710657435821461707043283167e3589L, -1.856140759923563235273220981623595304434e3594L, 1.492185412981476596273279338314204171587e3599L, -1.202290032627175365810126250991853594801e3604L, 9.708881154579770196658265042625239421053e3608L, -7.857809850747029705680072304049448493252e3613L, 6.373898598298513400228819113197728735438e3618L, -5.181780406472117449048907989647202286666e3623L, 4.222036621953044040518942750638183171221e3628L, -3.447728386429130175025813550845575613047e3633L, 2.821701521717856346224159586852612710800e3638L, -2.314488376711998526455043944505424906920e3643L, 1.902671298033180765286213227393060711096e3648L, -1.567603736821312488140289549008391847440e3653L, 1.294408945316538946551785312385509945367e3658L, -1.071194533081615830960091702262923009420e3663L, 8.884351908108581551151252566466606126397e3667L, -7.384866682828103669170236267589653324531e3672L, 6.152023838008155718180876735217718355563e3677L, -5.136304310431705506236573876510219357975e3682L, 4.297736808124296434723193397876220759378e3687L, -3.603994887745884762510172194982172483480e3692L, 3.028884745605031552399167746007361297342e3697L, -2.551141302205187365552982635794121855138e3702L, 2.153467982869535549299173317536193051608e3707L, -1.821769476343602094059466497311600827296e3712L, 1.544537580582347892980177956984101211006e3717L, -1.312358705945937257247030754517293537539e3722L, 1.117518229297781388884979995402355617235e3727L, -9.536820860779441793021624381677086661097e3731L, 8.156400668831968026931547065507466530546e3736L, -6.990984948728184142718575396052260691181e3741L, 6.005124901126818071638224144541102727563e3746L, -5.169500241880947716732682089328427995109e3751L, 4.459815478235310026240134567325749844182e3756L, -3.855902253361684187081283218890336962427e3761L, 3.340988024176995223515640815937037040546e3766L, -2.901099226680215736735094376078800376829e3771L, 2.524573363444334459448089563912567842927e3776L, -2.201659455716348555524529213295341212492e3781L, 1.924190302190936448078364755844591374353e3786L, -1.685313186099770223843319514432495898517e3791L, 1.479268235966730475749985741048766689808e3796L, -1.301205702893883803117530921635013780575e3801L, 1.147035071153450453405384269242743907426e3806L, -1.013300250456366849150496776951686112298e3811L, 8.970761720605591762300958007557533865346e3815L, -7.958829781488943084496783248922217392838e3820L, 7.076146954685024795720193943027902028642e3825L, -6.304798526260409199660290516451546966159e3830L, 5.629519616664188107056583939722984509867e3835L, -5.037281594099054092767959480843344929292e3840L, 4.516946091316834843581919268794683123349e3845L, -4.058975118925834202620358386772092359951e3850L, 3.655187798978978909014603682039470653549e3855L, -3.298555903041546671060101785513812175322e3860L, 2.983031738662727912016882399515879119620e3865L, -2.703403043317732979516341931451317866898e3870L, 2.455170460800096241793872443768546335444e3875L, -2.234443928432490538417605502448376856290e3880L, 2.037854924078003280537856980560782325730e3885L, -1.862482033918775734840779765743099458137e3890L, - // - // 1902-2200: http://www.wolframalpha.com/input/?i=TABLE[N[Bernoulli[i]%2C40]%2C+{i%2C1902%2C2200%2C2}] - 1.705787724951999960095629912416210969679e3895L, -1.565564556110550991891247404758895970376e3900L, 1.439889351869832939488618785632174464789e3905L, -1.327084102784257406218693901793045990520e3910L, 1.225682557296027075027021534960026145706e3915L, -1.134401635488994148555787301654561211982e3920L, 1.052116934052356802920509999705307165985e3925L, -9.778417073593082219082361206542342793584e3929L, 9.107088061888562704837019028349522303725e3934L, -8.499551364633102138471246155980056936129e3939L, 7.949082681085658044610890152056533167407e3944L, -7.449748809722797718736397140511396011691e3949L, 6.996307824769340144608141799981589288378e3954L, -6.584122718472954006131003060359621706243e3959L, 6.209086595833487707192492087176843233407e3964L, -5.867557793863165391821489909125720982339e3969L, 5.556303538475260373917478405626416604297e3974L, -5.272450955936249442242634142613834212778e3979L, 5.013444428433789818228792126117223030641e3984L, -4.777008429684552423800736200488532033034e3989L, 4.561115100786341787876705283291018781137e3994L, -4.363955932181992701667719449097126840439e3999L, 4.183917007557000586305945495258591147615e4004L, -4.019557342177353010692923286760895584096e4009L, 3.869589913635745758786275231296652917580e4014L, -3.732865038934070181861017140563175000872e4019L, 3.608355799736107390800162778737339576843e4024L, -3.495145258697474565347261083975193776541e4029L, 3.392415245050326563747729613872524362741e4034L, -3.299436517958948801426629481782413630714e4039L, 3.215560142306355508598119430378551642857e4044L, -3.140209934146377815556058799557727461298e4049L, 3.072875852591406752692761744649563131272e4054L, -3.013108231854799187724018548255922550991e4059L, 2.960512761914376268185064129600549308882e4064L, -2.914746139139036596123006476633770383901e4069L, 2.875512319506974985103149834921665445532e4074L, -2.842559316984704569380036093537576068104e4079L, 2.815676498441436148701483904115879856704e4084L, -2.794692334326268275058539147656334465534e4089L, 2.779472571396106785963004020814493340829e4094L, -2.769918800191406321625251621260024635680e4099L, 2.765967395840433013288935879837390099329e4104L, -2.767588816244119880300161388073836623878e4109L, 2.774787246856347651152278076466043136230e4114L, -2.787600586224957950622601135620189837948e4119L, 2.806100771288225169339048358106052817280e4124L, -2.830394446218080573456394167711739786431e4129L, 2.860623983452244712039094143642843717029e4134L, -2.896968870550611723525738907034588104300e4139L, 2.939647481737606306044335918078617963078e4144L, -2.988919258547518526076380181812161398808e4149L, 3.045087329976721023952450383837883029431e4154L, -3.108501609077197464748958150625867523408e4159L, 3.179562410123820875787052833975010965963e4164L, -3.258724638491880104953913719767939138170e4169L, 3.346502614347964869115073881474258766546e4174L, -3.443475601364631413158991572423086599816e4179L, 3.550294123121350747300886840907918182129e4184L, -3.667687162886053419715985091863398517145e4189L, 3.796470357354794420044278000297864085607e4194L, -3.937555311976846882455930574021795626971e4199L, 4.091960185075595842547638450930710467324e4204L, -4.260821710519620959138720129506770036460e4209L, 4.445408854703156440576808070360934740837e4214L, -4.647138333645908068599900650548418672065e4219L, 4.867592250805288922190809906525766574205e4224L, -5.108538156515551259475573296900660666192e4229L, 5.371951876776035157276013631113314852508e4234L, -5.660043513521220243900043448456234873940e4239L, 5.975287081834808618140945840817834710330e4244L, -6.320454323372684034118816565375206053746e4249L, 6.698653321371992324876559665938996023646e4254L, -7.113372643219128807424340495235606473967e4259L, 7.568531854202750881338746432078817214052e4264L, -8.068539383842553693076672384509126681464e4269L, 8.618358887685935324188596304168259394311e4274L, -9.223585437012291673660319256730398171887e4279L, 9.890533091606747031464718533600572123091e4284L, -1.062633567277107015128545384570274268438e4290L, 1.143906286231591191271274413511275981288e4295L, -1.233785411712565904499340744089870916842e4300L, 1.333307331840530219050170916015276125870e4305L, -1.443648758235403286296065629219598769529e4310L, 1.566147425967471851736562867318748510088e4315L, -1.702326086290842780634120184324081017286e4320L, 1.853920350455786350409148418966087344063e4325L, -2.022911043115598592197907512410632615740e4330L, 2.211561842992792253055716743938240466613e4335L, -2.422463130294011318178080247305407476096e4340L, 2.658583129381772791030436640519847627789e4345L, -2.923327636881988941081365085520742216540e4350L, 3.220609866329557159104267531058019683271e4355L, -3.554932228621330128152149026066400241546e4360L, 3.931482212643167323798366327390058684499e4365L, -4.356244944221399578650235478583297389113e4370L, 4.836135498303121165971331625888490168138e4375L, -5.379154636371461359750682662639062606297e4380L, 5.994572359716861309678596804350346692501e4385L, -6.693144535124290060793936095397161934045e4390L, 7.487368894313509797084395689517008597061e4395L, -8.391787970609807810531578161564037339793e4400L, 9.423348062978921203475110312003096820035e4405L, -1.060182516651648405903017734022504884319e4411L, 1.195033105063952979885086754342706651656e4416L, -1.349591538868673992167798923586925758429e4421L, 1.527028315253291113905307092657539132480e4426L, -1.731065051510920640409442255224015234974e4431L, 1.966076741510092840076264635935585216200e4436L, -2.237214093245750681191361238831105906202e4441L, 2.550550094903891445719729187215253324232e4446L, -2.913255853313667303707651906277658164129e4451L, 3.333811847072394764285817140850092324169e4456L, -3.822262084288044913490118858492563410392e4461L, 4.390520310533864198186202368026630430120e4466L, -5.052739449335052080092114976206610871466e4471L, 5.825757966350870043117899492954521458799e4476L, -6.729639942938203582008846884575881320532e4481L, 7.788329466816396015493306357116312471970e4486L, -9.030444674469025073047417528762134025409e4491L, 1.049024263381993629167658236142000524752e4497L, -1.220879351508964912255081664072251573277e4502L, 1.423541151220109512749655991050110438471e4507L, -1.662940118618541616964708044356967429362e4512L, 1.946219185900482116137855064775635250366e4517L, -2.281995008842006909631764011781911322493e4522L, 2.680678198213108543648324254258111216040e4527L, -3.154866427472784086389609599207759103500e4532L, 3.719827710160801797530420206201570269720e4537L, -4.394095404360277919140027580071549980218e4542L, 5.200201854779615608741690339830306148442e4547L, -6.165584312943608652377791415603277251516e4552L, 7.323705248531382981433751104158852636445e4557L, -8.715439846124090647163930834760361817820e4562L, 1.039079696609215651011736087603304766850e4568L, -1.241105689556982425619608247473478857800e4573L, 1.485143079696380339521658550262280772546e4578L, -1.780437412164973637340821168154300094802e4583L, 2.138372099157518882088209435171770222745e4588L, -2.572985071149069551034276570909360759588e4593L, 3.101615379617643734762997559011097203354e4598L, -3.745713657616368229906151946770042703357e4603L, 4.531859496161940719835150033082561700677e4608L, -5.493040495326927998321538336584233566465e4613L, 6.670262730603009306595018122252730741798e4618L, -8.114581584793494903775255213273982440688e4623L, 9.889666561810883044159054730371102725871e4628L, -1.207504541653929734716275932570097623330e4634L, 1.477021377885843688233899471354959308782e4639L, -1.809984912147908767583043524070645821179e4644L, - // - // 2202-2320: http://www.wolframalpha.com/input/?i=TABLE[N[Bernoulli[i]%2C40]%2C+{i%2C2202%2C2320%2C2}] - 2.222043594325228980916360265527780300093e4649L, -2.732869701246338361699515268224049951411e4654L, 3.367233945421922463553518272642397177145e4659L, -4.156377225041273602431272489314020150392e4664L, 5.139764368092890466235162431795350591151e4669L, -6.367329693760865476879589228002216011370e4674L, 7.902356742934106007362514378717026407839e4679L, -9.825176966314431712897976595483070301406e4684L, 1.223792760178593282435724837135946867088e4690L, -1.527068151452750404853140815207477555192e4695L, 1.908935682572268829496101580401263597905e4700L, -2.390593888616966248780378941331847473699e4705L, 2.999171106576893833644521002894489856321e4710L, -3.769440655453736670024798444784356437578e4715L, 4.746047769851891438576002047529258107351e4720L, -5.986405469241447720766576164546767533359e4725L, 7.564466155536872051712519119999711534616e4730L, -9.575641408047918720040356745796976488951e4735L, 1.214322951835035451699619713803395497423e4741L, -1.542682591979864353012093794301924196234e4746L, 1.963334539793192183270983986567556358603e4751L, -2.503148969013901182572118121398034622584e4756L, 3.197076711250102964526567664729089847162e4761L, -4.090653552025822488578293526174572934858e4766L, 5.243302769651520536759521264615159906699e4771L, -6.732697170903775309261288127044088674182e4776L, 8.660529543801770516930589210020128142543e4781L, -1.116015823611149634592870112730519454113e4787L, 1.440675306432920129218036927923030695520e4792L, -1.863078034853256227415397798026969938881e4797L, 2.413595413458810442409656314019115041699e4802L, -3.132317029597258599678590012779717945144e4807L, 4.072246763371584312534474102756137619716e4812L, -5.303577511521827157146305369181950467569e4817L, 6.919417518688636032335131253584331645491e4822L, -9.043473312934241153732087612484569398979e4827L, 1.184037400265044213826044590639924237359e4833L, -1.552956685415800894409743993367334099777e4838L, 2.040404893052952221581694807126473204625e4843L, -2.685565763841580219033402331219206776210e4848L, 3.540927057361929050327811875290025248120e4853L, -4.676912607538885419407656762767991163574e4858L, 6.188165903566760647569323704623433330229e4863L, -8.202087471895029964699042637255411806373e4868L, 1.089045274355389654614196651761310970580e4874L, -1.448524684976553869119447042300206226148e4879L, 1.930028100376784839502387280956424581974e4884L, -2.576074799096023589462128312524664980682e4889L, 3.444369635011990347297134928452972402038e4894L, -4.613354441299253694113609154769978684993e4899L, 6.189834306866879018555349507257537840922e4904L, -8.319470760665157534580593571258276368233e4909L, 1.120124240070996761986102680587384813245e4915L, -1.510740451399746828351090108638980398124e4920L, 2.041108231091323198877509959371257503819e4925L, -2.762447751447012472733302936575873838539e4930L, -#endif - }}; - - return bernoulli_data[n]; -} - -template -inline T unchecked_bernoulli_imp(std::size_t n, const mpl::int_<4>& ) -{ - // - // Special case added for multiprecision types that have no conversion from long long, - // there are very few such types, but mpfr_class is one. - // - static const boost::array::value> numerators = - {{ - boost::int32_t( +1LL), - boost::int32_t( +1LL), - boost::int32_t( -1LL), - boost::int32_t( +1LL), - boost::int32_t( -1LL), - boost::int32_t( +5LL), - boost::int32_t( -691LL), - boost::int32_t( +7LL), - boost::int32_t( -3617LL), - boost::int32_t( +43867LL), - boost::int32_t( -174611LL), - boost::int32_t( +854513LL), - }}; - - static const boost::array::value> denominators = - {{ - boost::int32_t( 1LL), - boost::int32_t( 6LL), - boost::int32_t( 30LL), - boost::int32_t( 42LL), - boost::int32_t( 30LL), - boost::int32_t( 66LL), - boost::int32_t( 2730LL), - boost::int32_t( 6LL), - boost::int32_t( 510LL), - boost::int32_t( 798LL), - boost::int32_t( 330LL), - boost::int32_t( 138LL), - }}; - return T(numerators[n]) / T(denominators[n]); -} - -} // namespace detail - -template -inline T unchecked_bernoulli_b2n(const std::size_t n) -{ - typedef mpl::int_::value> tag_type; - - return detail::unchecked_bernoulli_imp(n, tag_type()); -} - -}} // namespaces - -#endif // BOOST_MATH_UNCHECKED_BERNOULLI_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/math_fwd.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/math_fwd.hpp deleted file mode 100644 index d9eff247c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/math_fwd.hpp +++ /dev/null @@ -1,1586 +0,0 @@ -// math_fwd.hpp - -// TODO revise completely for new distribution classes. - -// Copyright Paul A. Bristow 2006. -// Copyright John Maddock 2006. - -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt -// or copy at http://www.boost.org/LICENSE_1_0.txt) - -// Omnibus list of forward declarations of math special functions. - -// IT = Integer type. -// RT = Real type (built-in floating-point types, float, double, long double) & User Defined Types -// AT = Integer or Real type - -#ifndef BOOST_MATH_SPECIAL_MATH_FWD_HPP -#define BOOST_MATH_SPECIAL_MATH_FWD_HPP - -#ifdef _MSC_VER -#pragma once -#endif - -#include "policy.hpp" -#include -#include // for argument promotion. -#include -#include -#include - -#define BOOST_NO_MACRO_EXPAND /**/ - -namespace boost -{ - namespace math - { // Math functions (in roughly alphabetic order). - - // Beta functions. - template - typename tools::promote_args::type - beta(RT1 a, RT2 b); // Beta function (2 arguments). - - template - typename tools::promote_args::type - beta(RT1 a, RT2 b, A x); // Beta function (3 arguments). - - template - typename tools::promote_args::type - beta(RT1 a, RT2 b, RT3 x, const Policy& pol); // Beta function (3 arguments). - - template - typename tools::promote_args::type - betac(RT1 a, RT2 b, RT3 x); - - template - typename tools::promote_args::type - betac(RT1 a, RT2 b, RT3 x, const Policy& pol); - - template - typename tools::promote_args::type - ibeta(RT1 a, RT2 b, RT3 x); // Incomplete beta function. - - template - typename tools::promote_args::type - ibeta(RT1 a, RT2 b, RT3 x, const Policy& pol); // Incomplete beta function. - - template - typename tools::promote_args::type - ibetac(RT1 a, RT2 b, RT3 x); // Incomplete beta complement function. - - template - typename tools::promote_args::type - ibetac(RT1 a, RT2 b, RT3 x, const Policy& pol); // Incomplete beta complement function. - - template - typename tools::promote_args::type - ibeta_inv(T1 a, T2 b, T3 p, T4* py); - - template - typename tools::promote_args::type - ibeta_inv(T1 a, T2 b, T3 p, T4* py, const Policy& pol); - - template - typename tools::promote_args::type - ibeta_inv(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function. - - template - typename tools::promote_args::type - ibeta_inv(RT1 a, RT2 b, RT3 p, const Policy&); // Incomplete beta inverse function. - - template - typename tools::promote_args::type - ibeta_inva(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function. - - template - typename tools::promote_args::type - ibeta_inva(RT1 a, RT2 b, RT3 p, const Policy&); // Incomplete beta inverse function. - - template - typename tools::promote_args::type - ibeta_invb(RT1 a, RT2 b, RT3 p); // Incomplete beta inverse function. - - template - typename tools::promote_args::type - ibeta_invb(RT1 a, RT2 b, RT3 p, const Policy&); // Incomplete beta inverse function. - - template - typename tools::promote_args::type - ibetac_inv(T1 a, T2 b, T3 q, T4* py); - - template - typename tools::promote_args::type - ibetac_inv(T1 a, T2 b, T3 q, T4* py, const Policy& pol); - - template - typename tools::promote_args::type - ibetac_inv(RT1 a, RT2 b, RT3 q); // Incomplete beta complement inverse function. - - template - typename tools::promote_args::type - ibetac_inv(RT1 a, RT2 b, RT3 q, const Policy&); // Incomplete beta complement inverse function. - - template - typename tools::promote_args::type - ibetac_inva(RT1 a, RT2 b, RT3 q); // Incomplete beta complement inverse function. - - template - typename tools::promote_args::type - ibetac_inva(RT1 a, RT2 b, RT3 q, const Policy&); // Incomplete beta complement inverse function. - - template - typename tools::promote_args::type - ibetac_invb(RT1 a, RT2 b, RT3 q); // Incomplete beta complement inverse function. - - template - typename tools::promote_args::type - ibetac_invb(RT1 a, RT2 b, RT3 q, const Policy&); // Incomplete beta complement inverse function. - - template - typename tools::promote_args::type - ibeta_derivative(RT1 a, RT2 b, RT3 x); // derivative of incomplete beta - - template - typename tools::promote_args::type - ibeta_derivative(RT1 a, RT2 b, RT3 x, const Policy& pol); // derivative of incomplete beta - - // Binomial: - template - T binomial_coefficient(unsigned n, unsigned k, const Policy& pol); - template - T binomial_coefficient(unsigned n, unsigned k); - - // erf & erfc error functions. - template // Error function. - typename tools::promote_args::type erf(RT z); - template // Error function. - typename tools::promote_args::type erf(RT z, const Policy&); - - template // Error function complement. - typename tools::promote_args::type erfc(RT z); - template // Error function complement. - typename tools::promote_args::type erfc(RT z, const Policy&); - - template // Error function inverse. - typename tools::promote_args::type erf_inv(RT z); - template // Error function inverse. - typename tools::promote_args::type erf_inv(RT z, const Policy& pol); - - template // Error function complement inverse. - typename tools::promote_args::type erfc_inv(RT z); - template // Error function complement inverse. - typename tools::promote_args::type erfc_inv(RT z, const Policy& pol); - - // Polynomials: - template - typename tools::promote_args::type - legendre_next(unsigned l, T1 x, T2 Pl, T3 Plm1); - - template - typename tools::promote_args::type - legendre_p(int l, T x); -#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1310) - template - typename boost::enable_if_c::value, typename tools::promote_args::type>::type - legendre_p(int l, T x, const Policy& pol); -#endif - template - typename tools::promote_args::type - legendre_q(unsigned l, T x); -#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1310) - template - typename boost::enable_if_c::value, typename tools::promote_args::type>::type - legendre_q(unsigned l, T x, const Policy& pol); -#endif - template - typename tools::promote_args::type - legendre_next(unsigned l, unsigned m, T1 x, T2 Pl, T3 Plm1); - - template - typename tools::promote_args::type - legendre_p(int l, int m, T x); - - template - typename tools::promote_args::type - legendre_p(int l, int m, T x, const Policy& pol); - - template - typename tools::promote_args::type - laguerre_next(unsigned n, T1 x, T2 Ln, T3 Lnm1); - - template - typename tools::promote_args::type - laguerre_next(unsigned n, unsigned l, T1 x, T2 Pl, T3 Plm1); - - template - typename tools::promote_args::type - laguerre(unsigned n, T x); - - template - typename tools::promote_args::type - laguerre(unsigned n, unsigned m, T x, const Policy& pol); - - template - struct laguerre_result - { - typedef typename mpl::if_< - policies::is_policy, - typename tools::promote_args::type, - typename tools::promote_args::type - >::type type; - }; - - template - typename laguerre_result::type - laguerre(unsigned n, T1 m, T2 x); - - template - typename tools::promote_args::type - hermite(unsigned n, T x); - - template - typename tools::promote_args::type - hermite(unsigned n, T x, const Policy& pol); - - template - typename tools::promote_args::type - hermite_next(unsigned n, T1 x, T2 Hn, T3 Hnm1); - - template - std::complex::type> - spherical_harmonic(unsigned n, int m, T1 theta, T2 phi); - - template - std::complex::type> - spherical_harmonic(unsigned n, int m, T1 theta, T2 phi, const Policy& pol); - - template - typename tools::promote_args::type - spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi); - - template - typename tools::promote_args::type - spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi, const Policy& pol); - - template - typename tools::promote_args::type - spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi); - - template - typename tools::promote_args::type - spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi, const Policy& pol); - - // Elliptic integrals: - template - typename tools::promote_args::type - ellint_rf(T1 x, T2 y, T3 z); - - template - typename tools::promote_args::type - ellint_rf(T1 x, T2 y, T3 z, const Policy& pol); - - template - typename tools::promote_args::type - ellint_rd(T1 x, T2 y, T3 z); - - template - typename tools::promote_args::type - ellint_rd(T1 x, T2 y, T3 z, const Policy& pol); - - template - typename tools::promote_args::type - ellint_rc(T1 x, T2 y); - - template - typename tools::promote_args::type - ellint_rc(T1 x, T2 y, const Policy& pol); - - template - typename tools::promote_args::type - ellint_rj(T1 x, T2 y, T3 z, T4 p); - - template - typename tools::promote_args::type - ellint_rj(T1 x, T2 y, T3 z, T4 p, const Policy& pol); - - template - typename tools::promote_args::type - ellint_rg(T1 x, T2 y, T3 z); - - template - typename tools::promote_args::type - ellint_rg(T1 x, T2 y, T3 z, const Policy& pol); - - template - typename tools::promote_args::type ellint_2(T k); - - template - typename tools::promote_args::type ellint_2(T1 k, T2 phi); - - template - typename tools::promote_args::type ellint_2(T1 k, T2 phi, const Policy& pol); - - template - typename tools::promote_args::type ellint_1(T k); - - template - typename tools::promote_args::type ellint_1(T1 k, T2 phi); - - template - typename tools::promote_args::type ellint_1(T1 k, T2 phi, const Policy& pol); - - template - typename tools::promote_args::type ellint_d(T k); - - template - typename tools::promote_args::type ellint_d(T1 k, T2 phi); - - template - typename tools::promote_args::type ellint_d(T1 k, T2 phi, const Policy& pol); - - template - typename tools::promote_args::type jacobi_zeta(T1 k, T2 phi); - - template - typename tools::promote_args::type jacobi_zeta(T1 k, T2 phi, const Policy& pol); - - template - typename tools::promote_args::type heuman_lambda(T1 k, T2 phi); - - template - typename tools::promote_args::type heuman_lambda(T1 k, T2 phi, const Policy& pol); - - namespace detail{ - - template - struct ellint_3_result - { - typedef typename mpl::if_< - policies::is_policy, - typename tools::promote_args::type, - typename tools::promote_args::type - >::type type; - }; - - } // namespace detail - - - template - typename detail::ellint_3_result::type ellint_3(T1 k, T2 v, T3 phi); - - template - typename tools::promote_args::type ellint_3(T1 k, T2 v, T3 phi, const Policy& pol); - - template - typename tools::promote_args::type ellint_3(T1 k, T2 v); - - // Factorial functions. - // Note: not for integral types, at present. - template - struct max_factorial; - template - RT factorial(unsigned int); - template - RT factorial(unsigned int, const Policy& pol); - template - RT unchecked_factorial(unsigned int BOOST_MATH_APPEND_EXPLICIT_TEMPLATE_TYPE(RT)); - template - RT double_factorial(unsigned i); - template - RT double_factorial(unsigned i, const Policy& pol); - - template - typename tools::promote_args::type falling_factorial(RT x, unsigned n); - - template - typename tools::promote_args::type falling_factorial(RT x, unsigned n, const Policy& pol); - - template - typename tools::promote_args::type rising_factorial(RT x, int n); - - template - typename tools::promote_args::type rising_factorial(RT x, int n, const Policy& pol); - - // Gamma functions. - template - typename tools::promote_args::type tgamma(RT z); - - template - typename tools::promote_args::type tgamma1pm1(RT z); - - template - typename tools::promote_args::type tgamma1pm1(RT z, const Policy& pol); - - template - typename tools::promote_args::type tgamma(RT1 a, RT2 z); - - template - typename tools::promote_args::type tgamma(RT1 a, RT2 z, const Policy& pol); - - template - typename tools::promote_args::type lgamma(RT z, int* sign); - - template - typename tools::promote_args::type lgamma(RT z, int* sign, const Policy& pol); - - template - typename tools::promote_args::type lgamma(RT x); - - template - typename tools::promote_args::type lgamma(RT x, const Policy& pol); - - template - typename tools::promote_args::type tgamma_lower(RT1 a, RT2 z); - - template - typename tools::promote_args::type tgamma_lower(RT1 a, RT2 z, const Policy&); - - template - typename tools::promote_args::type gamma_q(RT1 a, RT2 z); - - template - typename tools::promote_args::type gamma_q(RT1 a, RT2 z, const Policy&); - - template - typename tools::promote_args::type gamma_p(RT1 a, RT2 z); - - template - typename tools::promote_args::type gamma_p(RT1 a, RT2 z, const Policy&); - - template - typename tools::promote_args::type tgamma_delta_ratio(T1 z, T2 delta); - - template - typename tools::promote_args::type tgamma_delta_ratio(T1 z, T2 delta, const Policy&); - - template - typename tools::promote_args::type tgamma_ratio(T1 a, T2 b); - - template - typename tools::promote_args::type tgamma_ratio(T1 a, T2 b, const Policy&); - - template - typename tools::promote_args::type gamma_p_derivative(T1 a, T2 x); - - template - typename tools::promote_args::type gamma_p_derivative(T1 a, T2 x, const Policy&); - - // gamma inverse. - template - typename tools::promote_args::type gamma_p_inv(T1 a, T2 p); - - template - typename tools::promote_args::type gamma_p_inva(T1 a, T2 p, const Policy&); - - template - typename tools::promote_args::type gamma_p_inva(T1 a, T2 p); - - template - typename tools::promote_args::type gamma_p_inv(T1 a, T2 p, const Policy&); - - template - typename tools::promote_args::type gamma_q_inv(T1 a, T2 q); - - template - typename tools::promote_args::type gamma_q_inv(T1 a, T2 q, const Policy&); - - template - typename tools::promote_args::type gamma_q_inva(T1 a, T2 q); - - template - typename tools::promote_args::type gamma_q_inva(T1 a, T2 q, const Policy&); - - // digamma: - template - typename tools::promote_args::type digamma(T x); - - template - typename tools::promote_args::type digamma(T x, const Policy&); - - // trigamma: - template - typename tools::promote_args::type trigamma(T x); - - template - typename tools::promote_args::type trigamma(T x, const Policy&); - - // polygamma: - template - typename tools::promote_args::type polygamma(int n, T x); - - template - typename tools::promote_args::type polygamma(int n, T x, const Policy&); - - // Hypotenuse function sqrt(x ^ 2 + y ^ 2). - template - typename tools::promote_args::type - hypot(T1 x, T2 y); - - template - typename tools::promote_args::type - hypot(T1 x, T2 y, const Policy&); - - // cbrt - cube root. - template - typename tools::promote_args::type cbrt(RT z); - - template - typename tools::promote_args::type cbrt(RT z, const Policy&); - - // log1p is log(x + 1) - template - typename tools::promote_args::type log1p(T); - - template - typename tools::promote_args::type log1p(T, const Policy&); - - // log1pmx is log(x + 1) - x - template - typename tools::promote_args::type log1pmx(T); - - template - typename tools::promote_args::type log1pmx(T, const Policy&); - - // Exp (x) minus 1 functions. - template - typename tools::promote_args::type expm1(T); - - template - typename tools::promote_args::type expm1(T, const Policy&); - - // Power - 1 - template - typename tools::promote_args::type - powm1(const T1 a, const T2 z); - - template - typename tools::promote_args::type - powm1(const T1 a, const T2 z, const Policy&); - - // sqrt(1+x) - 1 - template - typename tools::promote_args::type sqrt1pm1(const T& val); - - template - typename tools::promote_args::type sqrt1pm1(const T& val, const Policy&); - - // sinus cardinals: - template - typename tools::promote_args::type sinc_pi(T x); - - template - typename tools::promote_args::type sinc_pi(T x, const Policy&); - - template - typename tools::promote_args::type sinhc_pi(T x); - - template - typename tools::promote_args::type sinhc_pi(T x, const Policy&); - - // inverse hyperbolics: - template - typename tools::promote_args::type asinh(T x); - - template - typename tools::promote_args::type asinh(T x, const Policy&); - - template - typename tools::promote_args::type acosh(T x); - - template - typename tools::promote_args::type acosh(T x, const Policy&); - - template - typename tools::promote_args::type atanh(T x); - - template - typename tools::promote_args::type atanh(T x, const Policy&); - - namespace detail{ - - typedef mpl::int_<0> bessel_no_int_tag; // No integer optimisation possible. - typedef mpl::int_<1> bessel_maybe_int_tag; // Maybe integer optimisation. - typedef mpl::int_<2> bessel_int_tag; // Definite integer optimistaion. - - template - struct bessel_traits - { - typedef typename mpl::if_< - is_integral, - typename tools::promote_args::type, - typename tools::promote_args::type - >::type result_type; - - typedef typename policies::precision::type precision_type; - - typedef typename mpl::if_< - mpl::or_< - mpl::less_equal >, - mpl::greater > >, - bessel_no_int_tag, - typename mpl::if_< - is_integral, - bessel_int_tag, - bessel_maybe_int_tag - >::type - >::type optimisation_tag; - }; - } // detail - - // Bessel functions: - template - typename detail::bessel_traits::result_type cyl_bessel_j(T1 v, T2 x, const Policy& pol); - template - typename detail::bessel_traits::result_type cyl_bessel_j_prime(T1 v, T2 x, const Policy& pol); - - template - typename detail::bessel_traits >::result_type cyl_bessel_j(T1 v, T2 x); - template - typename detail::bessel_traits >::result_type cyl_bessel_j_prime(T1 v, T2 x); - - template - typename detail::bessel_traits::result_type sph_bessel(unsigned v, T x, const Policy& pol); - template - typename detail::bessel_traits::result_type sph_bessel_prime(unsigned v, T x, const Policy& pol); - - template - typename detail::bessel_traits >::result_type sph_bessel(unsigned v, T x); - template - typename detail::bessel_traits >::result_type sph_bessel_prime(unsigned v, T x); - - template - typename detail::bessel_traits::result_type cyl_bessel_i(T1 v, T2 x, const Policy& pol); - template - typename detail::bessel_traits::result_type cyl_bessel_i_prime(T1 v, T2 x, const Policy& pol); - - template - typename detail::bessel_traits >::result_type cyl_bessel_i(T1 v, T2 x); - template - typename detail::bessel_traits >::result_type cyl_bessel_i_prime(T1 v, T2 x); - - template - typename detail::bessel_traits::result_type cyl_bessel_k(T1 v, T2 x, const Policy& pol); - template - typename detail::bessel_traits::result_type cyl_bessel_k_prime(T1 v, T2 x, const Policy& pol); - - template - typename detail::bessel_traits >::result_type cyl_bessel_k(T1 v, T2 x); - template - typename detail::bessel_traits >::result_type cyl_bessel_k_prime(T1 v, T2 x); - - template - typename detail::bessel_traits::result_type cyl_neumann(T1 v, T2 x, const Policy& pol); - template - typename detail::bessel_traits::result_type cyl_neumann_prime(T1 v, T2 x, const Policy& pol); - - template - typename detail::bessel_traits >::result_type cyl_neumann(T1 v, T2 x); - template - typename detail::bessel_traits >::result_type cyl_neumann_prime(T1 v, T2 x); - - template - typename detail::bessel_traits::result_type sph_neumann(unsigned v, T x, const Policy& pol); - template - typename detail::bessel_traits::result_type sph_neumann_prime(unsigned v, T x, const Policy& pol); - - template - typename detail::bessel_traits >::result_type sph_neumann(unsigned v, T x); - template - typename detail::bessel_traits >::result_type sph_neumann_prime(unsigned v, T x); - - template - typename detail::bessel_traits::result_type cyl_bessel_j_zero(T v, int m, const Policy& pol); - - template - typename detail::bessel_traits >::result_type cyl_bessel_j_zero(T v, int m); - - template - OutputIterator cyl_bessel_j_zero(T v, - int start_index, - unsigned number_of_zeros, - OutputIterator out_it); - - template - OutputIterator cyl_bessel_j_zero(T v, - int start_index, - unsigned number_of_zeros, - OutputIterator out_it, - const Policy&); - - template - typename detail::bessel_traits::result_type cyl_neumann_zero(T v, int m, const Policy& pol); - - template - typename detail::bessel_traits >::result_type cyl_neumann_zero(T v, int m); - - template - OutputIterator cyl_neumann_zero(T v, - int start_index, - unsigned number_of_zeros, - OutputIterator out_it); - - template - OutputIterator cyl_neumann_zero(T v, - int start_index, - unsigned number_of_zeros, - OutputIterator out_it, - const Policy&); - - template - std::complex >::result_type> cyl_hankel_1(T1 v, T2 x); - - template - std::complex::result_type> cyl_hankel_1(T1 v, T2 x, const Policy& pol); - - template - std::complex::result_type> cyl_hankel_2(T1 v, T2 x, const Policy& pol); - - template - std::complex >::result_type> cyl_hankel_2(T1 v, T2 x); - - template - std::complex::result_type> sph_hankel_1(T1 v, T2 x, const Policy& pol); - - template - std::complex >::result_type> sph_hankel_1(T1 v, T2 x); - - template - std::complex::result_type> sph_hankel_2(T1 v, T2 x, const Policy& pol); - - template - std::complex >::result_type> sph_hankel_2(T1 v, T2 x); - - template - typename tools::promote_args::type airy_ai(T x, const Policy&); - - template - typename tools::promote_args::type airy_ai(T x); - - template - typename tools::promote_args::type airy_bi(T x, const Policy&); - - template - typename tools::promote_args::type airy_bi(T x); - - template - typename tools::promote_args::type airy_ai_prime(T x, const Policy&); - - template - typename tools::promote_args::type airy_ai_prime(T x); - - template - typename tools::promote_args::type airy_bi_prime(T x, const Policy&); - - template - typename tools::promote_args::type airy_bi_prime(T x); - - template - T airy_ai_zero(int m); - template - T airy_ai_zero(int m, const Policy&); - - template - OutputIterator airy_ai_zero( - int start_index, - unsigned number_of_zeros, - OutputIterator out_it); - template - OutputIterator airy_ai_zero( - int start_index, - unsigned number_of_zeros, - OutputIterator out_it, - const Policy&); - - template - T airy_bi_zero(int m); - template - T airy_bi_zero(int m, const Policy&); - - template - OutputIterator airy_bi_zero( - int start_index, - unsigned number_of_zeros, - OutputIterator out_it); - template - OutputIterator airy_bi_zero( - int start_index, - unsigned number_of_zeros, - OutputIterator out_it, - const Policy&); - - template - typename tools::promote_args::type sin_pi(T x, const Policy&); - - template - typename tools::promote_args::type sin_pi(T x); - - template - typename tools::promote_args::type cos_pi(T x, const Policy&); - - template - typename tools::promote_args::type cos_pi(T x); - - template - int fpclassify BOOST_NO_MACRO_EXPAND(T t); - - template - bool isfinite BOOST_NO_MACRO_EXPAND(T z); - - template - bool isinf BOOST_NO_MACRO_EXPAND(T t); - - template - bool isnan BOOST_NO_MACRO_EXPAND(T t); - - template - bool isnormal BOOST_NO_MACRO_EXPAND(T t); - - template - int signbit BOOST_NO_MACRO_EXPAND(T x); - - template - int sign BOOST_NO_MACRO_EXPAND(const T& z); - - template - typename tools::promote_args_permissive::type copysign BOOST_NO_MACRO_EXPAND(const T& x, const U& y); - - template - typename tools::promote_args_permissive::type changesign BOOST_NO_MACRO_EXPAND(const T& z); - - // Exponential integrals: - namespace detail{ - - template - struct expint_result - { - typedef typename mpl::if_< - policies::is_policy, - typename tools::promote_args::type, - typename tools::promote_args::type - >::type type; - }; - - } // namespace detail - - template - typename tools::promote_args::type expint(unsigned n, T z, const Policy&); - - template - typename detail::expint_result::type expint(T const z, U const u); - - template - typename tools::promote_args::type expint(T z); - - // Zeta: - template - typename tools::promote_args::type zeta(T s, const Policy&); - - // Owen's T function: - template - typename tools::promote_args::type owens_t(T1 h, T2 a, const Policy& pol); - - template - typename tools::promote_args::type owens_t(T1 h, T2 a); - - // Jacobi Functions: - template - typename tools::promote_args::type jacobi_elliptic(T k, U theta, V* pcn, V* pdn, const Policy&); - - template - typename tools::promote_args::type jacobi_elliptic(T k, U theta, V* pcn = 0, V* pdn = 0); - - template - typename tools::promote_args::type jacobi_sn(U k, T theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_sn(U k, T theta); - - template - typename tools::promote_args::type jacobi_cn(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_cn(T k, U theta); - - template - typename tools::promote_args::type jacobi_dn(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_dn(T k, U theta); - - template - typename tools::promote_args::type jacobi_cd(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_cd(T k, U theta); - - template - typename tools::promote_args::type jacobi_dc(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_dc(T k, U theta); - - template - typename tools::promote_args::type jacobi_ns(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_ns(T k, U theta); - - template - typename tools::promote_args::type jacobi_sd(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_sd(T k, U theta); - - template - typename tools::promote_args::type jacobi_ds(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_ds(T k, U theta); - - template - typename tools::promote_args::type jacobi_nc(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_nc(T k, U theta); - - template - typename tools::promote_args::type jacobi_nd(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_nd(T k, U theta); - - template - typename tools::promote_args::type jacobi_sc(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_sc(T k, U theta); - - template - typename tools::promote_args::type jacobi_cs(T k, U theta, const Policy& pol); - - template - typename tools::promote_args::type jacobi_cs(T k, U theta); - - - template - typename tools::promote_args::type zeta(T s); - - // pow: - template - typename tools::promote_args::type pow(T base, const Policy& policy); - - template - typename tools::promote_args::type pow(T base); - - // next: - template - typename tools::promote_args::type nextafter(const T&, const U&, const Policy&); - template - typename tools::promote_args::type nextafter(const T&, const U&); - template - typename tools::promote_args::type float_next(const T&, const Policy&); - template - typename tools::promote_args::type float_next(const T&); - template - typename tools::promote_args::type float_prior(const T&, const Policy&); - template - typename tools::promote_args::type float_prior(const T&); - template - typename tools::promote_args::type float_distance(const T&, const U&, const Policy&); - template - typename tools::promote_args::type float_distance(const T&, const U&); - template - typename tools::promote_args::type float_advance(T val, int distance, const Policy& pol); - template - typename tools::promote_args::type float_advance(const T& val, int distance); - - template - typename tools::promote_args::type ulp(const T& val, const Policy& pol); - template - typename tools::promote_args::type ulp(const T& val); - - template - typename tools::promote_args::type relative_difference(const T&, const U&); - template - typename tools::promote_args::type epsilon_difference(const T&, const U&); -/* - template - T unchecked_bernoulli_b2n(const std::size_t n); - template - T bernoulli_b2n(const int i, const Policy &pol); - template - T bernoulli_b2n(const int i); - template - OutputIterator bernoulli_b2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it, - const Policy& pol); - template - OutputIterator bernoulli_b2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it); - template - T tangent_t2n(const int i, const Policy &pol); - template - T tangent_t2n(const int i); - template - OutputIterator tangent_t2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it, - const Policy& pol); - template - OutputIterator tangent_t2n(const int start_index, - const unsigned number_of_bernoullis_b2n, - OutputIterator out_it); -*/ - } // namespace math -} // namespace boost - -#ifdef BOOST_HAS_LONG_LONG -#define BOOST_MATH_DETAIL_LL_FUNC(Policy)\ - \ - template \ - inline T modf(const T& v, boost::long_long_type* ipart){ using boost::math::modf; return modf(v, ipart, Policy()); }\ - \ - template \ - inline boost::long_long_type lltrunc(const T& v){ using boost::math::lltrunc; return lltrunc(v, Policy()); }\ - \ - template \ - inline boost::long_long_type llround(const T& v){ using boost::math::llround; return llround(v, Policy()); }\ - -#else -#define BOOST_MATH_DETAIL_LL_FUNC(Policy) -#endif - -#define BOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(Policy)\ - \ - BOOST_MATH_DETAIL_LL_FUNC(Policy)\ - \ - template \ - inline typename boost::math::tools::promote_args::type \ - beta(RT1 a, RT2 b) { return ::boost::math::beta(a, b, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - beta(RT1 a, RT2 b, A x){ return ::boost::math::beta(a, b, x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - betac(RT1 a, RT2 b, RT3 x) { return ::boost::math::betac(a, b, x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibeta(RT1 a, RT2 b, RT3 x){ return ::boost::math::ibeta(a, b, x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibetac(RT1 a, RT2 b, RT3 x){ return ::boost::math::ibetac(a, b, x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibeta_inv(T1 a, T2 b, T3 p, T4* py){ return ::boost::math::ibeta_inv(a, b, p, py, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibeta_inv(RT1 a, RT2 b, RT3 p){ return ::boost::math::ibeta_inv(a, b, p, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibetac_inv(T1 a, T2 b, T3 q, T4* py){ return ::boost::math::ibetac_inv(a, b, q, py, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibeta_inva(RT1 a, RT2 b, RT3 p){ return ::boost::math::ibeta_inva(a, b, p, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibetac_inva(T1 a, T2 b, T3 q){ return ::boost::math::ibetac_inva(a, b, q, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibeta_invb(RT1 a, RT2 b, RT3 p){ return ::boost::math::ibeta_invb(a, b, p, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibetac_invb(T1 a, T2 b, T3 q){ return ::boost::math::ibetac_invb(a, b, q, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibetac_inv(RT1 a, RT2 b, RT3 q){ return ::boost::math::ibetac_inv(a, b, q, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ibeta_derivative(RT1 a, RT2 b, RT3 x){ return ::boost::math::ibeta_derivative(a, b, x, Policy()); }\ -\ - template T binomial_coefficient(unsigned n, unsigned k){ return ::boost::math::binomial_coefficient(n, k, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type erf(RT z) { return ::boost::math::erf(z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type erfc(RT z){ return ::boost::math::erfc(z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type erf_inv(RT z) { return ::boost::math::erf_inv(z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type erfc_inv(RT z){ return ::boost::math::erfc_inv(z, Policy()); }\ -\ - using boost::math::legendre_next;\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - legendre_p(int l, T x){ return ::boost::math::legendre_p(l, x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - legendre_q(unsigned l, T x){ return ::boost::math::legendre_q(l, x, Policy()); }\ -\ - using ::boost::math::legendre_next;\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - legendre_p(int l, int m, T x){ return ::boost::math::legendre_p(l, m, x, Policy()); }\ -\ - using ::boost::math::laguerre_next;\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - laguerre(unsigned n, T x){ return ::boost::math::laguerre(n, x, Policy()); }\ -\ - template \ - inline typename boost::math::laguerre_result::type \ - laguerre(unsigned n, T1 m, T2 x) { return ::boost::math::laguerre(n, m, x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - hermite(unsigned n, T x){ return ::boost::math::hermite(n, x, Policy()); }\ -\ - using boost::math::hermite_next;\ -\ - template \ - inline std::complex::type> \ - spherical_harmonic(unsigned n, int m, T1 theta, T2 phi){ return boost::math::spherical_harmonic(n, m, theta, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - spherical_harmonic_r(unsigned n, int m, T1 theta, T2 phi){ return ::boost::math::spherical_harmonic_r(n, m, theta, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi){ return boost::math::spherical_harmonic_i(n, m, theta, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - spherical_harmonic_i(unsigned n, int m, T1 theta, T2 phi, const Policy& pol);\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ellint_rf(T1 x, T2 y, T3 z){ return ::boost::math::ellint_rf(x, y, z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ellint_rd(T1 x, T2 y, T3 z){ return ::boost::math::ellint_rd(x, y, z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ellint_rc(T1 x, T2 y){ return ::boost::math::ellint_rc(x, y, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ellint_rj(T1 x, T2 y, T3 z, T4 p){ return boost::math::ellint_rj(x, y, z, p, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - ellint_rg(T1 x, T2 y, T3 z){ return ::boost::math::ellint_rg(x, y, z, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type ellint_2(T k){ return boost::math::ellint_2(k, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type ellint_2(T1 k, T2 phi){ return boost::math::ellint_2(k, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type ellint_d(T k){ return boost::math::ellint_d(k, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type ellint_d(T1 k, T2 phi){ return boost::math::ellint_d(k, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type jacobi_zeta(T1 k, T2 phi){ return boost::math::jacobi_zeta(k, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type heuman_lambda(T1 k, T2 phi){ return boost::math::heuman_lambda(k, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type ellint_1(T k){ return boost::math::ellint_1(k, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type ellint_1(T1 k, T2 phi){ return boost::math::ellint_1(k, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type ellint_3(T1 k, T2 v, T3 phi){ return boost::math::ellint_3(k, v, phi, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type ellint_3(T1 k, T2 v){ return boost::math::ellint_3(k, v, Policy()); }\ -\ - using boost::math::max_factorial;\ - template \ - inline RT factorial(unsigned int i) { return boost::math::factorial(i, Policy()); }\ - using boost::math::unchecked_factorial;\ - template \ - inline RT double_factorial(unsigned i){ return boost::math::double_factorial(i, Policy()); }\ - template \ - inline typename boost::math::tools::promote_args::type falling_factorial(RT x, unsigned n){ return boost::math::falling_factorial(x, n, Policy()); }\ - template \ - inline typename boost::math::tools::promote_args::type rising_factorial(RT x, unsigned n){ return boost::math::rising_factorial(x, n, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type tgamma(RT z){ return boost::math::tgamma(z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type tgamma1pm1(RT z){ return boost::math::tgamma1pm1(z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type tgamma(RT1 a, RT2 z){ return boost::math::tgamma(a, z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type lgamma(RT z, int* sign){ return boost::math::lgamma(z, sign, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type lgamma(RT x){ return boost::math::lgamma(x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type tgamma_lower(RT1 a, RT2 z){ return boost::math::tgamma_lower(a, z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type gamma_q(RT1 a, RT2 z){ return boost::math::gamma_q(a, z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type gamma_p(RT1 a, RT2 z){ return boost::math::gamma_p(a, z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type tgamma_delta_ratio(T1 z, T2 delta){ return boost::math::tgamma_delta_ratio(z, delta, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type tgamma_ratio(T1 a, T2 b) { return boost::math::tgamma_ratio(a, b, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type gamma_p_derivative(T1 a, T2 x){ return boost::math::gamma_p_derivative(a, x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type gamma_p_inv(T1 a, T2 p){ return boost::math::gamma_p_inv(a, p, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type gamma_p_inva(T1 a, T2 p){ return boost::math::gamma_p_inva(a, p, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type gamma_q_inv(T1 a, T2 q){ return boost::math::gamma_q_inv(a, q, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type gamma_q_inva(T1 a, T2 q){ return boost::math::gamma_q_inva(a, q, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type digamma(T x){ return boost::math::digamma(x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type trigamma(T x){ return boost::math::trigamma(x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type polygamma(int n, T x){ return boost::math::polygamma(n, x, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type \ - hypot(T1 x, T2 y){ return boost::math::hypot(x, y, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type cbrt(RT z){ return boost::math::cbrt(z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type log1p(T x){ return boost::math::log1p(x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type log1pmx(T x){ return boost::math::log1pmx(x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type expm1(T x){ return boost::math::expm1(x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type \ - powm1(const T1 a, const T2 z){ return boost::math::powm1(a, z, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type sqrt1pm1(const T& val){ return boost::math::sqrt1pm1(val, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type sinc_pi(T x){ return boost::math::sinc_pi(x, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type sinhc_pi(T x){ return boost::math::sinhc_pi(x, Policy()); }\ -\ - template\ - inline typename boost::math::tools::promote_args::type asinh(const T x){ return boost::math::asinh(x, Policy()); }\ -\ - template\ - inline typename boost::math::tools::promote_args::type acosh(const T x){ return boost::math::acosh(x, Policy()); }\ -\ - template\ - inline typename boost::math::tools::promote_args::type atanh(const T x){ return boost::math::atanh(x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type cyl_bessel_j(T1 v, T2 x)\ - { return boost::math::cyl_bessel_j(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type cyl_bessel_j_prime(T1 v, T2 x)\ - { return boost::math::cyl_bessel_j_prime(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type sph_bessel(unsigned v, T x)\ - { return boost::math::sph_bessel(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type sph_bessel_prime(unsigned v, T x)\ - { return boost::math::sph_bessel_prime(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type \ - cyl_bessel_i(T1 v, T2 x) { return boost::math::cyl_bessel_i(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type \ - cyl_bessel_i_prime(T1 v, T2 x) { return boost::math::cyl_bessel_i_prime(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type \ - cyl_bessel_k(T1 v, T2 x) { return boost::math::cyl_bessel_k(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type \ - cyl_bessel_k_prime(T1 v, T2 x) { return boost::math::cyl_bessel_k_prime(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type \ - cyl_neumann(T1 v, T2 x){ return boost::math::cyl_neumann(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type \ - cyl_neumann_prime(T1 v, T2 x){ return boost::math::cyl_neumann_prime(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type \ - sph_neumann(unsigned v, T x){ return boost::math::sph_neumann(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type \ - sph_neumann_prime(unsigned v, T x){ return boost::math::sph_neumann_prime(v, x, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type cyl_bessel_j_zero(T v, int m)\ - { return boost::math::cyl_bessel_j_zero(v, m, Policy()); }\ -\ -template \ - inline void cyl_bessel_j_zero(T v,\ - int start_index,\ - unsigned number_of_zeros,\ - OutputIterator out_it)\ - { boost::math::cyl_bessel_j_zero(v, start_index, number_of_zeros, out_it, Policy()); }\ -\ - template \ - inline typename boost::math::detail::bessel_traits::result_type cyl_neumann_zero(T v, int m)\ - { return boost::math::cyl_neumann_zero(v, m, Policy()); }\ -\ -template \ - inline void cyl_neumann_zero(T v,\ - int start_index,\ - unsigned number_of_zeros,\ - OutputIterator out_it)\ - { boost::math::cyl_neumann_zero(v, start_index, number_of_zeros, out_it, Policy()); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type sin_pi(T x){ return boost::math::sin_pi(x); }\ -\ - template \ - inline typename boost::math::tools::promote_args::type cos_pi(T x){ return boost::math::cos_pi(x); }\ -\ - using boost::math::fpclassify;\ - using boost::math::isfinite;\ - using boost::math::isinf;\ - using boost::math::isnan;\ - using boost::math::isnormal;\ - using boost::math::signbit;\ - using boost::math::sign;\ - using boost::math::copysign;\ - using boost::math::changesign;\ - \ - template \ - inline typename boost::math::tools::promote_args::type expint(T const& z, U const& u)\ - { return boost::math::expint(z, u, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type expint(T z){ return boost::math::expint(z, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type zeta(T s){ return boost::math::zeta(s, Policy()); }\ - \ - template \ - inline T round(const T& v){ using boost::math::round; return round(v, Policy()); }\ - \ - template \ - inline int iround(const T& v){ using boost::math::iround; return iround(v, Policy()); }\ - \ - template \ - inline long lround(const T& v){ using boost::math::lround; return lround(v, Policy()); }\ - \ - template \ - inline T trunc(const T& v){ using boost::math::trunc; return trunc(v, Policy()); }\ - \ - template \ - inline int itrunc(const T& v){ using boost::math::itrunc; return itrunc(v, Policy()); }\ - \ - template \ - inline long ltrunc(const T& v){ using boost::math::ltrunc; return ltrunc(v, Policy()); }\ - \ - template \ - inline T modf(const T& v, T* ipart){ using boost::math::modf; return modf(v, ipart, Policy()); }\ - \ - template \ - inline T modf(const T& v, int* ipart){ using boost::math::modf; return modf(v, ipart, Policy()); }\ - \ - template \ - inline T modf(const T& v, long* ipart){ using boost::math::modf; return modf(v, ipart, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type pow(T v){ return boost::math::pow(v, Policy()); }\ - \ - template T nextafter(const T& a, const T& b){ return boost::math::nextafter(a, b, Policy()); }\ - template T float_next(const T& a){ return boost::math::float_next(a, Policy()); }\ - template T float_prior(const T& a){ return boost::math::float_prior(a, Policy()); }\ - template T float_distance(const T& a, const T& b){ return boost::math::float_distance(a, b, Policy()); }\ - template T ulp(const T& a){ return boost::math::ulp(a, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type owens_t(RT1 a, RT2 z){ return boost::math::owens_t(a, z, Policy()); }\ - \ - template \ - inline std::complex::result_type> cyl_hankel_1(T1 v, T2 x)\ - { return boost::math::cyl_hankel_1(v, x, Policy()); }\ - \ - template \ - inline std::complex::result_type> cyl_hankel_2(T1 v, T2 x)\ - { return boost::math::cyl_hankel_2(v, x, Policy()); }\ - \ - template \ - inline std::complex::result_type> sph_hankel_1(T1 v, T2 x)\ - { return boost::math::sph_hankel_1(v, x, Policy()); }\ - \ - template \ - inline std::complex::result_type> sph_hankel_2(T1 v, T2 x)\ - { return boost::math::sph_hankel_2(v, x, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_elliptic(T k, T theta, T* pcn, T* pdn)\ - { return boost::math::jacobi_elliptic(k, theta, pcn, pdn, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_sn(U k, T theta)\ - { return boost::math::jacobi_sn(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_cn(T k, U theta)\ - { return boost::math::jacobi_cn(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_dn(T k, U theta)\ - { return boost::math::jacobi_dn(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_cd(T k, U theta)\ - { return boost::math::jacobi_cd(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_dc(T k, U theta)\ - { return boost::math::jacobi_dc(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_ns(T k, U theta)\ - { return boost::math::jacobi_ns(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_sd(T k, U theta)\ - { return boost::math::jacobi_sd(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_ds(T k, U theta)\ - { return boost::math::jacobi_ds(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_nc(T k, U theta)\ - { return boost::math::jacobi_nc(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_nd(T k, U theta)\ - { return boost::math::jacobi_nd(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_sc(T k, U theta)\ - { return boost::math::jacobi_sc(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type jacobi_cs(T k, U theta)\ - { return boost::math::jacobi_cs(k, theta, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type airy_ai(T x)\ - { return boost::math::airy_ai(x, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type airy_bi(T x)\ - { return boost::math::airy_bi(x, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type airy_ai_prime(T x)\ - { return boost::math::airy_ai_prime(x, Policy()); }\ - \ - template \ - inline typename boost::math::tools::promote_args::type airy_bi_prime(T x)\ - { return boost::math::airy_bi_prime(x, Policy()); }\ - \ - template \ - inline T airy_ai_zero(int m)\ - { return boost::math::airy_ai_zero(m, Policy()); }\ - template \ - OutputIterator airy_ai_zero(int start_index, unsigned number_of_zeros, OutputIterator out_it)\ - { return boost::math::airy_ai_zero(start_index, number_of_zeros, out_it, Policy()); }\ - \ - template \ - inline T airy_bi_zero(int m)\ - { return boost::math::airy_bi_zero(m, Policy()); }\ - template \ - OutputIterator airy_bi_zero(int start_index, unsigned number_of_zeros, OutputIterator out_it)\ - { return boost::math::airy_bi_zero(start_index, number_of_zeros, out_it, Policy()); }\ - \ - template \ - T bernoulli_b2n(const int i)\ - { return boost::math::bernoulli_b2n(i, Policy()); }\ - template \ - OutputIterator bernoulli_b2n(int start_index, unsigned number_of_bernoullis_b2n, OutputIterator out_it)\ - { return boost::math::bernoulli_b2n(start_index, number_of_bernoullis_b2n, out_it, Policy()); }\ - \ - template \ - T tangent_t2n(const int i)\ - { return boost::math::tangent_t2n(i, Policy()); }\ - template \ - OutputIterator tangent_t2n(int start_index, unsigned number_of_bernoullis_b2n, OutputIterator out_it)\ - { return boost::math::tangent_t2n(start_index, number_of_bernoullis_b2n, out_it, Policy()); }\ - \ - - - - - -#endif // BOOST_MATH_SPECIAL_MATH_FWD_HPP - - diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/policy.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/policy.hpp deleted file mode 100644 index bef8aaf1f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/policy.hpp +++ /dev/null @@ -1,1045 +0,0 @@ -// Copyright John Maddock 2007. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#ifndef BOOST_MATH_POLICY_HPP -#define BOOST_MATH_POLICY_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -//#include -//#include -#include -// Sadly we do need the .h versions of these to be sure of getting -// FLT_MANT_DIG etc. -#include -#include -#include -#include - -namespace boost{ namespace math{ - -namespace tools{ - -template -BOOST_MATH_CONSTEXPR int digits(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_NOEXCEPT; -template -BOOST_MATH_CONSTEXPR T epsilon(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T); - -} // Namespace tools - -namespace policies{ - -// -// Define macros for our default policies, if they're not defined already: -// -// Special cases for exceptions disabled first: -// -#ifdef BOOST_NO_EXCEPTIONS -# ifndef BOOST_MATH_DOMAIN_ERROR_POLICY -# define BOOST_MATH_DOMAIN_ERROR_POLICY errno_on_error -# endif -# ifndef BOOST_MATH_POLE_ERROR_POLICY -# define BOOST_MATH_POLE_ERROR_POLICY errno_on_error -# endif -# ifndef BOOST_MATH_OVERFLOW_ERROR_POLICY -# define BOOST_MATH_OVERFLOW_ERROR_POLICY errno_on_error -# endif -# ifndef BOOST_MATH_EVALUATION_ERROR_POLICY -# define BOOST_MATH_EVALUATION_ERROR_POLICY errno_on_error -# endif -# ifndef BOOST_MATH_ROUNDING_ERROR_POLICY -# define BOOST_MATH_ROUNDING_ERROR_POLICY errno_on_error -# endif -#endif -// -// Then the regular cases: -// -#ifndef BOOST_MATH_DOMAIN_ERROR_POLICY -#define BOOST_MATH_DOMAIN_ERROR_POLICY throw_on_error -#endif -#ifndef BOOST_MATH_POLE_ERROR_POLICY -#define BOOST_MATH_POLE_ERROR_POLICY throw_on_error -#endif -#ifndef BOOST_MATH_OVERFLOW_ERROR_POLICY -#define BOOST_MATH_OVERFLOW_ERROR_POLICY throw_on_error -#endif -#ifndef BOOST_MATH_EVALUATION_ERROR_POLICY -#define BOOST_MATH_EVALUATION_ERROR_POLICY throw_on_error -#endif -#ifndef BOOST_MATH_ROUNDING_ERROR_POLICY -#define BOOST_MATH_ROUNDING_ERROR_POLICY throw_on_error -#endif -#ifndef BOOST_MATH_UNDERFLOW_ERROR_POLICY -#define BOOST_MATH_UNDERFLOW_ERROR_POLICY ignore_error -#endif -#ifndef BOOST_MATH_DENORM_ERROR_POLICY -#define BOOST_MATH_DENORM_ERROR_POLICY ignore_error -#endif -#ifndef BOOST_MATH_INDETERMINATE_RESULT_ERROR_POLICY -#define BOOST_MATH_INDETERMINATE_RESULT_ERROR_POLICY ignore_error -#endif -#ifndef BOOST_MATH_DIGITS10_POLICY -#define BOOST_MATH_DIGITS10_POLICY 0 -#endif -#ifndef BOOST_MATH_PROMOTE_FLOAT_POLICY -#define BOOST_MATH_PROMOTE_FLOAT_POLICY true -#endif -#ifndef BOOST_MATH_PROMOTE_DOUBLE_POLICY -#ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS -#define BOOST_MATH_PROMOTE_DOUBLE_POLICY false -#else -#define BOOST_MATH_PROMOTE_DOUBLE_POLICY true -#endif -#endif -#ifndef BOOST_MATH_DISCRETE_QUANTILE_POLICY -#define BOOST_MATH_DISCRETE_QUANTILE_POLICY integer_round_outwards -#endif -#ifndef BOOST_MATH_ASSERT_UNDEFINED_POLICY -#define BOOST_MATH_ASSERT_UNDEFINED_POLICY true -#endif -#ifndef BOOST_MATH_MAX_SERIES_ITERATION_POLICY -#define BOOST_MATH_MAX_SERIES_ITERATION_POLICY 1000000 -#endif -#ifndef BOOST_MATH_MAX_ROOT_ITERATION_POLICY -#define BOOST_MATH_MAX_ROOT_ITERATION_POLICY 200 -#endif - -#if !defined(__BORLANDC__) -#define BOOST_MATH_META_INT(type, name, Default)\ - template struct name : public boost::mpl::int_{};\ - namespace detail{\ - template \ - char test_is_valid_arg(const name*);\ - char test_is_default_arg(const name*);\ - template struct is_##name##_imp\ - {\ - template static char test(const name*);\ - static double test(...);\ - BOOST_STATIC_CONSTANT(bool, value = sizeof(test(static_cast(0))) == 1);\ - };\ - }\ - template struct is_##name : public boost::mpl::bool_< ::boost::math::policies::detail::is_##name##_imp::value>{}; - -#define BOOST_MATH_META_BOOL(name, Default)\ - template struct name : public boost::mpl::bool_{};\ - namespace detail{\ - template \ - char test_is_valid_arg(const name*);\ - char test_is_default_arg(const name*);\ - template struct is_##name##_imp\ - {\ - template static char test(const name*);\ - static double test(...);\ - BOOST_STATIC_CONSTANT(bool, value = sizeof(test(static_cast(0))) == 1);\ - };\ - }\ - template struct is_##name : public boost::mpl::bool_< ::boost::math::policies::detail::is_##name##_imp::value>{}; -#else -#define BOOST_MATH_META_INT(Type, name, Default)\ - template struct name : public boost::mpl::int_{};\ - namespace detail{\ - template \ - char test_is_valid_arg(const name*);\ - char test_is_default_arg(const name*);\ - template struct is_##name##_tester\ - {\ - template static char test(const name&);\ - static double test(...);\ - };\ - template struct is_##name##_imp\ - {\ - static T inst;\ - BOOST_STATIC_CONSTANT(bool, value = sizeof( ::boost::math::policies::detail::is_##name##_tester::test(inst)) == 1);\ - };\ - }\ - template struct is_##name : public boost::mpl::bool_< ::boost::math::policies::detail::is_##name##_imp::value>\ - {\ - template struct apply{ typedef is_##name type; };\ - }; - -#define BOOST_MATH_META_BOOL(name, Default)\ - template struct name : public boost::mpl::bool_{};\ - namespace detail{\ - template \ - char test_is_valid_arg(const name*);\ - char test_is_default_arg(const name*);\ - template struct is_##name##_tester\ - {\ - template static char test(const name&);\ - static double test(...);\ - };\ - template struct is_##name##_imp\ - {\ - static T inst;\ - BOOST_STATIC_CONSTANT(bool, value = sizeof( ::boost::math::policies::detail::is_##name##_tester::test(inst)) == 1);\ - };\ - }\ - template struct is_##name : public boost::mpl::bool_< ::boost::math::policies::detail::is_##name##_imp::value>\ - {\ - template struct apply{ typedef is_##name type; };\ - }; -#endif -// -// Begin by defining policy types for error handling: -// -enum error_policy_type -{ - throw_on_error = 0, - errno_on_error = 1, - ignore_error = 2, - user_error = 3 -}; - -BOOST_MATH_META_INT(error_policy_type, domain_error, BOOST_MATH_DOMAIN_ERROR_POLICY) -BOOST_MATH_META_INT(error_policy_type, pole_error, BOOST_MATH_POLE_ERROR_POLICY) -BOOST_MATH_META_INT(error_policy_type, overflow_error, BOOST_MATH_OVERFLOW_ERROR_POLICY) -BOOST_MATH_META_INT(error_policy_type, underflow_error, BOOST_MATH_UNDERFLOW_ERROR_POLICY) -BOOST_MATH_META_INT(error_policy_type, denorm_error, BOOST_MATH_DENORM_ERROR_POLICY) -BOOST_MATH_META_INT(error_policy_type, evaluation_error, BOOST_MATH_EVALUATION_ERROR_POLICY) -BOOST_MATH_META_INT(error_policy_type, rounding_error, BOOST_MATH_ROUNDING_ERROR_POLICY) -BOOST_MATH_META_INT(error_policy_type, indeterminate_result_error, BOOST_MATH_INDETERMINATE_RESULT_ERROR_POLICY) - -// -// Policy types for internal promotion: -// -BOOST_MATH_META_BOOL(promote_float, BOOST_MATH_PROMOTE_FLOAT_POLICY) -BOOST_MATH_META_BOOL(promote_double, BOOST_MATH_PROMOTE_DOUBLE_POLICY) -BOOST_MATH_META_BOOL(assert_undefined, BOOST_MATH_ASSERT_UNDEFINED_POLICY) -// -// Policy types for discrete quantiles: -// -enum discrete_quantile_policy_type -{ - real, - integer_round_outwards, - integer_round_inwards, - integer_round_down, - integer_round_up, - integer_round_nearest -}; - -BOOST_MATH_META_INT(discrete_quantile_policy_type, discrete_quantile, BOOST_MATH_DISCRETE_QUANTILE_POLICY) -// -// Precision: -// -BOOST_MATH_META_INT(int, digits10, BOOST_MATH_DIGITS10_POLICY) -BOOST_MATH_META_INT(int, digits2, 0) -// -// Iterations: -// -BOOST_MATH_META_INT(unsigned long, max_series_iterations, BOOST_MATH_MAX_SERIES_ITERATION_POLICY) -BOOST_MATH_META_INT(unsigned long, max_root_iterations, BOOST_MATH_MAX_ROOT_ITERATION_POLICY) -// -// Define the names for each possible policy: -// -#define BOOST_MATH_PARAMETER(name)\ - BOOST_PARAMETER_TEMPLATE_KEYWORD(name##_name)\ - BOOST_PARAMETER_NAME(name##_name) - -struct default_policy{}; - -namespace detail{ -// -// Trait to work out bits precision from digits10 and digits2: -// -template -struct precision -{ - // - // Now work out the precision: - // - typedef typename mpl::if_c< - (Digits10::value == 0), - digits2<0>, - digits2<((Digits10::value + 1) * 1000L) / 301L> - >::type digits2_type; -public: -#ifdef __BORLANDC__ - typedef typename mpl::if_c< - (Digits2::value > ::boost::math::policies::detail::precision::digits2_type::value), - Digits2, digits2_type>::type type; -#else - typedef typename mpl::if_c< - (Digits2::value > digits2_type::value), - Digits2, digits2_type>::type type; -#endif -}; - -template -struct select_result -{ - typedef A type; -}; -template -struct select_result -{ - typedef typename mpl::deref::type type; -}; - -template -struct find_arg -{ -private: - typedef typename mpl::find_if::type iter; - typedef typename mpl::end::type end_type; -public: - typedef typename select_result< - DefaultType, iter, - ::boost::is_same::value>::type type; -}; - -double test_is_valid_arg(...); -double test_is_default_arg(...); -char test_is_valid_arg(const default_policy*); -char test_is_default_arg(const default_policy*); - -template -struct is_valid_policy_imp -{ - BOOST_STATIC_CONSTANT(bool, value = sizeof(::boost::math::policies::detail::test_is_valid_arg(static_cast(0))) == 1); -}; - -template -struct is_default_policy_imp -{ - BOOST_STATIC_CONSTANT(bool, value = sizeof(::boost::math::policies::detail::test_is_default_arg(static_cast(0))) == 1); -}; - -template struct is_valid_policy -: public mpl::bool_< - ::boost::math::policies::detail::is_valid_policy_imp::value> -{}; - -template struct is_default_policy -: public mpl::bool_< - ::boost::math::policies::detail::is_default_policy_imp::value> -{ - template - struct apply - { - typedef is_default_policy type; - }; -}; - -template -struct append_N -{ - typedef typename mpl::push_back::type new_seq; - typedef typename append_N::type type; -}; - -template -struct append_N -{ - typedef Seq type; -}; - -// -// Traits class to work out what template parameters our default -// policy<> class will have when modified for forwarding: -// -template -struct default_args -{ - typedef promote_float arg1; - typedef promote_double arg2; -}; - -template <> -struct default_args -{ - typedef default_policy arg1; - typedef default_policy arg2; -}; - -template <> -struct default_args -{ - typedef promote_float arg1; - typedef default_policy arg2; -}; - -template <> -struct default_args -{ - typedef promote_double arg1; - typedef default_policy arg2; -}; - -typedef default_args::arg1 forwarding_arg1; -typedef default_args::arg2 forwarding_arg2; - -} // detail -// -// Now define the policy type with enough arguments to handle all -// the policies: -// -template -struct policy -{ -private: - // - // Validate all our arguments: - // - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - BOOST_STATIC_ASSERT(::boost::math::policies::detail::is_valid_policy::value); - // - // Typelist of the arguments: - // - typedef mpl::list arg_list; - -public: - typedef typename detail::find_arg, domain_error<> >::type domain_error_type; - typedef typename detail::find_arg, pole_error<> >::type pole_error_type; - typedef typename detail::find_arg, overflow_error<> >::type overflow_error_type; - typedef typename detail::find_arg, underflow_error<> >::type underflow_error_type; - typedef typename detail::find_arg, denorm_error<> >::type denorm_error_type; - typedef typename detail::find_arg, evaluation_error<> >::type evaluation_error_type; - typedef typename detail::find_arg, rounding_error<> >::type rounding_error_type; - typedef typename detail::find_arg, indeterminate_result_error<> >::type indeterminate_result_error_type; -private: - // - // Now work out the precision: - // - typedef typename detail::find_arg, digits10<> >::type digits10_type; - typedef typename detail::find_arg, digits2<> >::type bits_precision_type; -public: - typedef typename detail::precision::type precision_type; - // - // Internal promotion: - // - typedef typename detail::find_arg, promote_float<> >::type promote_float_type; - typedef typename detail::find_arg, promote_double<> >::type promote_double_type; - // - // Discrete quantiles: - // - typedef typename detail::find_arg, discrete_quantile<> >::type discrete_quantile_type; - // - // Mathematically undefined properties: - // - typedef typename detail::find_arg, assert_undefined<> >::type assert_undefined_type; - // - // Max iterations: - // - typedef typename detail::find_arg, max_series_iterations<> >::type max_series_iterations_type; - typedef typename detail::find_arg, max_root_iterations<> >::type max_root_iterations_type; -}; -// -// These full specializations are defined to reduce the amount of -// template instantiations that have to take place when using the default -// policies, they have quite a large impact on compile times: -// -template <> -struct policy -{ -public: - typedef domain_error<> domain_error_type; - typedef pole_error<> pole_error_type; - typedef overflow_error<> overflow_error_type; - typedef underflow_error<> underflow_error_type; - typedef denorm_error<> denorm_error_type; - typedef evaluation_error<> evaluation_error_type; - typedef rounding_error<> rounding_error_type; - typedef indeterminate_result_error<> indeterminate_result_error_type; -#if BOOST_MATH_DIGITS10_POLICY == 0 - typedef digits2<> precision_type; -#else - typedef detail::precision, digits2<> >::type precision_type; -#endif - typedef promote_float<> promote_float_type; - typedef promote_double<> promote_double_type; - typedef discrete_quantile<> discrete_quantile_type; - typedef assert_undefined<> assert_undefined_type; - typedef max_series_iterations<> max_series_iterations_type; - typedef max_root_iterations<> max_root_iterations_type; -}; - -template <> -struct policy -{ -public: - typedef domain_error<> domain_error_type; - typedef pole_error<> pole_error_type; - typedef overflow_error<> overflow_error_type; - typedef underflow_error<> underflow_error_type; - typedef denorm_error<> denorm_error_type; - typedef evaluation_error<> evaluation_error_type; - typedef rounding_error<> rounding_error_type; - typedef indeterminate_result_error<> indeterminate_result_error_type; -#if BOOST_MATH_DIGITS10_POLICY == 0 - typedef digits2<> precision_type; -#else - typedef detail::precision, digits2<> >::type precision_type; -#endif - typedef promote_float promote_float_type; - typedef promote_double promote_double_type; - typedef discrete_quantile<> discrete_quantile_type; - typedef assert_undefined<> assert_undefined_type; - typedef max_series_iterations<> max_series_iterations_type; - typedef max_root_iterations<> max_root_iterations_type; -}; - -template -struct normalise -{ -private: - typedef mpl::list arg_list; - typedef typename detail::find_arg, typename Policy::domain_error_type >::type domain_error_type; - typedef typename detail::find_arg, typename Policy::pole_error_type >::type pole_error_type; - typedef typename detail::find_arg, typename Policy::overflow_error_type >::type overflow_error_type; - typedef typename detail::find_arg, typename Policy::underflow_error_type >::type underflow_error_type; - typedef typename detail::find_arg, typename Policy::denorm_error_type >::type denorm_error_type; - typedef typename detail::find_arg, typename Policy::evaluation_error_type >::type evaluation_error_type; - typedef typename detail::find_arg, typename Policy::rounding_error_type >::type rounding_error_type; - typedef typename detail::find_arg, typename Policy::indeterminate_result_error_type >::type indeterminate_result_error_type; - // - // Now work out the precision: - // - typedef typename detail::find_arg, digits10<> >::type digits10_type; - typedef typename detail::find_arg, typename Policy::precision_type >::type bits_precision_type; - typedef typename detail::precision::type precision_type; - // - // Internal promotion: - // - typedef typename detail::find_arg, typename Policy::promote_float_type >::type promote_float_type; - typedef typename detail::find_arg, typename Policy::promote_double_type >::type promote_double_type; - // - // Discrete quantiles: - // - typedef typename detail::find_arg, typename Policy::discrete_quantile_type >::type discrete_quantile_type; - // - // Mathematically undefined properties: - // - typedef typename detail::find_arg, typename Policy::assert_undefined_type >::type assert_undefined_type; - // - // Max iterations: - // - typedef typename detail::find_arg, typename Policy::max_series_iterations_type>::type max_series_iterations_type; - typedef typename detail::find_arg, typename Policy::max_root_iterations_type>::type max_root_iterations_type; - // - // Define a typelist of the policies: - // - typedef mpl::vector< - domain_error_type, - pole_error_type, - overflow_error_type, - underflow_error_type, - denorm_error_type, - evaluation_error_type, - rounding_error_type, - indeterminate_result_error_type, - precision_type, - promote_float_type, - promote_double_type, - discrete_quantile_type, - assert_undefined_type, - max_series_iterations_type, - max_root_iterations_type> result_list; - // - // Remove all the policies that are the same as the default: - // - typedef typename mpl::remove_if >::type reduced_list; - // - // Pad out the list with defaults: - // - typedef typename detail::append_N::value)>::type result_type; -public: - typedef policy< - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type, - typename mpl::at >::type > type; -}; -// -// Full specialisation to speed up compilation of the common case: -// -template <> -struct normalise, - promote_float, - promote_double, - discrete_quantile<>, - assert_undefined<>, - default_policy, - default_policy, - default_policy, - default_policy, - default_policy, - default_policy, - default_policy> -{ - typedef policy type; -}; - -template <> -struct normalise, - promote_float, - promote_double, - discrete_quantile<>, - assert_undefined<>, - default_policy, - default_policy, - default_policy, - default_policy, - default_policy, - default_policy, - default_policy> -{ - typedef policy type; -}; - -inline BOOST_MATH_CONSTEXPR policy<> make_policy() BOOST_NOEXCEPT -{ return policy<>(); } - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1>::type make_policy(const A1&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2>::type make_policy(const A1&, const A2&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3>::type make_policy(const A1&, const A2&, const A3&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3, A4>::type make_policy(const A1&, const A2&, const A3&, const A4&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3, A4>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3, A4, A5>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3, A4, A5>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3, A4, A5, A6>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3, A4, A5, A6>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3, A4, A5, A6, A7>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3, A4, A5, A6, A7>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3, A4, A5, A6, A7, A8>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&, const A8&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3, A4, A5, A6, A7, A8>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3, A4, A5, A6, A7, A8, A9>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&, const A8&, const A9&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3, A4, A5, A6, A7, A8, A9>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&, const A8&, const A9&, const A10&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>::type result_type; - return result_type(); -} - -template -inline BOOST_MATH_CONSTEXPR typename normalise, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&, const A7&, const A8&, const A9&, const A10&, const A11&) BOOST_NOEXCEPT -{ - typedef typename normalise, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11>::type result_type; - return result_type(); -} - -// -// Traits class to handle internal promotion: -// -template -struct evaluation -{ - typedef Real type; -}; - -template -struct evaluation -{ - typedef typename mpl::if_::type type; -}; - -template -struct evaluation -{ - typedef typename mpl::if_::type type; -}; - -#ifdef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS - -template -struct basic_digits : public mpl::int_<0>{ }; -template <> -struct basic_digits : public mpl::int_{ }; -template <> -struct basic_digits : public mpl::int_{ }; -template <> -struct basic_digits : public mpl::int_{ }; - -template -struct precision -{ - BOOST_STATIC_ASSERT( ::std::numeric_limits::radix == 2); - typedef typename Policy::precision_type precision_type; - typedef basic_digits digits_t; - typedef typename mpl::if_< - mpl::equal_to >, - // Possibly unknown precision: - precision_type, - typename mpl::if_< - mpl::or_, mpl::less_equal > >, - // Default case, full precision for RealType: - digits2< ::std::numeric_limits::digits>, - // User customised precision: - precision_type - >::type - >::type type; -}; - -template -struct precision -{ - typedef digits2 type; -}; -template -struct precision -{ - typedef digits2 type; -}; -template -struct precision -{ - typedef digits2 type; -}; - -#else - -template -struct precision -{ - BOOST_STATIC_ASSERT((::std::numeric_limits::radix == 2) || ((::std::numeric_limits::is_specialized == 0) || (::std::numeric_limits::digits == 0))); -#ifndef __BORLANDC__ - typedef typename Policy::precision_type precision_type; - typedef typename mpl::if_c< - ((::std::numeric_limits::is_specialized == 0) || (::std::numeric_limits::digits == 0)), - // Possibly unknown precision: - precision_type, - typename mpl::if_c< - ((::std::numeric_limits::digits <= precision_type::value) - || (Policy::precision_type::value <= 0)), - // Default case, full precision for RealType: - digits2< ::std::numeric_limits::digits>, - // User customised precision: - precision_type - >::type - >::type type; -#else - typedef typename Policy::precision_type precision_type; - typedef mpl::int_< ::std::numeric_limits::digits> digits_t; - typedef mpl::bool_< ::std::numeric_limits::is_specialized> spec_t; - typedef typename mpl::if_< - mpl::or_, mpl::equal_to > >, - // Possibly unknown precision: - precision_type, - typename mpl::if_< - mpl::or_, mpl::less_equal > >, - // Default case, full precision for RealType: - digits2< ::std::numeric_limits::digits>, - // User customised precision: - precision_type - >::type - >::type type; -#endif -}; - -#endif - -#ifdef BOOST_MATH_USE_FLOAT128 - -template -struct precision -{ - typedef mpl::int_<113> type; -}; - -#endif - -namespace detail{ - -template -inline BOOST_MATH_CONSTEXPR int digits_imp(mpl::true_ const&) BOOST_NOEXCEPT -{ -#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS - BOOST_STATIC_ASSERT( ::std::numeric_limits::is_specialized); -#else - BOOST_ASSERT(::std::numeric_limits::is_specialized); -#endif - typedef typename boost::math::policies::precision::type p_t; - return p_t::value; -} - -template -inline BOOST_MATH_CONSTEXPR int digits_imp(mpl::false_ const&) BOOST_NOEXCEPT -{ - return tools::digits(); -} - -} // namespace detail - -template -inline BOOST_MATH_CONSTEXPR int digits(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_NOEXCEPT -{ - typedef mpl::bool_< std::numeric_limits::is_specialized > tag_type; - return detail::digits_imp(tag_type()); -} -template -inline BOOST_MATH_CONSTEXPR int digits_base10(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_NOEXCEPT -{ - return boost::math::policies::digits() * 301 / 1000L; -} - -template -inline BOOST_MATH_CONSTEXPR unsigned long get_max_series_iterations() BOOST_NOEXCEPT -{ - typedef typename Policy::max_series_iterations_type iter_type; - return iter_type::value; -} - -template -inline BOOST_MATH_CONSTEXPR unsigned long get_max_root_iterations() BOOST_NOEXCEPT -{ - typedef typename Policy::max_root_iterations_type iter_type; - return iter_type::value; -} - -namespace detail{ - -template -struct series_factor_calc -{ - static T get() BOOST_MATH_NOEXCEPT(T) - { - return ldexp(T(1.0), 1 - Digits::value); - } -}; - -template -struct series_factor_calc -{ - static BOOST_MATH_CONSTEXPR T get() BOOST_MATH_NOEXCEPT(T) - { - return boost::math::tools::epsilon(); - } -}; -template -struct series_factor_calc -{ - BOOST_STATIC_CONSTANT(boost::uintmax_t, v = static_cast(1u) << (Digits::value - 1)); - - static BOOST_MATH_CONSTEXPR T get() BOOST_MATH_NOEXCEPT(T) - { - return 1 / static_cast(v); - } -}; -template -struct series_factor_calc -{ - static BOOST_MATH_CONSTEXPR T get() BOOST_MATH_NOEXCEPT(T) - { - return boost::math::tools::epsilon(); - } -}; - -template -inline BOOST_MATH_CONSTEXPR T get_epsilon_imp(mpl::true_ const&) BOOST_MATH_NOEXCEPT(T) -{ -#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS - BOOST_STATIC_ASSERT( ::std::numeric_limits::is_specialized); - BOOST_STATIC_ASSERT( ::std::numeric_limits::radix == 2); -#else - BOOST_ASSERT(::std::numeric_limits::is_specialized); - BOOST_ASSERT(::std::numeric_limits::radix == 2); -#endif - typedef typename boost::math::policies::precision::type p_t; - typedef mpl::bool_::digits> is_small_int; - typedef mpl::bool_= std::numeric_limits::digits> is_default_value; - return series_factor_calc::get(); -} - -template -inline BOOST_MATH_CONSTEXPR T get_epsilon_imp(mpl::false_ const&) BOOST_MATH_NOEXCEPT(T) -{ - return tools::epsilon(); -} - -} // namespace detail - -template -inline BOOST_MATH_CONSTEXPR T get_epsilon(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE(T)) BOOST_MATH_NOEXCEPT(T) -{ - typedef mpl::bool_< (std::numeric_limits::is_specialized && (std::numeric_limits::radix == 2)) > tag_type; - return detail::get_epsilon_imp(tag_type()); -} - -namespace detail{ - -template -char test_is_policy(const policy*); -double test_is_policy(...); - -template -struct is_policy_imp -{ - BOOST_STATIC_CONSTANT(bool, value = (sizeof(::boost::math::policies::detail::test_is_policy(static_cast(0))) == 1)); -}; - -} - -template -struct is_policy : public mpl::bool_< ::boost::math::policies::detail::is_policy_imp

::value> {}; - -// -// Helper traits class for distribution error handling: -// -template -struct constructor_error_check -{ - typedef typename Policy::domain_error_type domain_error_type; - typedef typename mpl::if_c< - (domain_error_type::value == throw_on_error) || (domain_error_type::value == user_error) || (domain_error_type::value == errno_on_error), - mpl::true_, - mpl::false_>::type type; -}; - -template -struct method_error_check -{ - typedef typename Policy::domain_error_type domain_error_type; - typedef typename mpl::if_c< - (domain_error_type::value == throw_on_error) && (domain_error_type::value != user_error), - mpl::false_, - mpl::true_>::type type; -}; -// -// Does the Policy ever throw on error? -// -template -struct is_noexcept_error_policy -{ - typedef typename Policy::domain_error_type t1; - typedef typename Policy::pole_error_type t2; - typedef typename Policy::overflow_error_type t3; - typedef typename Policy::underflow_error_type t4; - typedef typename Policy::denorm_error_type t5; - typedef typename Policy::evaluation_error_type t6; - typedef typename Policy::rounding_error_type t7; - typedef typename Policy::indeterminate_result_error_type t8; - - BOOST_STATIC_CONSTANT(bool, value = - ((t1::value != throw_on_error) && (t1::value != user_error) - && (t2::value != throw_on_error) && (t2::value != user_error) - && (t3::value != throw_on_error) && (t3::value != user_error) - && (t4::value != throw_on_error) && (t4::value != user_error) - && (t5::value != throw_on_error) && (t5::value != user_error) - && (t6::value != throw_on_error) && (t6::value != user_error) - && (t7::value != throw_on_error) && (t7::value != user_error) - && (t8::value != throw_on_error) && (t8::value != user_error))); -}; - -}}} // namespaces - -#endif // BOOST_MATH_POLICY_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/polygamma.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/polygamma.hpp deleted file mode 100644 index 3ff77836b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/polygamma.hpp +++ /dev/null @@ -1,94 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////// -// Copyright 2013 Nikhar Agrawal -// Copyright 2013 Christopher Kormanyos -// Copyright 2014 John Maddock -// Copyright 2013 Paul Bristow -// Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#ifndef _BOOST_POLYGAMMA_2013_07_30_HPP_ - #define _BOOST_POLYGAMMA_2013_07_30_HPP_ - -#include "detail/polygamma.hpp" -#include "trigamma.hpp" -#include - -// Forward declarations -namespace boost { namespace math { - template - inline typename tools::promote_args::type - trigamma(T x, const Policy&); - - template - inline typename tools::promote_args::type - trigamma(T x); -}} - -namespace boost { namespace math { - - - template - inline typename tools::promote_args::type polygamma(const int n, T x, const Policy& pol) - { - // - // Filter off special cases right at the start: - // - if(n == 0) - return boost::math::digamma(x, pol); - if(n == 1) - return boost::math::trigamma(x, pol); - // - // We've found some standard library functions to misbehave if any FPU exception flags - // are set prior to their call, this code will clear those flags, then reset them - // on exit: - // - BOOST_FPU_EXCEPTION_GUARD - // - // The type of the result - the common type of T and U after - // any integer types have been promoted to double: - // - typedef typename tools::promote_args::type result_type; - // - // The type used for the calculation. This may be a wider type than - // the result in order to ensure full precision: - // - typedef typename policies::evaluation::type value_type; - // - // The type of the policy to forward to the actual implementation. - // We disable promotion of float and double as that's [possibly] - // happened already in the line above. Also reset to the default - // any policies we don't use (reduces code bloat if we're called - // multiple times with differing policies we don't actually use). - // Also normalise the type, again to reduce code bloat in case we're - // called multiple times with functionally identical policies that happen - // to be different types. - // - typedef typename policies::normalise< - Policy, - policies::promote_float, - policies::promote_double, - policies::discrete_quantile<>, - policies::assert_undefined<> >::type forwarding_policy; - // - // Whew. Now we can make the actual call to the implementation. - // Arguments are explicitly cast to the evaluation type, and the result - // passed through checked_narrowing_cast which handles things like overflow - // according to the policy passed: - // - return policies::checked_narrowing_cast( - detail::polygamma_imp(n, static_cast(x), forwarding_policy()), - "boost::math::polygamma<%1%>(int, %1%)"); - } - - template - inline typename tools::promote_args::type polygamma(const int n, T x) - { - return boost::math::polygamma(n, x, policies::policy<>()); - } - -} } // namespace boost::math - -#endif // _BOOST_BERNOULLI_2013_05_30_HPP_ - diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/trigamma.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/trigamma.hpp deleted file mode 100644 index ebf435289..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/trigamma.hpp +++ /dev/null @@ -1,469 +0,0 @@ -// (C) Copyright John Maddock 2006. -// Use, modification and distribution are subject to the -// Boost Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#ifndef BOOST_MATH_SF_TRIGAMMA_HPP -#define BOOST_MATH_SF_TRIGAMMA_HPP - -#ifdef _MSC_VER -#pragma once -#endif - -#include "math_fwd.hpp" -#include "polygamma.hpp" -#include -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace math{ -namespace detail{ - -template -T polygamma_imp(const int n, T x, const Policy &pol); - -template -T trigamma_prec(T x, const mpl::int_<53>*, const Policy&) -{ - // Max error in interpolated form: 3.736e-017 - static const T offset = BOOST_MATH_BIG_CONSTANT(T, 53, 2.1093254089355469); - static const T P_1_2[] = { - BOOST_MATH_BIG_CONSTANT(T, 53, -1.1093280605946045), - BOOST_MATH_BIG_CONSTANT(T, 53, -3.8310674472619321), - BOOST_MATH_BIG_CONSTANT(T, 53, -3.3703848401898283), - BOOST_MATH_BIG_CONSTANT(T, 53, 0.28080574467981213), - BOOST_MATH_BIG_CONSTANT(T, 53, 1.6638069578676164), - BOOST_MATH_BIG_CONSTANT(T, 53, 0.64468386819102836), - }; - static const T Q_1_2[] = { - BOOST_MATH_BIG_CONSTANT(T, 53, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 53, 3.4535389668541151), - BOOST_MATH_BIG_CONSTANT(T, 53, 4.5208926987851437), - BOOST_MATH_BIG_CONSTANT(T, 53, 2.7012734178351534), - BOOST_MATH_BIG_CONSTANT(T, 53, 0.64468798399785611), - BOOST_MATH_BIG_CONSTANT(T, 53, -0.20314516859987728e-6), - }; - // Max error in interpolated form: 1.159e-017 - static const T P_2_4[] = { - BOOST_MATH_BIG_CONSTANT(T, 53, -0.13803835004508849e-7), - BOOST_MATH_BIG_CONSTANT(T, 53, 0.50000049158540261), - BOOST_MATH_BIG_CONSTANT(T, 53, 1.6077979838469348), - BOOST_MATH_BIG_CONSTANT(T, 53, 2.5645435828098254), - BOOST_MATH_BIG_CONSTANT(T, 53, 2.0534873203680393), - BOOST_MATH_BIG_CONSTANT(T, 53, 0.74566981111565923), - }; - static const T Q_2_4[] = { - BOOST_MATH_BIG_CONSTANT(T, 53, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 53, 2.8822787662376169), - BOOST_MATH_BIG_CONSTANT(T, 53, 4.1681660554090917), - BOOST_MATH_BIG_CONSTANT(T, 53, 2.7853527819234466), - BOOST_MATH_BIG_CONSTANT(T, 53, 0.74967671848044792), - BOOST_MATH_BIG_CONSTANT(T, 53, -0.00057069112416246805), - }; - // Maximum Deviation Found: 6.896e-018 - // Expected Error Term : -6.895e-018 - // Maximum Relative Change in Control Points : 8.497e-004 - static const T P_4_inf[] = { - static_cast(0.68947581948701249e-17L), - static_cast(0.49999999999998975L), - static_cast(1.0177274392923795L), - static_cast(2.498208511343429L), - static_cast(2.1921221359427595L), - static_cast(1.5897035272532764L), - static_cast(0.40154388356961734L), - }; - static const T Q_4_inf[] = { - static_cast(1.0L), - static_cast(1.7021215452463932L), - static_cast(4.4290431747556469L), - static_cast(2.9745631894384922L), - static_cast(2.3013614809773616L), - static_cast(0.28360399799075752L), - static_cast(0.022892987908906897L), - }; - - if(x <= 2) - { - return (offset + boost::math::tools::evaluate_polynomial(P_1_2, x) / tools::evaluate_polynomial(Q_1_2, x)) / (x * x); - } - else if(x <= 4) - { - T y = 1 / x; - return (1 + tools::evaluate_polynomial(P_2_4, y) / tools::evaluate_polynomial(Q_2_4, y)) / x; - } - T y = 1 / x; - return (1 + tools::evaluate_polynomial(P_4_inf, y) / tools::evaluate_polynomial(Q_4_inf, y)) / x; -} - -template -T trigamma_prec(T x, const mpl::int_<64>*, const Policy&) -{ - // Max error in interpolated form: 1.178e-020 - static const T offset_1_2 = BOOST_MATH_BIG_CONSTANT(T, 64, 2.109325408935546875); - static const T P_1_2[] = { - BOOST_MATH_BIG_CONSTANT(T, 64, -1.10932535608960258341), - BOOST_MATH_BIG_CONSTANT(T, 64, -4.18793841543017129052), - BOOST_MATH_BIG_CONSTANT(T, 64, -4.63865531898487734531), - BOOST_MATH_BIG_CONSTANT(T, 64, -0.919832884430500908047), - BOOST_MATH_BIG_CONSTANT(T, 64, 1.68074038333180423012), - BOOST_MATH_BIG_CONSTANT(T, 64, 1.21172611429185622377), - BOOST_MATH_BIG_CONSTANT(T, 64, 0.259635673503366427284), - }; - static const T Q_1_2[] = { - BOOST_MATH_BIG_CONSTANT(T, 64, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 64, 3.77521119359546982995), - BOOST_MATH_BIG_CONSTANT(T, 64, 5.664338024578956321), - BOOST_MATH_BIG_CONSTANT(T, 64, 4.25995134879278028361), - BOOST_MATH_BIG_CONSTANT(T, 64, 1.62956638448940402182), - BOOST_MATH_BIG_CONSTANT(T, 64, 0.259635512844691089868), - BOOST_MATH_BIG_CONSTANT(T, 64, 0.629642219810618032207e-8), - }; - // Max error in interpolated form: 3.912e-020 - static const T P_2_8[] = { - BOOST_MATH_BIG_CONSTANT(T, 64, -0.387540035162952880976e-11), - BOOST_MATH_BIG_CONSTANT(T, 64, 0.500000000276430504), - BOOST_MATH_BIG_CONSTANT(T, 64, 3.21926880986360957306), - BOOST_MATH_BIG_CONSTANT(T, 64, 10.2550347708483445775), - BOOST_MATH_BIG_CONSTANT(T, 64, 18.9002075150709144043), - BOOST_MATH_BIG_CONSTANT(T, 64, 21.0357215832399705625), - BOOST_MATH_BIG_CONSTANT(T, 64, 13.4346512182925923978), - BOOST_MATH_BIG_CONSTANT(T, 64, 3.98656291026448279118), - }; - static const T Q_2_8[] = { - BOOST_MATH_BIG_CONSTANT(T, 64, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 64, 6.10520430478613667724), - BOOST_MATH_BIG_CONSTANT(T, 64, 18.475001060603645512), - BOOST_MATH_BIG_CONSTANT(T, 64, 31.7087534567758405638), - BOOST_MATH_BIG_CONSTANT(T, 64, 31.908814523890465398), - BOOST_MATH_BIG_CONSTANT(T, 64, 17.4175479039227084798), - BOOST_MATH_BIG_CONSTANT(T, 64, 3.98749106958394941276), - BOOST_MATH_BIG_CONSTANT(T, 64, -0.000115917322224411128566), - }; - // Maximum Deviation Found: 2.635e-020 - // Expected Error Term : 2.635e-020 - // Maximum Relative Change in Control Points : 1.791e-003 - static const T P_8_inf[] = { - BOOST_MATH_BIG_CONSTANT(T, 64, -0.263527875092466899848e-19), - BOOST_MATH_BIG_CONSTANT(T, 64, 0.500000000000000058145), - BOOST_MATH_BIG_CONSTANT(T, 64, 0.0730121433777364138677), - BOOST_MATH_BIG_CONSTANT(T, 64, 1.94505878379957149534), - BOOST_MATH_BIG_CONSTANT(T, 64, 0.0517092358874932620529), - BOOST_MATH_BIG_CONSTANT(T, 64, 1.07995383547483921121), - }; - static const T Q_8_inf[] = { - BOOST_MATH_BIG_CONSTANT(T, 64, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 64, -0.187309046577818095504), - BOOST_MATH_BIG_CONSTANT(T, 64, 3.95255391645238842975), - BOOST_MATH_BIG_CONSTANT(T, 64, -1.14743283327078949087), - BOOST_MATH_BIG_CONSTANT(T, 64, 2.52989799376344914499), - BOOST_MATH_BIG_CONSTANT(T, 64, -0.627414303172402506396), - BOOST_MATH_BIG_CONSTANT(T, 64, 0.141554248216425512536), - }; - - if(x <= 2) - { - return (offset_1_2 + boost::math::tools::evaluate_polynomial(P_1_2, x) / tools::evaluate_polynomial(Q_1_2, x)) / (x * x); - } - else if(x <= 8) - { - T y = 1 / x; - return (1 + tools::evaluate_polynomial(P_2_8, y) / tools::evaluate_polynomial(Q_2_8, y)) / x; - } - T y = 1 / x; - return (1 + tools::evaluate_polynomial(P_8_inf, y) / tools::evaluate_polynomial(Q_8_inf, y)) / x; -} - -template -T trigamma_prec(T x, const mpl::int_<113>*, const Policy&) -{ - // Max error in interpolated form: 1.916e-035 - - static const T P_1_2[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, -0.999999999999999082554457936871832533), - BOOST_MATH_BIG_CONSTANT(T, 113, -4.71237311120865266379041700054847734), - BOOST_MATH_BIG_CONSTANT(T, 113, -7.94125711970499027763789342500817316), - BOOST_MATH_BIG_CONSTANT(T, 113, -5.74657746697664735258222071695644535), - BOOST_MATH_BIG_CONSTANT(T, 113, -0.404213349456398905981223965160595687), - BOOST_MATH_BIG_CONSTANT(T, 113, 2.47877781178642876561595890095758896), - BOOST_MATH_BIG_CONSTANT(T, 113, 2.07714151702455125992166949812126433), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.858877899162360138844032265418028567), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.20499222604410032375789018837922397), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.0272103140348194747360175268778415049), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.0015764849020876949848954081173520686), - }; - static const T Q_1_2[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 113, 4.71237311120863419878375031457715223), - BOOST_MATH_BIG_CONSTANT(T, 113, 9.58619118655339853449127952145877467), - BOOST_MATH_BIG_CONSTANT(T, 113, 11.0940067269829372437561421279054968), - BOOST_MATH_BIG_CONSTANT(T, 113, 8.09075424749327792073276309969037885), - BOOST_MATH_BIG_CONSTANT(T, 113, 3.87705890159891405185343806884451286), - BOOST_MATH_BIG_CONSTANT(T, 113, 1.22758678701914477836330837816976782), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.249092040606385004109672077814668716), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.0295750413900655597027079600025569048), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.00157648490200498142247694709728858139), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.161264050344059471721062360645432809e-14), - }; - - // Max error in interpolated form: 8.958e-035 - static const T P_2_4[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, -2.55843734739907925764326773972215085), - BOOST_MATH_BIG_CONSTANT(T, 113, -12.2830208240542011967952466273455887), - BOOST_MATH_BIG_CONSTANT(T, 113, -23.9195022162767993526575786066414403), - BOOST_MATH_BIG_CONSTANT(T, 113, -24.9256431504823483094158828285470862), - BOOST_MATH_BIG_CONSTANT(T, 113, -14.7979122765478779075108064826412285), - BOOST_MATH_BIG_CONSTANT(T, 113, -4.46654453928610666393276765059122272), - BOOST_MATH_BIG_CONSTANT(T, 113, -0.0191439033405649675717082465687845002), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.515412052554351265708917209749037352), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.195378348786064304378247325360320038), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.0334761282624174313035014426794245393), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.002373665205942206348500250056602687), - }; - static const T Q_2_4[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 113, 4.80098558454419907830670928248659245), - BOOST_MATH_BIG_CONSTANT(T, 113, 9.99220727843170133895059300223445265), - BOOST_MATH_BIG_CONSTANT(T, 113, 11.8896146167631330735386697123464976), - BOOST_MATH_BIG_CONSTANT(T, 113, 8.96613256683809091593793565879092581), - BOOST_MATH_BIG_CONSTANT(T, 113, 4.47254136149624110878909334574485751), - BOOST_MATH_BIG_CONSTANT(T, 113, 1.48600982028196527372434773913633152), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.319570735766764237068541501137990078), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.0407358345787680953107374215319322066), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.00237366520593271641375755486420859837), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.239554887903526152679337256236302116e-15), - BOOST_MATH_BIG_CONSTANT(T, 113, -0.294749244740618656265237072002026314e-17), - }; - - static const T y_offset_2_4 = BOOST_MATH_BIG_CONSTANT(T, 113, 3.558437347412109375); - - // Max error in interpolated form: 4.319e-035 - static const T P_4_8[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, 0.166626112697021464248967707021688845e-16), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.499999999999997739552090249208808197), - BOOST_MATH_BIG_CONSTANT(T, 113, 6.40270945019053817915772473771553187), - BOOST_MATH_BIG_CONSTANT(T, 113, 41.3833374155000608013677627389343329), - BOOST_MATH_BIG_CONSTANT(T, 113, 166.803341854562809335667241074035245), - BOOST_MATH_BIG_CONSTANT(T, 113, 453.39964786925369319960722793414521), - BOOST_MATH_BIG_CONSTANT(T, 113, 851.153712317697055375935433362983944), - BOOST_MATH_BIG_CONSTANT(T, 113, 1097.70657567285059133109286478004458), - BOOST_MATH_BIG_CONSTANT(T, 113, 938.431232478455316020076349367632922), - BOOST_MATH_BIG_CONSTANT(T, 113, 487.268001604651932322080970189930074), - BOOST_MATH_BIG_CONSTANT(T, 113, 119.953445242335730062471193124820659), - }; - static const T Q_4_8[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 113, 12.4720855670474488978638945855932398), - BOOST_MATH_BIG_CONSTANT(T, 113, 78.6093129753298570701376952709727391), - BOOST_MATH_BIG_CONSTANT(T, 113, 307.470246050318322489781182863190127), - BOOST_MATH_BIG_CONSTANT(T, 113, 805.140686101151538537565264188630079), - BOOST_MATH_BIG_CONSTANT(T, 113, 1439.12019760292146454787601409644413), - BOOST_MATH_BIG_CONSTANT(T, 113, 1735.6105285756048831268586001383127), - BOOST_MATH_BIG_CONSTANT(T, 113, 1348.32500712856328019355198611280536), - BOOST_MATH_BIG_CONSTANT(T, 113, 607.225985860570846699704222144650563), - BOOST_MATH_BIG_CONSTANT(T, 113, 119.952317857277045332558673164517227), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.000140165918355036060868680809129436084), - }; - - // Maximum Deviation Found: 2.867e-035 - // Expected Error Term : 2.866e-035 - // Maximum Relative Change in Control Points : 2.662e-004 - static const T P_8_16[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, -0.184828315274146610610872315609837439e-19), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.500000000000000004122475157735807738), - BOOST_MATH_BIG_CONSTANT(T, 113, 3.02533865247313349284875558880415875), - BOOST_MATH_BIG_CONSTANT(T, 113, 13.5995927517457371243039532492642734), - BOOST_MATH_BIG_CONSTANT(T, 113, 35.3132224283087906757037999452941588), - BOOST_MATH_BIG_CONSTANT(T, 113, 67.1639424550714159157603179911505619), - BOOST_MATH_BIG_CONSTANT(T, 113, 83.5767733658513967581959839367419891), - BOOST_MATH_BIG_CONSTANT(T, 113, 71.073491212235705900866411319363501), - BOOST_MATH_BIG_CONSTANT(T, 113, 35.8621515614725564575893663483998663), - BOOST_MATH_BIG_CONSTANT(T, 113, 8.72152231639983491987779743154333318), - }; - static const T Q_8_16[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 113, 5.71734397161293452310624822415866372), - BOOST_MATH_BIG_CONSTANT(T, 113, 25.293404179620438179337103263274815), - BOOST_MATH_BIG_CONSTANT(T, 113, 62.2619767967468199111077640625328469), - BOOST_MATH_BIG_CONSTANT(T, 113, 113.955048909238993473389714972250235), - BOOST_MATH_BIG_CONSTANT(T, 113, 130.807138328938966981862203944329408), - BOOST_MATH_BIG_CONSTANT(T, 113, 102.423146902337654110717764213057753), - BOOST_MATH_BIG_CONSTANT(T, 113, 44.0424772805245202514468199602123565), - BOOST_MATH_BIG_CONSTANT(T, 113, 8.89898032477904072082994913461386099), - BOOST_MATH_BIG_CONSTANT(T, 113, -0.0296627336872039988632793863671456398), - }; - // Maximum Deviation Found: 1.079e-035 - // Expected Error Term : -1.079e-035 - // Maximum Relative Change in Control Points : 7.884e-003 - static const T P_16_inf[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, 0.0), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.500000000000000000000000000000087317), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.345625669885456215194494735902663968), - BOOST_MATH_BIG_CONSTANT(T, 113, 9.62895499360842232127552650044647769), - BOOST_MATH_BIG_CONSTANT(T, 113, 3.5936085382439026269301003761320812), - BOOST_MATH_BIG_CONSTANT(T, 113, 49.459599118438883265036646019410669), - BOOST_MATH_BIG_CONSTANT(T, 113, 7.77519237321893917784735690560496607), - BOOST_MATH_BIG_CONSTANT(T, 113, 74.4536074488178075948642351179304121), - BOOST_MATH_BIG_CONSTANT(T, 113, 2.75209340397069050436806159297952699), - BOOST_MATH_BIG_CONSTANT(T, 113, 23.9292359711471667884504840186561598), - }; - static const T Q_16_inf[] = { - BOOST_MATH_BIG_CONSTANT(T, 113, 1.0), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.357918006437579097055656138920742037), - BOOST_MATH_BIG_CONSTANT(T, 113, 19.1386039850709849435325005484512944), - BOOST_MATH_BIG_CONSTANT(T, 113, 0.874349081464143606016221431763364517), - BOOST_MATH_BIG_CONSTANT(T, 113, 98.6516097434855572678195488061432509), - BOOST_MATH_BIG_CONSTANT(T, 113, -16.1051972833382893468655223662534306), - BOOST_MATH_BIG_CONSTANT(T, 113, 154.316860216253720989145047141653727), - BOOST_MATH_BIG_CONSTANT(T, 113, -40.2026880424378986053105969312264534), - BOOST_MATH_BIG_CONSTANT(T, 113, 60.1679136674264778074736441126810223), - BOOST_MATH_BIG_CONSTANT(T, 113, -13.3414844622256422644504472438320114), - BOOST_MATH_BIG_CONSTANT(T, 113, 2.53795636200649908779512969030363442), - }; - - if(x <= 2) - { - return (2 + boost::math::tools::evaluate_polynomial(P_1_2, x) / tools::evaluate_polynomial(Q_1_2, x)) / (x * x); - } - else if(x <= 4) - { - return (y_offset_2_4 + boost::math::tools::evaluate_polynomial(P_2_4, x) / tools::evaluate_polynomial(Q_2_4, x)) / (x * x); - } - else if(x <= 8) - { - T y = 1 / x; - return (1 + tools::evaluate_polynomial(P_4_8, y) / tools::evaluate_polynomial(Q_4_8, y)) / x; - } - else if(x <= 16) - { - T y = 1 / x; - return (1 + tools::evaluate_polynomial(P_8_16, y) / tools::evaluate_polynomial(Q_8_16, y)) / x; - } - T y = 1 / x; - return (1 + tools::evaluate_polynomial(P_16_inf, y) / tools::evaluate_polynomial(Q_16_inf, y)) / x; -} - -template -T trigamma_imp(T x, const Tag* t, const Policy& pol) -{ - // - // This handles reflection of negative arguments, and all our - // error handling, then forwards to the T-specific approximation. - // - BOOST_MATH_STD_USING // ADL of std functions. - - T result = 0; - // - // Check for negative arguments and use reflection: - // - if(x <= 0) - { - // Reflect: - T z = 1 - x; - // Argument reduction for tan: - if(floor(x) == x) - { - return policies::raise_pole_error("boost::math::trigamma<%1%>(%1%)", 0, (1-x), pol); - } - T s = fabs(x) < fabs(z) ? boost::math::sin_pi(x, pol) : boost::math::sin_pi(z, pol); - return -trigamma_imp(z, t, pol) + boost::math::pow<2>(constants::pi()) / (s * s); - } - if(x < 1) - { - result = 1 / (x * x); - x += 1; - } - return result + trigamma_prec(x, t, pol); -} - -template -T trigamma_imp(T x, const mpl::int_<0>*, const Policy& pol) -{ - return polygamma_imp(1, x, pol); -} -// -// Initializer: ensure all our constants are initialized prior to the first call of main: -// -template -struct trigamma_initializer -{ - struct init - { - init() - { - typedef typename policies::precision::type precision_type; - do_init(mpl::bool_()); - } - void do_init(const mpl::true_&) - { - boost::math::trigamma(T(2.5), Policy()); - } - void do_init(const mpl::false_&){} - void force_instantiate()const{} - }; - static const init initializer; - static void force_instantiate() - { - initializer.force_instantiate(); - } -}; - -template -const typename trigamma_initializer::init trigamma_initializer::initializer; - -} // namespace detail - -template -inline typename tools::promote_args::type - trigamma(T x, const Policy&) -{ - typedef typename tools::promote_args::type result_type; - typedef typename policies::evaluation::type value_type; - typedef typename policies::precision::type precision_type; - typedef typename mpl::if_< - mpl::or_< - mpl::less_equal >, - mpl::greater > - >, - mpl::int_<0>, - typename mpl::if_< - mpl::less >, - mpl::int_<53>, - typename mpl::if_< - mpl::less >, - mpl::int_<64>, - mpl::int_<113> - >::type - >::type - >::type tag_type; - - typedef typename policies::normalise< - Policy, - policies::promote_float, - policies::promote_double, - policies::discrete_quantile<>, - policies::assert_undefined<> >::type forwarding_policy; - - // Force initialization of constants: - detail::trigamma_initializer::force_instantiate(); - - return policies::checked_narrowing_cast(detail::trigamma_imp( - static_cast(x), - static_cast(0), forwarding_policy()), "boost::math::trigamma<%1%>(%1%)"); -} - -template -inline typename tools::promote_args::type - trigamma(T x) -{ - return trigamma(x, policies::policy<>()); -} - -} // namespace math -} // namespace boost -#endif - diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_collections_load_imp.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_collections_load_imp.hpp deleted file mode 100644 index 411b9a0ab..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_collections_load_imp.hpp +++ /dev/null @@ -1,77 +0,0 @@ -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -#ifndef BOOST_SERIALIZATION_UNORDERED_COLLECTIONS_LOAD_IMP_HPP -#define BOOST_SERIALIZATION_UNORDERED_COLLECTIONS_LOAD_IMP_HPP - -// MS compatible compilers support #pragma once -#if defined(_MSC_VER) && (_MSC_VER >= 1020) -# pragma once -# pragma warning (disable : 4786) // too long name, harmless warning -#endif - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// unordered_collections_load_imp.hpp: serialization for loading stl collections - -// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . -// (C) Copyright 2014 Jim Bell -// Use, modification and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for updates, documentation, and revision history. - -// helper function templates for serialization of collections - -#include -#include // size_t -#include // msvc 6.0 needs this for warning suppression -#if defined(BOOST_NO_STDC_NAMESPACE) -namespace std{ - using ::size_t; -} // namespace std -#endif -#include - -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace serialization { -namespace stl { - -////////////////////////////////////////////////////////////////////// -// implementation of serialization for STL containers -// -template -inline void load_unordered_collection(Archive & ar, Container &s) -{ - s.clear(); - collection_size_type count; - collection_size_type bucket_count; - boost::serialization::item_version_type item_version(0); - boost::archive::library_version_type library_version( - ar.get_library_version() - ); - // retrieve number of elements - ar >> BOOST_SERIALIZATION_NVP(count); - ar >> BOOST_SERIALIZATION_NVP(bucket_count); - if(boost::archive::library_version_type(3) < library_version){ - ar >> BOOST_SERIALIZATION_NVP(item_version); - } - s.rehash(bucket_count); - InputFunction ifunc; - while(count-- > 0){ - ifunc(ar, s, item_version); - } -} - -} // namespace stl -} // namespace serialization -} // namespace boost - -#endif //BOOST_SERIALIZATION_UNORDERED_COLLECTIONS_LOAD_IMP_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_collections_save_imp.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_collections_save_imp.hpp deleted file mode 100644 index 6f763bc8f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_collections_save_imp.hpp +++ /dev/null @@ -1,89 +0,0 @@ -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -#ifndef BOOST_SERIALIZATION_UNORDERED_COLLECTIONS_SAVE_IMP_HPP -#define BOOST_SERIALIZATION_UNORDERED_COLLECTIONS_SAVE_IMP_HPP - -// MS compatible compilers support #pragma once -#if defined(_MSC_VER) && (_MSC_VER >= 1020) -# pragma once -#endif - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// hash_collections_save_imp.hpp: serialization for stl collections - -// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . -// (C) Copyright 2014 Jim Bell -// Use, modification and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for updates, documentation, and revision history. - -// helper function templates for serialization of collections - -#include -#include -#include -#include -#include -#include - -namespace boost{ -namespace serialization { -namespace stl { - -////////////////////////////////////////////////////////////////////// -// implementation of serialization for STL containers -// - -template -inline void save_unordered_collection(Archive & ar, const Container &s) -{ - collection_size_type count(s.size()); - const collection_size_type bucket_count(s.bucket_count()); - const item_version_type item_version( - version::value - ); - - #if 0 - /* should only be necessary to create archives of previous versions - * which is not currently supported. So for now comment this out - */ - boost::archive::library_version_type library_version( - ar.get_library_version() - ); - // retrieve number of elements - ar << BOOST_SERIALIZATION_NVP(count); - ar << BOOST_SERIALIZATION_NVP(bucket_count); - if(boost::archive::library_version_type(3) < library_version){ - // record number of elements - // make sure the target type is registered so we can retrieve - // the version when we load - ar << BOOST_SERIALIZATION_NVP(item_version); - } - #else - ar << BOOST_SERIALIZATION_NVP(count); - ar << BOOST_SERIALIZATION_NVP(bucket_count); - ar << BOOST_SERIALIZATION_NVP(item_version); - #endif - - typename Container::const_iterator it = s.begin(); - while(count-- > 0){ - // note borland emits a no-op without the explicit namespace - boost::serialization::save_construct_data_adl( - ar, - &(*it), - boost::serialization::version< - typename Container::value_type - >::value - ); - ar << boost::serialization::make_nvp("item", *it++); - } -} - -} // namespace stl -} // namespace serialization -} // namespace boost - -#endif //BOOST_SERIALIZATION_UNORDERED_COLLECTIONS_SAVE_IMP_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_map.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_map.hpp deleted file mode 100644 index 4ae37d22c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/unordered_map.hpp +++ /dev/null @@ -1,234 +0,0 @@ -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -#ifndef BOOST_SERIALIZATION_UNORDERED_MAP_HPP -#define BOOST_SERIALIZATION_UNORDERED_MAP_HPP - -// MS compatible compilers support #pragma once -#if defined(_MSC_VER) && (_MSC_VER >= 1020) -# pragma once -#endif - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// serialization/unordered_map.hpp: -// serialization for stl unordered_map templates - -// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . -// (C) Copyright 2014 Jim Bell -// Use, modification and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for updates, documentation, and revision history. - -#include - -#include - -#include -#include "unordered_collections_save_imp.hpp" -#include "unordered_collections_load_imp.hpp" -#include - -namespace boost { -namespace serialization { - -namespace stl { - -// map input -template -struct archive_input_unordered_map -{ - inline void operator()( - Archive &ar, - Container &s, - const unsigned int v - ){ - typedef typename Container::value_type type; - detail::stack_construct t(ar, v); - // borland fails silently w/o full namespace - ar >> boost::serialization::make_nvp("item", t.reference()); - std::pair result = - s.insert(t.reference()); - // note: the following presumes that the map::value_type was NOT tracked - // in the archive. This is the usual case, but here there is no way - // to determine that. - if(result.second){ - ar.reset_object_address( - & (result.first->second), - & t.reference().second - ); - } - } -}; - -// multimap input -template -struct archive_input_unordered_multimap -{ - inline void operator()( - Archive &ar, - Container &s, - const unsigned int v - ){ - typedef typename Container::value_type type; - detail::stack_construct t(ar, v); - // borland fails silently w/o full namespace - ar >> boost::serialization::make_nvp("item", t.reference()); - typename Container::const_iterator result - = s.insert(t.reference()); - // note: the following presumes that the map::value_type was NOT tracked - // in the archive. This is the usual case, but here there is no way - // to determine that. - ar.reset_object_address( - & result->second, - & t.reference() - ); - } -}; - -} // stl - -template< - class Archive, - class Key, - class HashFcn, - class EqualKey, - class Allocator -> -inline void save( - Archive & ar, - const std::unordered_map< - Key, HashFcn, EqualKey, Allocator - > &t, - const unsigned int /*file_version*/ -){ - boost::serialization::stl::save_unordered_collection< - Archive, - std::unordered_map< - Key, HashFcn, EqualKey, Allocator - > - >(ar, t); -} - -template< - class Archive, - class Key, - class HashFcn, - class EqualKey, - class Allocator -> -inline void load( - Archive & ar, - std::unordered_map< - Key, HashFcn, EqualKey, Allocator - > &t, - const unsigned int /*file_version*/ -){ - boost::serialization::stl::load_unordered_collection< - Archive, - std::unordered_map< - Key, HashFcn, EqualKey, Allocator - >, - boost::serialization::stl::archive_input_unordered_map< - Archive, - std::unordered_map< - Key, HashFcn, EqualKey, Allocator - > - > - >(ar, t); -} - -// split non-intrusive serialization function member into separate -// non intrusive save/load member functions -template< - class Archive, - class Key, - class HashFcn, - class EqualKey, - class Allocator -> -inline void serialize( - Archive & ar, - std::unordered_map< - Key, HashFcn, EqualKey, Allocator - > &t, - const unsigned int file_version -){ - boost::serialization::split_free(ar, t, file_version); -} - -// unordered_multimap -template< - class Archive, - class Key, - class HashFcn, - class EqualKey, - class Allocator -> -inline void save( - Archive & ar, - const std::unordered_multimap< - Key, HashFcn, EqualKey, Allocator - > &t, - const unsigned int /*file_version*/ -){ - boost::serialization::stl::save_unordered_collection< - Archive, - std::unordered_multimap< - Key, HashFcn, EqualKey, Allocator - > - >(ar, t); -} - -template< - class Archive, - class Key, - class HashFcn, - class EqualKey, - class Allocator -> -inline void load( - Archive & ar, - std::unordered_multimap< - Key, HashFcn, EqualKey, Allocator - > &t, - const unsigned int /*file_version*/ -){ - boost::serialization::stl::load_unordered_collection< - Archive, - std::unordered_multimap< - Key, HashFcn, EqualKey, Allocator - >, - boost::serialization::stl::archive_input_unordered_multimap< - Archive, - std::unordered_multimap< - Key, HashFcn, EqualKey, Allocator - > - > - >(ar, t); -} - -// split non-intrusive serialization function member into separate -// non intrusive save/load member functions -template< - class Archive, - class Key, - class HashFcn, - class EqualKey, - class Allocator -> -inline void serialize( - Archive & ar, - std::unordered_multimap< - Key, HashFcn, EqualKey, Allocator - > &t, - const unsigned int file_version -){ - boost::serialization::split_free(ar, t, file_version); -} - -} // namespace serialization -} // namespace boost - -#endif // BOOST_SERIALIZATION_UNORDERED_MAP_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/boost_backport/vector.hpp b/src/sdk/mlpack/include/mlpack/core/boost_backport/vector.hpp deleted file mode 100644 index a1737548e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/boost_backport/vector.hpp +++ /dev/null @@ -1,227 +0,0 @@ -#ifndef BOOST_SERIALIZATION_VECTOR_HPP -#define BOOST_SERIALIZATION_VECTOR_HPP - -// MS compatible compilers support #pragma once -#if defined(_MSC_VER) -# pragma once -#endif - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// vector.hpp: serialization for stl vector templates - -// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . -// fast array serialization (C) Copyright 2005 Matthias Troyer -// Use, modification and distribution is subject to the Boost Software -// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -// See http://www.boost.org for updates, documentation, and revision history. - -#include - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -// default is being compatible with version 1.34.1 files, not 1.35 files -#ifndef BOOST_SERIALIZATION_VECTOR_VERSIONED -#define BOOST_SERIALIZATION_VECTOR_VERSIONED(V) (V==4 || V==5) -#endif - -// function specializations must be defined in the appropriate -// namespace - boost::serialization -#if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION) -#define STD _STLP_STD -#else -#define STD std -#endif - -namespace boost { -namespace serialization { - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// vector< T > - -// the default versions - -template -inline void save( - Archive & ar, - const std::vector &t, - const unsigned int /* file_version */, - mpl::false_ -){ - boost::serialization::stl::save_collection >( - ar, t - ); -} - -template -inline void load( - Archive & ar, - std::vector &t, - const unsigned int /* file_version */, - mpl::false_ -){ - const boost::archive::library_version_type library_version( - ar.get_library_version() - ); - // retrieve number of elements - item_version_type item_version(0); - collection_size_type count; - ar >> BOOST_SERIALIZATION_NVP(count); - if(boost::archive::library_version_type(3) < library_version){ - ar >> BOOST_SERIALIZATION_NVP(item_version); - } - t.reserve(count); - stl::collection_load_impl(ar, t, count, item_version); -} - -// the optimized versions - -template -inline void save( - Archive & ar, - const std::vector &t, - const unsigned int /* file_version */, - mpl::true_ -){ - const collection_size_type count(t.size()); - ar << BOOST_SERIALIZATION_NVP(count); - if (!t.empty()) - ar << boost::serialization::make_array(detail::get_data(t),t.size()); -} - -template -inline void load( - Archive & ar, - std::vector &t, - const unsigned int /* file_version */, - mpl::true_ -){ - collection_size_type count(t.size()); - ar >> BOOST_SERIALIZATION_NVP(count); - t.resize(count); - unsigned int item_version=0; - if(BOOST_SERIALIZATION_VECTOR_VERSIONED(ar.get_library_version())) { - ar >> BOOST_SERIALIZATION_NVP(item_version); - } - if (!t.empty()) - ar >> boost::serialization::make_array(detail::get_data(t),t.size()); - } - -// dispatch to either default or optimized versions - -template -inline void save( - Archive & ar, - const std::vector &t, - const unsigned int file_version -){ - typedef typename - boost::serialization::use_array_optimization::template apply< - typename remove_const::type - >::type use_optimized; - save(ar,t,file_version, use_optimized()); -} - -template -inline void load( - Archive & ar, - std::vector &t, - const unsigned int file_version -){ -#ifdef BOOST_SERIALIZATION_VECTOR_135_HPP - if (ar.get_library_version()==boost::archive::library_version_type(5)) - { - load(ar,t,file_version, boost::is_arithmetic()); - return; - } -#endif - typedef typename - boost::serialization::use_array_optimization::template apply< - typename remove_const::type - >::type use_optimized; - load(ar,t,file_version, use_optimized()); -} - -// split non-intrusive serialization function member into separate -// non intrusive save/load member functions -template -inline void serialize( - Archive & ar, - std::vector & t, - const unsigned int file_version -){ - boost::serialization::split_free(ar, t, file_version); -} - -/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 -// vector -template -inline void save( - Archive & ar, - const std::vector &t, - const unsigned int /* file_version */ -){ - // record number of elements - collection_size_type count (t.size()); - ar << BOOST_SERIALIZATION_NVP(count); - std::vector::const_iterator it = t.begin(); - while(count-- > 0){ - bool tb = *it++; - ar << boost::serialization::make_nvp("item", tb); - } -} - -template -inline void load( - Archive & ar, - std::vector &t, - const unsigned int /* file_version */ -){ - // retrieve number of elements - collection_size_type count; - ar >> BOOST_SERIALIZATION_NVP(count); - t.resize(count); - for(collection_size_type i = collection_size_type(0); i < count; ++i){ - bool b; - ar >> boost::serialization::make_nvp("item", b); - t[i] = b; - } -} - -// split non-intrusive serialization function member into separate -// non intrusive save/load member functions -template -inline void serialize( - Archive & ar, - std::vector & t, - const unsigned int file_version -){ - boost::serialization::split_free(ar, t, file_version); -} - -} // serialization -} // namespace boost - -#include - -BOOST_SERIALIZATION_COLLECTION_TRAITS(std::vector) -#undef STD - -#endif // BOOST_SERIALIZATION_VECTOR_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/cv/cv_base.hpp b/src/sdk/mlpack/include/mlpack/core/cv/cv_base.hpp deleted file mode 100644 index 5f51dd7f9..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/cv_base.hpp +++ /dev/null @@ -1,236 +0,0 @@ -/** - * @file cv_base.hpp - * @author Kirill Mishchenko - * - * A base class for cross-validation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_CV_BASE_HPP -#define MLPACK_CORE_CV_CV_BASE_HPP - -#include - -namespace mlpack { -namespace cv { - -/** - * An auxiliary class for cross-validation. It serves to handle basic non-data - * constructor parameters of a machine learning algorithm (like datasetInfo or - * numClasses) and to assert that the machine learning algorithm and data - * satisfy certain conditions. - * - * This class is not meant to be used directly by users. To cross-validate - * rather use end-user classes like SimpleCV or KFoldCV. - * - * @tparam MLAlgorithm A machine learning algorithm. - * @tparam MatType The type of data. - * @tparam PredictionsType The type of predictions (labels/responses). - * @tparam WeightsType The type of weights. It supposed to be void* when weights - * are not supported. - */ -template -class CVBase -{ - public: - //! A short alias for MetaInfoExtractor. - using MIE = - MetaInfoExtractor; - - /** - * Assert that MLAlgorithm doesn't take any additional basic parameters like - * numClasses. - */ - CVBase(); - - /** - * Assert that MLAlgorithm takes the numClasses parameter and store it. - * - * @param numClasses Number of classes in the dataset. - */ - CVBase(const size_t numClasses); - - /** - * Assert that MLAlgorithm takes the numClasses parameter and a - * data::DatasetInfo parameter and store them. - * - * @param datasetInfo Type information for each dimension of the dataset. - * @param numClasses Number of classes in the dataset. - */ - CVBase(const data::DatasetInfo& datasetInfo, - const size_t numClasses); - - /** - * Assert there is the equal number of data points and predictions. - */ - static void AssertDataConsistency(const MatType& xs, - const PredictionsType& ys); - - /** - * Assert weighted learning is supported and there is the equal number of data - * points and weights. - */ - static void AssertWeightsConsistency(const MatType& xs, - const WeightsType& weights); - - /** - * Train MLAlgorithm with given data points, predictions, and hyperparameters - * depending on what CVBase constructor has been called. - */ - template - MLAlgorithm Train(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args); - - /** - * Train MLAlgorithm with given data points, predictions, weights, and - * hyperparameters depending on what CVBase constructor has been called. - */ - template - MLAlgorithm Train(const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const MLAlgorithmArgs&... args); - - private: - static_assert(MIE::IsSupported, - "The given MLAlgorithm is not supported by MetaInfoExtractor"); - - //! A variable for storing a data::DatasetInfo parameter if it is passed. - const data::DatasetInfo datasetInfo; - //! An indicator whether a data::DatasetInfo parameter has been passed. - const bool isDatasetInfoPassed; - //! A variable for storing the numClasses parameter if it is passed. - size_t numClasses; - - /** - * Assert there is an equal number of data points and predictions. - */ - static void AssertSizeEquality(const MatType& xs, - const PredictionsType& ys); - - /** - * Assert the number of weights is the same as the number of data points. - */ - static void AssertWeightsSize(const MatType& xs, - const WeightsType& weights); - - /** - * Construct a trained MLAlgorithm model if MLAlgorithm doesn't take the - * numClasses parameter. - */ - template::type> - MLAlgorithm TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args); - - /** - * Construct a trained MLAlgorithm model if MLAlgorithm takes the - * numClasses parameter. - */ - template::type, - typename = void> - MLAlgorithm TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args); - - /** - * Construct a trained MLAlgorithm model if MLAlgorithm takes the - * numClasses parameter and a data::DatasetInfo parameter. - */ - template::type, - typename = void, - typename = void> - MLAlgorithm TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args); - - /** - * Construct a trained MLAlgorithm model if MLAlgorithm doesn't take the - * numClasses parameter. - */ - template::type> - MLAlgorithm TrainModel(const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const MLAlgorithmArgs&... args); - - /** - * Construct a trained MLAlgorithm model if MLAlgorithm takes the - * numClasses parameter. - */ - template::type, - typename = void> - MLAlgorithm TrainModel(const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const MLAlgorithmArgs&... args); - - /** - * Construct a trained MLAlgorithm model if MLAlgorithm takes the - * numClasses parameter and a data::DatasetInfo parameter. - */ - template::type, - typename = void, - typename = void> - MLAlgorithm TrainModel(const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const MLAlgorithmArgs&... args); - - /** - * When MLAlgorithm supports a data::DatasetInfo parameter, training should be - * treated separately - there are models that can be constructed with and - * without a data:DatasetInfo parameter and models that can be constructed - * only with a data::DatasetInfo parameter. - * - * Construct a trained MLAlgorithm model when it can be constructed without a - * data::DatasetInfo parameter. - */ - template::type> - MLAlgorithm TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args); - - /** - * Construct a trained MLAlgorithm model when it can't be constructed without - * a data::DatasetInfo parameter. - */ - template::type, - typename = void> - MLAlgorithm TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args); -}; - -} // namespace cv -} // namespace mlpack - -// Include implementation -#include "cv_base_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/cv_base_impl.hpp b/src/sdk/mlpack/include/mlpack/core/cv/cv_base_impl.hpp deleted file mode 100644 index 6570b614a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/cv_base_impl.hpp +++ /dev/null @@ -1,317 +0,0 @@ -/** - * @file cv_base_impl.hpp - * @author Kirill Mishchenko - * - * The implementation of the class CVBase. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_CV_BASE_IMPL_HPP -#define MLPACK_CORE_CV_CV_BASE_IMPL_HPP - -namespace mlpack { -namespace cv { - -template -CVBase::CVBase() : - isDatasetInfoPassed(false) -{ - static_assert(!MIE::TakesNumClasses, - "The given MLAlgorithm requires the numClasses parameter"); -} - -template -CVBase::CVBase(const size_t numClasses) : - isDatasetInfoPassed(false), - numClasses(numClasses) -{ - static_assert(MIE::TakesNumClasses, - "The given MLAlgorithm does not take the numClasses parameter"); -} - -template -CVBase::CVBase(const data::DatasetInfo& datasetInfo, - const size_t numClasses) : - datasetInfo(datasetInfo), - isDatasetInfoPassed(true), - numClasses(numClasses) -{ - static_assert(MIE::TakesNumClasses, - "The given MLAlgorithm does not take the numClasses parameter"); - static_assert(MIE::TakesDatasetInfo, - "The given MLAlgorithm does not accept a data::DatasetInfo parameter"); -} - -template -template -MLAlgorithm CVBase::Train(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args) -{ - return TrainModel(xs, ys, args...); -} - -template -template -MLAlgorithm CVBase::Train(const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const MLAlgorithmArgs&... args) -{ - return TrainModel(xs, ys, weights, args...); -} - -template -void CVBase::AssertDataConsistency(const MatType& xs, - const PredictionsType& ys) -{ - if (xs.n_cols != ys.n_cols) - { - std::ostringstream oss; - oss << "CVBase::AssertDataConsistency(): number of data points (" - << xs.n_cols << ") does not match number of predictions (" << ys.n_cols - << ")!" << std::endl; - throw std::invalid_argument(oss.str()); - } -} - -template -void CVBase::AssertWeightsConsistency(const MatType& xs, - const WeightsType& weights) -{ - static_assert(MIE::SupportsWeights, - "The given MLAlgorithm does not support weighted learning"); - - if (weights.n_elem != xs.n_cols) - { - std::ostringstream oss; - oss << "CVBase::AssertWeightsConsistency(): number of weights (" - << weights.n_elem << ") does not match number of data points (" - << xs.n_cols << ")!" << std::endl; - throw std::invalid_argument(oss.str()); - } -} - -template -template -MLAlgorithm CVBase::TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args) -{ - static_assert( - std::is_constructible::value, - "The given MLAlgorithm is not constructible from the passed arguments"); - - return MLAlgorithm(xs, ys, args...); -} - -template -template -MLAlgorithm CVBase::TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args) -{ - static_assert( - std::is_constructible::value, - "The given MLAlgorithm is not constructible from the passed arguments"); - - return MLAlgorithm(xs, ys, numClasses, args...); -} - -template -template -MLAlgorithm CVBase::TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args) -{ - static_assert( - std::is_constructible::value, - "The given MLAlgorithm is not constructible with a data::DatasetInfo " - "parameter and the passed arguments"); - - static const bool constructableWithoutDatasetInfo = - std::is_constructible::value; - return TrainModel(xs, ys, args...); -} - -template -template -MLAlgorithm CVBase::TrainModel(const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const MLAlgorithmArgs&... args) -{ - static_assert( - std::is_constructible::value, - "The given MLAlgorithm is not constructible from the passed arguments"); - - return MLAlgorithm(xs, ys, weights, args...); -} - -template -template -MLAlgorithm CVBase::TrainModel(const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const MLAlgorithmArgs&... args) -{ - static_assert( - std::is_constructible::value, - "The given MLAlgorithm is not constructible from the passed arguments"); - - return MLAlgorithm(xs, ys, numClasses, weights, args...); -} - -template -template -MLAlgorithm CVBase::TrainModel(const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const MLAlgorithmArgs&... args) -{ - static_assert( - std::is_constructible::value, - "The given MLAlgorithm is not constructible with a data::DatasetInfo " - "parameter and the passed arguments"); - - static const bool constructableWithoutDatasetInfo = - std::is_constructible::value; - return TrainModel(xs, ys, weights, args...); -} - -template -template -MLAlgorithm CVBase::TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args) -{ - if (isDatasetInfoPassed) - return MLAlgorithm(xs, datasetInfo, ys, numClasses, args...); - else - return MLAlgorithm(xs, ys, numClasses, args...); -} - -template -template -MLAlgorithm CVBase::TrainModel(const MatType& xs, - const PredictionsType& ys, - const MLAlgorithmArgs&... args) -{ - if (!isDatasetInfoPassed) - throw std::invalid_argument( - "The given MLAlgorithm requires a data::DatasetInfo parameter"); - - return MLAlgorithm(xs, datasetInfo, ys, numClasses, args...); -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/k_fold_cv.hpp b/src/sdk/mlpack/include/mlpack/core/cv/k_fold_cv.hpp deleted file mode 100644 index 0fb76ea16..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/k_fold_cv.hpp +++ /dev/null @@ -1,316 +0,0 @@ -/** - * @file k_fold_cv.hpp - * @author Kirill Mishchenko - * - * k-fold cross-validation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_K_FOLD_CV_HPP -#define MLPACK_CORE_CV_K_FOLD_CV_HPP - -#include -#include - -namespace mlpack { -namespace cv { - -/** - * The class KFoldCV implements k-fold cross-validation for regression and - * classification algorithms. - * - * To construct a KFoldCV object you need to pass the k parameter and arguments - * that specify data. For example, you can run 10-fold cross-validation for - * SoftmaxRegression in the following way. - * - * @code - * // 100-point 5-dimensional random dataset. - * arma::mat data = arma::randu(5, 100); - * // Random labels in the [0, 4] interval. - * arma::Row labels = - * arma::randi>(100, arma::distr_param(0, 4)); - * size_t numClasses = 5; - * - * KFoldCV, Accuracy> cv(10, data, labels, numClasses); - * - * double lambda = 0.1; - * double softmaxAccuracy = cv.Evaluate(lambda); - * @endcode - * - * Before calling @c Evaluate(), it is possible to shuffle the data by calling - * the @c Shuffle() function. Shuffling is performed at construction time if - * the parameter @c shuffle is set to @c true in the constructor. - * - * @tparam MLAlgorithm A machine learning algorithm. - * @tparam Metric A metric to assess the quality of a trained model. - * @tparam MatType The type of data. - * @tparam PredictionsType The type of predictions (should be passed when the - * predictions type is a template parameter in Train methods of - * MLAlgorithm). - * @tparam WeightsType The type of weights (should be passed when weighted - * learning is supported, and the weights type is a template parameter in - * Train methods of MLAlgorithm). - */ -template::PredictionsType, - typename WeightsType = - typename MetaInfoExtractor::WeightsType> -class KFoldCV -{ - public: - /** - * This constructor can be used for regression algorithms and for binary - * classification algorithms. - * - * @param k Number of folds (should be at least 2). - * @param xs Data points to cross-validate on. - * @param ys Predictions (labels for classification algorithms and responses - * for regression algorithms) for each data point. - * @param shuffle Whether or not to shuffle the data during construction. - */ - KFoldCV(const size_t k, - const MatType& xs, - const PredictionsType& ys, - const bool shuffle = true); - - /** - * This constructor can be used for multiclass classification algorithms. - * - * @param k Number of folds (should be at least 2). - * @param xs Data points to cross-validate on. - * @param ys Labels for each data point. - * @param numClasses Number of classes in the dataset. - * @param shuffle Whether or not to shuffle the data during construction. - */ - KFoldCV(const size_t k, - const MatType& xs, - const PredictionsType& ys, - const size_t numClasses, - const bool shuffle = true); - - /** - * This constructor can be used for multiclass classification algorithms that - * can take a data::DatasetInfo parameter. - * - * @param k Number of folds (should be at least 2). - * @param xs Data points to cross-validate on. - * @param datasetInfo Type information for each dimension of the dataset. - * @param ys Labels for each data point. - * @param numClasses Number of classes in the dataset. - * @param shuffle Whether or not to shuffle the data during construction. - */ - KFoldCV(const size_t k, - const MatType& xs, - const data::DatasetInfo& datasetInfo, - const PredictionsType& ys, - const size_t numClasses, - const bool shuffle = true); - - /** - * This constructor can be used for regression and binary classification - * algorithms that support weighted learning. - * - * @param k Number of folds (should be at least 2). - * @param xs Data points to cross-validate on. - * @param ys Predictions (labels for classification algorithms and responses - * for regression algorithms) for each data point. - * @param weights Observation weights (for boosting). - * @param shuffle Whether or not to shuffle the data during construction. - */ - KFoldCV(const size_t k, - const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const bool shuffle = true); - - /** - * This constructor can be used for multiclass classification algorithms that - * support weighted learning. - * - * @param k Number of folds (should be at least 2). - * @param xs Data points to cross-validate on. - * @param ys Labels for each data point. - * @param numClasses Number of classes in the dataset. - * @param weights Observation weights (for boosting). - * @param shuffle Whether or not to shuffle the data during construction. - */ - KFoldCV(const size_t k, - const MatType& xs, - const PredictionsType& ys, - const size_t numClasses, - const WeightsType& weights, - const bool shuffle = true); - - /** - * This constructor can be used for multiclass classification algorithms that - * can take a data::DatasetInfo parameter and support weighted learning. - * - * @param k Number of folds (should be at least 2). - * @param xs Data points to cross-validate on. - * @param datasetInfo Type information for each dimension of the dataset. - * @param ys Labels for each data point. - * @param numClasses Number of classes in the dataset. - * @param weights Observation weights (for boosting). - * @param shuffle Whether or not to shuffle the data during construction. - */ - KFoldCV(const size_t k, - const MatType& xs, - const data::DatasetInfo& datasetInfo, - const PredictionsType& ys, - const size_t numClasses, - const WeightsType& weights, - const bool shuffle = true); - - /** - * Run k-fold cross-validation. - * - * @param args Arguments for MLAlgorithm (in addition to the passed - * ones in the constructor). - */ - template - double Evaluate(const MLAlgorithmArgs& ...args); - - //! Access and modify a model from the last run of k-fold cross-validation. - MLAlgorithm& Model(); - - private: - //! A short alias for CVBase. - using Base = CVBase; - - public: - /** - * Shuffle the data. This overload is called if weights are not supported by - * the model type. - */ - template::type> - void Shuffle(); - - /** - * Shuffle the data. This overload is called if weights are supported by the - * model type. - */ - template::type, - typename = void> - void Shuffle(); - - private: - //! An auxiliary object. - Base base; - - //! The number of bins in the dataset. - const size_t k; - - //! The extended (by repeating the first k - 2 bins) data points. - MatType xs; - //! The extended (by repeating the first k - 2 bins) predictions. - PredictionsType ys; - //! The extended (by repeating the first k - 2 bins) weights. - WeightsType weights; - - //! The original size of the dataset. - size_t lastBinSize; - - //! The size of each bin in terms of data points. - size_t binSize; - - //! A pointer to a model from the last run of k-fold cross-validation. - std::unique_ptr modelPtr; - - /** - * Assert the k parameter and data consistency and initialize fields required - * for running k-fold cross-validation. - */ - KFoldCV(Base&& base, - const size_t k, - const MatType& xs, - const PredictionsType& ys, - const bool shuffle); - - /** - * Assert the k parameter and data consistency and initialize fields required - * for running k-fold cross-validation in the case of weighted learning. - */ - KFoldCV(Base&& base, - const size_t k, - const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const bool shuffle); - - /** - * Initialize the given destination matrix with the given source joined with - * its first k - 2 bins. - */ - template - void InitKFoldCVMat(const DataType& source, DataType& destination); - - /** - * Train and run evaluation in the case of non-weighted learning. - */ - template::type> - double TrainAndEvaluate(const MLAlgorithmArgs& ...mlAlgorithmArgs); - - /** - * Train and run evaluation in the case of supporting weighted learning. - */ - template::type, - typename = void> - double TrainAndEvaluate(const MLAlgorithmArgs& ...mlAlgorithmArgs); - - /** - * Calculate the index of the first column of the ith validation subset. - * - * We take the ith validation subset after the ith training subset if - * i < k - 1 and before it otherwise. - */ - inline size_t ValidationSubsetFirstCol(const size_t i); - - /** - * Get the ith training subset from a variable of a matrix type. - */ - template - inline arma::Mat GetTrainingSubset(arma::Mat& m, - const size_t i); - - /** - * Get the ith training subset from a variable of a row type. - */ - template - inline arma::Row GetTrainingSubset(arma::Row& r, - const size_t i); - - /** - * Get the ith validation subset from a variable of a matrix type. - */ - template - inline arma::Mat GetValidationSubset(arma::Mat& m, - const size_t i); - - /** - * Get the ith validation subset from a variable of a row type. - */ - template - inline arma::Row GetValidationSubset(arma::Row& r, - const size_t i); -}; - -} // namespace cv -} // namespace mlpack - -// Include implementation -#include "k_fold_cv_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/k_fold_cv_impl.hpp b/src/sdk/mlpack/include/mlpack/core/cv/k_fold_cv_impl.hpp deleted file mode 100644 index cdd2f9748..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/k_fold_cv_impl.hpp +++ /dev/null @@ -1,447 +0,0 @@ -/** - * @file simple_cv_impl.hpp - * @author Kirill Mishchenko - * - * The implementation of k-fold cross-validation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_K_FOLD_CV_IMPL_HPP -#define MLPACK_CORE_CV_K_FOLD_CV_IMPL_HPP - -namespace mlpack { -namespace cv { - -template -KFoldCV::KFoldCV(const size_t k, - const MatType& xs, - const PredictionsType& ys, - const bool shuffle) : - KFoldCV(Base(), k, xs, ys, shuffle) -{ /* Nothing left to do. */ } - -template -KFoldCV::KFoldCV(const size_t k, - const MatType& xs, - const PredictionsType& ys, - const size_t numClasses, - const bool shuffle) : - KFoldCV(Base(numClasses), k, xs, ys, shuffle) -{ /* Nothing left to do. */ } - -template -KFoldCV::KFoldCV(const size_t k, - const MatType& xs, - const data::DatasetInfo& datasetInfo, - const PredictionsType& ys, - const size_t numClasses, - const bool shuffle) : - KFoldCV(Base(datasetInfo, numClasses), k, xs, ys, shuffle) -{ /* Nothing left to do. */ } - -template -KFoldCV::KFoldCV(const size_t k, - const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const bool shuffle) : - KFoldCV(Base(), k, xs, ys, weights, shuffle) -{ /* Nothing left to do. */ } - -template -KFoldCV::KFoldCV(const size_t k, - const MatType& xs, - const PredictionsType& ys, - const size_t numClasses, - const WeightsType& weights, - const bool shuffle) : - KFoldCV(Base(numClasses), k, xs, ys, weights, shuffle) -{ /* Nothing left to do. */ } - -template -KFoldCV::KFoldCV(const size_t k, - const MatType& xs, - const data::DatasetInfo& datasetInfo, - const PredictionsType& ys, - const size_t numClasses, - const WeightsType& weights, - const bool shuffle) : - KFoldCV(Base(datasetInfo, numClasses), k, xs, ys, weights, shuffle) -{ /* Nothing left to do. */ } - -template -KFoldCV::KFoldCV(Base&& base, - const size_t k, - const MatType& xs, - const PredictionsType& ys, - const bool shuffle) : - base(std::move(base)), - k(k) -{ - if (k < 2) - throw std::invalid_argument("KFoldCV: k should not be less than 2"); - - Base::AssertDataConsistency(xs, ys); - - InitKFoldCVMat(xs, this->xs); - InitKFoldCVMat(ys, this->ys); - - // Do we need to shuffle the dataset? - if (shuffle) - Shuffle(); -} - -template -KFoldCV::KFoldCV(Base&& base, - const size_t k, - const MatType& xs, - const PredictionsType& ys, - const WeightsType& weights, - const bool shuffle) : - base(std::move(base)), - k(k) -{ - Base::AssertWeightsConsistency(xs, weights); - - InitKFoldCVMat(xs, this->xs); - InitKFoldCVMat(ys, this->ys); - InitKFoldCVMat(weights, this->weights); - - // Do we need to shuffle the dataset? - if (shuffle) - Shuffle(); -} - -template -template -double KFoldCV::Evaluate(const MLAlgorithmArgs&... args) -{ - return TrainAndEvaluate(args...); -} - -template -MLAlgorithm& KFoldCV::Model() -{ - if (modelPtr == nullptr) - throw std::logic_error( - "KFoldCV::Model(): attempted to access an uninitialized model"); - - return *modelPtr; -} - -template -template -void KFoldCV::InitKFoldCVMat(const DataType& source, - DataType& destination) -{ - binSize = source.n_cols / k; - lastBinSize = source.n_cols - ((k - 1) * binSize); - - destination = (k == 2) ? source : arma::join_rows(source, - source.cols(0, source.n_cols - lastBinSize - 1)); -} - -template -template -double KFoldCV::TrainAndEvaluate(const MLAlgorithmArgs&... args) -{ - arma::vec evaluations(k); - - for (size_t i = 0; i < k; ++i) - { - MLAlgorithm&& model = base.Train(GetTrainingSubset(xs, i), - GetTrainingSubset(ys, i), args...); - evaluations(i) = Metric::Evaluate(model, GetValidationSubset(xs, i), - GetValidationSubset(ys, i)); - if (i == k - 1) - modelPtr.reset(new MLAlgorithm(std::move(model))); - } - - return arma::mean(evaluations); -} - -template -template -double KFoldCV::TrainAndEvaluate(const MLAlgorithmArgs&... args) -{ - arma::vec evaluations(k); - - for (size_t i = 0; i < k; ++i) - { - MLAlgorithm&& model = (weights.n_elem > 0) ? - base.Train(GetTrainingSubset(xs, i), GetTrainingSubset(ys, i), - GetTrainingSubset(weights, i), args...) : - base.Train(GetTrainingSubset(xs, i), GetTrainingSubset(ys, i), - args...); - evaluations(i) = Metric::Evaluate(model, GetValidationSubset(xs, i), - GetValidationSubset(ys, i)); - if (i == k - 1) - modelPtr.reset(new MLAlgorithm(std::move(model))); - } - - return arma::mean(evaluations); -} - -template -template -void KFoldCV::Shuffle() -{ - MatType xsOrig = xs.cols(0, (k - 1) * binSize + lastBinSize - 1); - PredictionsType ysOrig = ys.cols(0, (k - 1) * binSize + lastBinSize - 1); - - // Now shuffle the data. - math::ShuffleData(xsOrig, ysOrig, xsOrig, ysOrig); - - InitKFoldCVMat(xsOrig, xs); - InitKFoldCVMat(ysOrig, ys); -} - -template -template -void KFoldCV::Shuffle() -{ - MatType xsOrig = xs.cols(0, (k - 1) * binSize + lastBinSize - 1); - PredictionsType ysOrig = ys.cols(0, (k - 1) * binSize + lastBinSize - 1); - WeightsType weightsOrig; - if (weights.n_elem > 0) - weightsOrig = weights.cols(0, (k - 1) * binSize + lastBinSize - 1); - - // Now shuffle the data. - if (weights.n_elem > 0) - math::ShuffleData(xsOrig, ysOrig, weightsOrig, xsOrig, ysOrig, weightsOrig); - else - math::ShuffleData(xsOrig, ysOrig, xsOrig, ysOrig); - - InitKFoldCVMat(xsOrig, xs); - InitKFoldCVMat(ysOrig, ys); - if (weights.n_elem > 0) - InitKFoldCVMat(weightsOrig, weights); -} - -template -size_t KFoldCV::ValidationSubsetFirstCol(const size_t i) -{ - // Use as close to the beginning of the dataset as we can. - return (i == 0) ? binSize * (k - 1) : binSize * (i - 1); -} - -template -template -arma::Mat KFoldCV::GetTrainingSubset( - arma::Mat& m, - const size_t i) -{ - // If this is not the first fold, we have to handle it a little bit - // differently, since the last fold may contain slightly more than 'binSize' - // points. - const size_t subsetSize = (i != 0) ? lastBinSize + (k - 2) * binSize : - (k - 1) * binSize; - - return arma::Mat(m.colptr(binSize * i), m.n_rows, subsetSize, - false, true); -} - -template -template -arma::Row KFoldCV::GetTrainingSubset( - arma::Row& r, - const size_t i) -{ - // If this is not the first fold, we have to handle it a little bit - // differently, since the last fold may contain slightly more than 'binSize' - // points. - const size_t subsetSize = (i != 0) ? lastBinSize + (k - 2) * binSize : - (k - 1) * binSize; - - return arma::Row(r.colptr(binSize * i), subsetSize, false, true); -} - -template -template -arma::Mat KFoldCV::GetValidationSubset( - arma::Mat& m, - const size_t i) -{ - const size_t subsetSize = (i == 0) ? lastBinSize : binSize; - return arma::Mat(m.colptr(ValidationSubsetFirstCol(i)), m.n_rows, - subsetSize, false, true); -} - -template -template -arma::Row KFoldCV::GetValidationSubset( - arma::Row& r, - const size_t i) -{ - const size_t subsetSize = (i == 0) ? lastBinSize : binSize; - return arma::Row(r.colptr(ValidationSubsetFirstCol(i)), - subsetSize, false, true); -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/meta_info_extractor.hpp b/src/sdk/mlpack/include/mlpack/core/cv/meta_info_extractor.hpp deleted file mode 100644 index 5675f94e6..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/meta_info_extractor.hpp +++ /dev/null @@ -1,260 +0,0 @@ -/** - * @file meta_info_extractor.hpp - * @author Kirill Mishchenko - * - * Tools for extracting meta information about machine learning algorithms. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_META_INFO_EXTRACTOR_HPP -#define MLPACK_CORE_CV_META_INFO_EXTRACTOR_HPP - -#include - -#include -#include - -namespace mlpack { -namespace cv { - -/** - * A wrapper struct for holding a Train form. - * - * @tparam MatType The type of data. - * @tparam PredictionsType The type of predictions. - * @tparam WeightsType The type of weights. - * @tparam DatasetInfo An indicator whether a data::DatasetInfo parameter should - * be present. - * @tparam NumClasses An indicator whether the numClasses parameter should be - * present. - */ -template -struct TrainForm; - -template -struct TrainFormBase -{ - using PredictionsType = PT; - using WeightsType = WT; - - /* A minimum number of parameters that should be inferred */ - static const size_t MinNumberOfAdditionalArgs = 1; - - template - using Type = RT(Class::*)(SignatureParams..., Ts...); -}; - -template -struct TrainForm : public TrainFormBase {}; - -template -struct TrainForm : public TrainFormBase {}; - -template -struct TrainForm : public TrainFormBase {}; - -template -struct TrainForm : public TrainFormBase {}; - -template -struct TrainForm : public TrainFormBase {}; - -template -struct TrainForm : public TrainFormBase {}; - -template -struct TrainForm : public TrainFormBase {}; - -template -struct TrainForm : public TrainFormBase {}; - -/* A struct for indication that a right method form can't be found */ -struct NotFoundMethodForm -{ - using PredictionsType = void*; - using WeightsType = void*; -}; - -/** - * A type function that selects a right method form. As parameters it takes a - * machine learning algorithm, a set of HasMethodForm structs, and a set of - * method forms. Method forms are passed to the internal struct From. The result - * type can be accessed through the Type member of the From struct. - * - * The implementation basically loops through all combinations of the - * HasMethodForm structs and the method forms. It stops when a right - * combination succeeds, or when there are no more combinations. - */ -template class, size_t> class... HMFs> -struct SelectMethodForm; - -template class, size_t> class HasMethodForm, - template class, size_t> class... HMFs> -struct SelectMethodForm -{ - template - class From - { - /* Declaration and definition of Implementation for the case when - * RemainingForms are empty */ - template - struct Implementation - { - using NextSMF = SelectMethodForm; - using Type = typename NextSMF::template From::Type; - }; - - /* The case when there is at least one remaining form */ - template - struct Implementation - { - using Type = typename std::conditional< - HasMethodForm::value, - Form, - typename Implementation::Type>::type; - }; - - public: - using Type = typename Implementation::Type; - }; -}; - -template -struct SelectMethodForm -{ - template - struct From - { - using Type = NotFoundMethodForm; - }; -}; - -/** - * MetaInfoExtractor is a tool for extracting meta information about a given - * machine learning algorithm. It can be used to automatically extract the type - * of predictions and weights (if weighted learning is supported), whether the - * machine learning algorithm takes a DatasetInfo parameter or a numClasses - * parameter. - * - * The following assumptions are made about the machine learning algorithm. - * 1. All needed information can be extracted from signatures of Train methods. - * 2. The machine learning algorithm contains either only non-templated Train - * methods or only templated ones. - * 3. Train methods that can be used for extraction of needed information should - * be distinguishable by a number of arguments (for more information read - * discussion in https://github.com/mlpack/mlpack/issues/929). - * 4. If weighted learning is supported, passing weights is an option rather - * than a requirement. - * - * @tparam MLAlgorithm A machine learning algorithm to investigate. - * @tparam MT The type of data. - * @tparam PT The type of predictions (should be passed when the - * predictions type is a template parameter in Train methods of MLAlgorithm). - * @tparam WT The type of weights (should be passed when weighted learning is - * supported, and the weights type is a template parameter in Train methods of - * MLAlgorithm). - */ -template, - typename WT = arma::rowvec> -class MetaInfoExtractor -{ - /* Defining type functions that check presence of Train methods of a given - * form. Defining such functions for templated and non-templated Train - * methods. */ - HAS_METHOD_FORM(Train, HasTrain); - HAS_METHOD_FORM(template Train<>, HasTTrain); - HAS_METHOD_FORM(template Train, HasMTrain); - HAS_METHOD_FORM(SINGLE_ARG(template Train), HasMPTrain); - HAS_METHOD_FORM(SINGLE_ARG(template Train), - HasMPWTrain); - - /* Forms of Train for regression algorithms */ - using TF1 = TrainForm; - using TF2 = TrainForm; - using TF3 = TrainForm; - - /* Forms of Train for classification algorithms */ - using TF4 = TrainForm; - using TF5 = TrainForm; - - /* Forms of Train with weights for regression algorithms */ - using WTF1 = TrainForm; - using WTF2 = TrainForm; - using WTF3 = TrainForm; - - /* Forms of Train with weights for classification algorithms */ - using WTF4 = TrainForm; - using WTF5 = TrainForm; - - /* A short alias for a type function that selects a right method form */ - template - using Select = typename SelectMethodForm::template From; - - /* An indication whether a method form is selected */ - template - using Selects = typename std::conditional< - std::is_same::Type, NotFoundMethodForm>::value, - std::false_type, std::true_type>::type; - - public: - /** - * The type of predictions used in MLAlgorithm. It is equal to void* if the - * extraction fails. - */ - using PredictionsType = - typename Select::Type::PredictionsType; - - /** - * The type of weights used in MLAlgorithm. It is equal to void* if the - * extraction fails. - */ - using WeightsType = - typename Select::Type::WeightsType; - - /** - * An indication whether PredictionsType has been identified (i.e. MLAlgorithm - * is supported by MetaInfoExtractor). - */ - static const bool IsSupported = !std::is_same::value; - - /** - * An indication whether MLAlgorithm supports weighted learning. - */ - static const bool SupportsWeights = !std::is_same::value; - - /** - * An indication whether MLAlgorithm takes a data::DatasetInfo parameter. - */ - static const bool TakesDatasetInfo = Selects::value; - - /** - * An indication whether MLAlgorithm takes the numClasses (size_t) parameter. - */ - static const bool TakesNumClasses = Selects::value; -}; - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/accuracy.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/accuracy.hpp deleted file mode 100644 index aff7c5acb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/accuracy.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file accuracy.hpp - * @author Kirill Mishchenko - * - * The accuracy metric. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_ACCURACY_HPP -#define MLPACK_CORE_CV_METRICS_ACCURACY_HPP - -#include - -namespace mlpack { -namespace cv { - -/** - * The Accuracy is a metric of performance for classification algorithms that is - * equal to a proportion of correctly labeled test items among all ones for - * given test items. - */ -class Accuracy -{ - public: - /** - * Run classification and calculate accuracy. - * - * @param model A classification model. - * @param data Column-major data containing test items. - * @param labels Ground truth (correct) labels for the test items. - */ - template - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Information for hyper-parameter tuning code. It indicates that we want - * to maximize the metric. - */ - static const bool NeedsMinimization = false; -}; - -} // namespace cv -} // namespace mlpack - -// Include implementation. -#include "accuracy_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/accuracy_impl.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/accuracy_impl.hpp deleted file mode 100644 index da395384a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/accuracy_impl.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @file accuracy_impl.hpp - * @author Kirill Mishchenko - * - * The implementation of the class Accuracy. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_ACCURACY_IMPL_HPP -#define MLPACK_CORE_CV_METRICS_ACCURACY_IMPL_HPP - -#include - -namespace mlpack { -namespace cv { - -template -double Accuracy::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "Accuracy::Evaluate()"); - - arma::Row predictedLabels; - model.Classify(data, predictedLabels); - size_t amountOfCorrectPredictions = arma::sum(predictedLabels == labels); - - return (double) amountOfCorrectPredictions / labels.n_elem; -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/average_strategy.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/average_strategy.hpp deleted file mode 100644 index 63b7449dd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/average_strategy.hpp +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @file average_strategy.hpp - * @author Kirill Mishchenko - * - * Strategies for averaging. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_AVERAGE_STRATEGY_HPP -#define MLPACK_CORE_CV_METRICS_AVERAGE_STRATEGY_HPP - -namespace mlpack { -namespace cv { - -/** - * This enum declares possible strategies for averaging that can be used in some - * metrics like precision, recall, and F1. - * - * The "Binary" strategy means binary classification is going to be used, and - * there is no need to average. - */ -enum AverageStrategy -{ - Binary, - Micro, - Macro -}; - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/f1.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/f1.hpp deleted file mode 100644 index 3189c02b8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/f1.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file f1.hpp - * @author Kirill Mishchenko - * - * The F1 metric. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_F1_HPP -#define MLPACK_CORE_CV_METRICS_F1_HPP - -#include - -#include -#include - -namespace mlpack { -namespace cv { - -/** - * F1 is a metric of performance for classification algorithms that for binary - * classification is equal to @f$ 2 * precision * recall / (precision + recall) - * @f$. For multiclass classification the F1 metric can be used with the - * following strategies for averaging. - * 1. Micro. The result is calculated by the above formula, but microaveraged - * precision and microaveraged recall are used. - * 2. Macro. F1 is calculated for each class (with values used for calculation - * of macroaveraged precision and macroaveraged recall), and then the F1 values - * are averaged. - * - * In the case of multiclass classification it is assumed that there are - * instances of every label from 0 to max(labels) among input data points. - * - * The returned value for F1 will be zero if both precision and recall turn out - * to be zeros. - * - * @tparam AS An average strategy. - * @tparam PositiveClass In the case of binary classification (AS = Binary) - * positives are assumed to have labels equal to this value. - */ -template -class F1 -{ - public: - /** - * Run classification and calculate F1. - * - * @param model A classification model. - * @param data Column-major data containing test items. - * @param labels Ground truth (correct) labels for the test items. - */ - template - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Information for hyper-parameter tuning code. It indicates that we want - * to maximize the metric. - */ - static const bool NeedsMinimization = false; - - private: - /** - * Run classification and calculate F1 for binary classification. - */ - template> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Run classification and calculate microaveraged F1. - */ - template, - typename = void> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Run classification and calculate macroaveraged F1. - */ - template, - typename = void, - typename = void> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); -}; - -} // namespace cv -} // namespace mlpack - -// Include implementation. -#include "f1_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/f1_impl.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/f1_impl.hpp deleted file mode 100644 index 56407a5ea..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/f1_impl.hpp +++ /dev/null @@ -1,99 +0,0 @@ -/** - * @file f1_impl.hpp - * @author Kirill Mishchenko - * - * Implementation of the class F1. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_F1_IMPL_HPP -#define MLPACK_CORE_CV_METRICS_F1_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace cv { - -template -template -double F1::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - return Evaluate(model, data, labels); -} - -template -template -double F1::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "F1::Evaluate()"); - - arma::Row predictedLabels; - model.Classify(data, predictedLabels); - - size_t tp = arma::sum((labels == PC) % (predictedLabels == PC)); - size_t numberOfPositivePredictions = arma::sum(predictedLabels == PC); - size_t numberOfPositiveClassInstances = arma::sum(labels == PC); - - double precision = double(tp) / numberOfPositivePredictions; - double recall = double(tp) / numberOfPositiveClassInstances; - - return (precision + recall == 0.0) ? 0.0 : - 2.0 * precision * recall / (precision + recall); -} - -template -template -double F1::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "F1::Evaluate()"); - - // Microaveraged F1 is really the same as microaveraged precision and - // microaveraged recall, which are in turn the same as accuracy. - return Accuracy::Evaluate(model, data, labels); -} - -template -template -double F1::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "F1::Evaluate()"); - - arma::Row predictedLabels; - model.Classify(data, predictedLabels); - - size_t numClasses = arma::max(labels) + 1; - - arma::vec f1s = arma::vec(numClasses); - for (size_t c = 0; c < numClasses; ++c) - { - size_t tp = arma::sum((labels == c) % (predictedLabels == c)); - size_t numberOfPositivePredictions = arma::sum(predictedLabels == c); - size_t numberOfClassInstances = arma::sum(labels == c); - - double precision = double(tp) / numberOfPositivePredictions; - double recall = double(tp) / numberOfClassInstances; - f1s(c) = (precision + recall == 0.0) ? 0.0 : - 2.0 * precision * recall / (precision + recall); - } - - return arma::mean(f1s); -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/facilities.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/facilities.hpp deleted file mode 100644 index adb90da2f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/facilities.hpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @file facilities.hpp - * @author Kirill Mishchenko - * - * Functionality that is used more than in one metric. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_FACILITIES_HPP -#define MLPACK_CORE_CV_METRICS_FACILITIES_HPP - -#include - -namespace mlpack { -namespace cv { - -/** - * Assert there is the same number of the given data points and labels. - * - * @param data Column-major data. - * @param labels Labels. - * @param callerDescription A description of the caller that can be used for - * error generation. - */ -template -void AssertSizes(const DataType& data, - const arma::Row& labels, - const std::string& callerDescription) -{ - if (data.n_cols != labels.n_elem) - { - std::ostringstream oss; - oss << callerDescription << ": number of points (" << data.n_cols << ") " - << "does not match number of labels (" << labels.n_elem << ")!" - << std::endl; - throw std::invalid_argument(oss.str()); - } -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/mse.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/mse.hpp deleted file mode 100644 index b913496f8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/mse.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @file mse.hpp - * @author Kirill Mishchenko - * - * The mean squared error (MSE). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_MSE_HPP -#define MLPACK_CORE_CV_METRICS_MSE_HPP - -#include - -namespace mlpack { -namespace cv { - -/** - * The MeanSquaredError is a metric of performance for regression algorithms - * that is equal to the mean squared error between predicted values and ground - * truth (correct) values for given test items. - */ -class MSE -{ - public: - /** - * Run prediction and calculate the mean squared error. - * - * @param model A regression model. - * @param data Column-major data containing test items. - * @param responses Ground truth (correct) target values for the test items, - * should be either a row vector or a column-major matrix. - */ - template - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const ResponsesType& responses); - - /** - * Information for hyper-parameter tuning code. It indicates that we want - * to minimize the measurement. - */ - static const bool NeedsMinimization = true; -}; - -} // namespace cv -} // namespace mlpack - -// Include implementation. -#include "mse_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/mse_impl.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/mse_impl.hpp deleted file mode 100644 index 92180e2b8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/mse_impl.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @file mse_impl.hpp - * @author Kirill Mishchenko - * - * The implementation of the class MSE. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_MSE_IMPL_HPP -#define MLPACK_CORE_CV_METRICS_MSE_IMPL_HPP - -namespace mlpack { -namespace cv { - -template -double MSE::Evaluate(MLAlgorithm& model, - const DataType& data, - const ResponsesType& responses) -{ - if (data.n_cols != responses.n_cols) - { - std::ostringstream oss; - oss << "MSE::Evaluate(): number of points (" << data.n_cols << ") " - << "does not match number of responses (" << responses.n_cols << ")!" - << std::endl; - throw std::invalid_argument(oss.str()); - } - - ResponsesType predictedResponses; - model.Predict(data, predictedResponses); - double sum = arma::accu(arma::square(responses - predictedResponses)); - - return sum / responses.n_elem; -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/precision.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/precision.hpp deleted file mode 100644 index 305a36524..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/precision.hpp +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @file precision.hpp - * @author Kirill Mishchenko - * - * The precision metric. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_PRECISION_HPP -#define MLPACK_CORE_CV_METRICS_PRECISION_HPP - -#include -#include - -namespace mlpack { -namespace cv { - -/** - * Precision is a metric of performance for classification algorithms that for - * binary classification is equal to @f$ tp / (tp + fp) @f$, where @f$ tp @f$ - * and @f$ fp @f$ are the numbers of true positives and false positives - * respectively. For multiclass classification the precision metric can be used - * with the following strategies for averaging. - * 1. Micro. If there are @f$ N + 1 @f$ classes in total, the result is equal to - * @f[ - * (tp_0 + tp_1 + \ldots + tp_N) / (tp_0 + tp_1 + \ldots + tp_N + fp_0 + fp_1 + - * \ldots + fp_N), - * @f] - * where @f$ tp_i @f$ and @f$ fp_i @f$ are the numbers of true - * positives and false positives respectively for the class (label) @f$ i @f$. - * 2. Macro. If there are @f$ N + 1 @f$ classes in total, the result is equal to - * the mean of the values - * @f[ - * tp_0 / (tp_0 + fp_0), tp_1 / (tp_1 + fp_1), \ldots, tp_N / (tp_N + fp_N), - * @f] - * where @f$ tp_i @f$ and @f$ fp_i @f$ are the - * numbers of true positives and false positives respectively for the class - * (label) @f$ i @f$. - * - * @tparam AS An average strategy. - * @tparam PositiveClass In the case of binary classification (AS = Binary) - * positives are assumed to have labels equal to this value. - */ -template -class Precision -{ - public: - /** - * Run classification and calculate precision. - * - * @param model A classification model. - * @param data Column-major data containing test items. - * @param labels Ground truth (correct) labels for the test items. - */ - template - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Information for hyper-parameter tuning code. It indicates that we want - * to maximize the metric. - */ - static const bool NeedsMinimization = false; - - private: - /** - * Run classification and calculate precision for binary classification. - */ - template> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Run classification and calculate microaveraged precision. - */ - template, - typename = void> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Run classification and calculate macroaveraged precision. - */ - template, - typename = void, - typename = void> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); -}; - -} // namespace cv -} // namespace mlpack - -// Include implementation. -#include "precision_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/precision_impl.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/precision_impl.hpp deleted file mode 100644 index a19a2f439..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/precision_impl.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file precision_impl.hpp - * @author Kirill Mishchenko - * - * Implementation of the class Precision. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_PRECISION_IMPL_HPP -#define MLPACK_CORE_CV_METRICS_PRECISION_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace cv { - -template -template -double Precision::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - return Evaluate(model, data, labels); -} - -template -template -double Precision::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "Precision::Evaluate()"); - - arma::Row predictedLabels; - model.Classify(data, predictedLabels); - - size_t tp = arma::sum((labels == PC) % (predictedLabels == PC)); - size_t numberOfPositivePredictions = arma::sum(predictedLabels == PC); - - return double(tp) / numberOfPositivePredictions; -} - -template -template -double Precision::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "Precision::Evaluate()"); - - // Microaveraged precision turns out to be just accuracy. - return Accuracy::Evaluate(model, data, labels); -} - -template -template -double Precision::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "Precision::Evaluate()"); - - arma::Row predictedLabels; - model.Classify(data, predictedLabels); - - size_t numClasses = arma::max(labels) + 1; - - arma::vec precisions = arma::vec(numClasses); - for (size_t c = 0; c < numClasses; ++c) - { - size_t tp = arma::sum((labels == c) % (predictedLabels == c)); - size_t numberOfPositivePredictions = arma::sum(predictedLabels == c); - precisions(c) = double(tp) / numberOfPositivePredictions; - } - - return arma::mean(precisions); -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/recall.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/recall.hpp deleted file mode 100644 index e95d739d7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/recall.hpp +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @file recall.hpp - * @author Kirill Mishchenko - * - * The recall metric. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_RECALL_HPP -#define MLPACK_CORE_CV_METRICS_RECALL_HPP - -#include -#include - -namespace mlpack { -namespace cv { - -/** - * Recall is a metric of performance for classification algorithms that for - * binary classification is equal to @f$ tp / (tp + fn) @f$, where @f$ tp @f$ - * and @f$ fn @f$ are the numbers of true positives and false negatives - * respectively. For multiclass classification the recall metric can be used - * with the following strategies for averaging. - * 1. Micro. If there are @f$ N + 1 @f$ classes in total, the result is equal to - * @f[ - * (tp_0 + tp_1 + \ldots + tp_N) / (tp_0 + tp_1 + \ldots + tp_N + fn_0 + fn_1 + - * \ldots + fn_N), - * @f] - * where @f$ tp_i @f$ and @f$ fn_i @f$ are the numbers of true - * positives and false negatives respectively for the class (label) @f$ i @f$. - * 2. Macro. If there are @f$ N + 1 @f$ classes in total, the result is equal to - * the mean of the values - * @f[ - * tp_0 / (tp_0 + fn_0), tp_1 / (tp_1 + fn_1), \ldots, tp_N / (tp_N + fn_N), - * @f] - * where @f$ tp_i @f$ and @f$ fn_i @f$ are the - * numbers of true positives and false negatives respectively for the class - * (label) @f$ i @f$. - * - * @tparam AS An average strategy. - * @tparam PositiveClass In the case of binary classification (AS = Binary) - * positives are assumed to have labels equal to this value. - */ -template -class Recall -{ - public: - /** - * Run classification and calculate recall. - * - * @param model A classification model. - * @param data Column-major data containing test items. - * @param labels Ground truth (correct) labels for the test items. - */ - template - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Information for hyper-parameter tuning code. It indicates that we want - * to maximize the metric. - */ - static const bool NeedsMinimization = false; - - private: - /** - * Run classification and calculate recall for binary classification. - */ - template> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Run classification and calculate microaveraged recall. - */ - template, - typename = void> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); - - /** - * Run classification and calculate macroaveraged recall. - */ - template, - typename = void, - typename = void> - static double Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels); -}; - -} // namespace cv -} // namespace mlpack - -// Include implementation. -#include "recall_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/metrics/recall_impl.hpp b/src/sdk/mlpack/include/mlpack/core/cv/metrics/recall_impl.hpp deleted file mode 100644 index 84f2e9d15..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/metrics/recall_impl.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file recall_impl.hpp - * @author Kirill Mishchenko - * - * Implementation of the class Recall. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_METRICS_RECALL_IMPL_HPP -#define MLPACK_CORE_CV_METRICS_RECALL_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace cv { - -template -template -double Recall::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - return Evaluate(model, data, labels); -} - -template -template -double Recall::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "Recall::Evaluate()"); - - arma::Row predictedLabels; - model.Classify(data, predictedLabels); - - size_t tp = arma::sum((labels == PC) % (predictedLabels == PC)); - size_t numberOfPositiveClassInstances = arma::sum(labels == PC); - - return double(tp) / numberOfPositiveClassInstances; -} - -template -template -double Recall::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "Recall::Evaluate()"); - - // Microaveraged recall is really the same as accuracy. - return Accuracy::Evaluate(model, data, labels); -} - -template -template -double Recall::Evaluate(MLAlgorithm& model, - const DataType& data, - const arma::Row& labels) -{ - AssertSizes(data, labels, "Recall::Evaluate()"); - - arma::Row predictedLabels; - model.Classify(data, predictedLabels); - - size_t numClasses = arma::max(labels) + 1; - - arma::vec recalls = arma::vec(numClasses); - for (size_t c = 0; c < numClasses; ++c) - { - size_t tp = arma::sum((labels == c) % (predictedLabels == c)); - size_t numberOfClassInstances = arma::sum(labels == c); - recalls(c) = double(tp) / numberOfClassInstances; - } - - return arma::mean(recalls); -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/simple_cv.hpp b/src/sdk/mlpack/include/mlpack/core/cv/simple_cv.hpp deleted file mode 100644 index d771c7b8b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/simple_cv.hpp +++ /dev/null @@ -1,312 +0,0 @@ -/** - * @file simple_cv.hpp - * @author Kirill Mishchenko - * - * A simple cross-validation strategy. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_SIMPLE_CV_HPP -#define MLPACK_CORE_CV_SIMPLE_CV_HPP - -#include -#include - -namespace mlpack { -namespace cv { - -/** - * SimpleCV splits data into two sets - training and validation sets - and then - * runs training on the training set and evaluates performance on the validation - * set. - * - * To construct a SimpleCV object you need to pass the validationSize parameter - * and arguments that specify data. For example, SoftmaxRegression can be - * validated in the following way. - * - * @code - * // 100-point 5-dimensional random dataset. - * arma::mat data = arma::randu(5, 100); - * // Random labels in the [0, 4] interval. - * arma::Row labels = - * arma::randi>(100, arma::distr_param(0, 4)); - * size_t numClasses = 5; - * - * double validationSize = 0.2; - * SimpleCV, Accuracy> cv(validationSize, data, labels, - * numClasses); - * - * double lambda = 0.1; - * double softmaxAccuracy = cv.Evaluate(lambda); - * @endcode - * - * In the example above, 80% of the passed dataset will be used for training, - * and remaining 20% will be used for calculating the accuracy metric. - * - * @tparam MLAlgorithm A machine learning algorithm. - * @tparam Metric A metric to assess the quality of a trained model. - * @tparam MatType The type of data. - * @tparam PredictionsType The type of predictions (should be passed when the - * predictions type is a template parameter in Train methods of the given - * MLAlgorithm; arma::Row will be used otherwise). - * @tparam WeightsType The type of weights (should be passed when weighted - * learning is supported, and the weights type is a template parameter in - * Train methods of the given MLAlgorithm; arma::vec will be used - * otherwise). - */ -template::PredictionsType, - typename WeightsType = - typename MetaInfoExtractor::WeightsType> -class SimpleCV -{ - public: - /** - * This constructor can be used for regression algorithms and for binary - * classification algorithms. - * - * @param validationSize A proportion (between 0 and 1) of data used as a - * validation set. - * @param xs Data points to cross-validate on. - * @param ys Predictions (labels for classification algorithms and responses - * for regression algorithms) for each data point. - * - * @tparam MatInType A type that can be converted to MatType. - * @tparam PredictionsInType A type that can be converted to PredictionsType. - */ - template - SimpleCV(const double validationSize, - MatInType&& xs, - PredictionsInType&& ys); - - /** - * This constructor can be used for multiclass classification algorithms. - * - * @param validationSize A proportion (between 0 and 1) of data used as a - * validation set. - * @param xs Data points to cross-validate on. - * @param ys Labels for each data point. - * @param numClasses Number of classes in the dataset. - * - * @tparam MatInType A type that can be converted to MatType. - * @tparam PredictionsInType A type that can be converted to PredictionsType. - */ - template - SimpleCV(const double validationSize, - MatInType&& xs, - PredictionsInType&& ys, - const size_t numClasses); - - /** - * This constructor can be used for multiclass classification algorithms that - * can take a data::DatasetInfo parameter. - * - * @param validationSize A proportion (between 0 and 1) of data used as a - * validation set. - * @param xs Data points to cross-validate on. - * @param datasetInfo Type information for each dimension of the dataset. - * @param ys Labels for each data point. - * @param numClasses Number of classes in the dataset. - * - * @tparam MatInType A type that can be converted to MatType. - * @tparam PredictionsInType A type that can be converted to PredictionsType. - */ - template - SimpleCV(const double validationSize, - MatInType&& xs, - const data::DatasetInfo& datasetInfo, - PredictionsInType&& ys, - const size_t numClasses); - - /** - * This constructor can be used for regression and binary classification - * algorithms that support weighted learning. - * - * @param validationSize A proportion (between 0 and 1) of data used as a - * validation set. - * @param xs Data points to cross-validate on. - * @param ys Predictions (labels for classification algorithms and responses - * for regression algorithms) for each data point. - * @param weights Observation weights (for boosting). - * - * @tparam MatInType A type that can be converted to MatType. - * @tparam PredictionsInType A type that can be converted to PredictionsType. - * @tparam WeightsInType A type that can be converted to WeightsType. - */ - template - SimpleCV(const double validationSize, - MatInType&& xs, - PredictionsInType&& ys, - WeightsInType&& weights); - - /** - * This constructor can be used for multiclass classification algorithms that - * support weighted learning. - * - * @param validationSize A proportion (between 0 and 1) of data used as a - * validation set. - * @param xs Data points to cross-validate on. - * @param ys Labels for each data point. - * @param numClasses Number of classes in the dataset. - * @param weights Observation weights (for boosting). - * - * @tparam MatInType A type that can be converted to MatType. - * @tparam PredictionsInType A type that can be converted to PredictionsType. - * @tparam WeightsInType A type that can be converted to WeightsType. - */ - template - SimpleCV(const double validationSize, - MatInType&& xs, - PredictionsInType&& ys, - const size_t numClasses, - WeightsInType&& weights); - - /** - * This constructor can be used for multiclass classification algorithms that - * can take a data::DatasetInfo parameter and support weighted learning. - * - * @param validationSize A proportion (between 0 and 1) of data used as a - * validation set. - * @param xs Data points to cross-validate on. - * @param datasetInfo Type information for each dimension of the dataset. - * @param ys Labels for each data point. - * @param numClasses Number of classes in the dataset. - * @param weights Observation weights (for boosting). - * - * @tparam MatInType A type that can be converted to MatType. - * @tparam PredictionsInType A type that can be converted to PredictionsType. - * @tparam WeightsInType A type that can be converted to WeightsType. - */ - template - SimpleCV(const double validationSize, - MatInType&& xs, - const data::DatasetInfo& datasetInfo, - PredictionsInType&& ys, - const size_t numClasses, - WeightsInType&& weights); - - /** - * Train on the training set and assess performance on the validation set by - * using the class Metric. - * - * @param args Arguments for the given MLAlgorithm taken by its constructor - * (in addition to the passed ones in the SimpleCV constructor). - */ - template - double Evaluate(const MLAlgorithmArgs&... args); - - //! Access and modify the last trained model. - MLAlgorithm& Model(); - - private: - //! A short alias for CVBase. - using Base = CVBase; - - //! An auxiliary object. - Base base; - - //! All input data points. - MatType xs; - //! All input predictions. - PredictionsType ys; - //! All input weights (optional). - WeightsType weights; - - //! The training data points. - MatType trainingXs; - //! The training predictions. - PredictionsType trainingYs; - //! The training weights (optional). - WeightsType trainingWeights; - - //! The validation data points. - MatType validationXs; - //! The validation predictions. - PredictionsType validationYs; - - //! The pointer to the last trained model. - std::unique_ptr modelPtr; - - /** - * Assert data consistency and initialize fields required for running - * cross-validation. - */ - template - SimpleCV(Base&& base, - const double validationSize, - MatInType&& xs, - PredictionsInType&& ys); - - /** - * Assert data consistency and initialize fields required for running - * cross-validation in the case of weighted learning. - */ - template - SimpleCV(Base&& base, - const double validationSize, - MatInType&& xs, - PredictionsInType&& ys, - WeightsInType&& weights); - - /** - * Calculate the number of training points and assert it is legitimate. - */ - size_t CalculateAndAssertNumberOfTrainingPoints(const double validationSize); - - /** - * Get the specified submatrix without coping the data. - */ - template - arma::Mat GetSubset(arma::Mat& m, - const size_t firstCol, - const size_t lastCol); - - /** - * Get the specified subrow without coping the data. - */ - template - arma::Row GetSubset(arma::Row& r, - const size_t firstCol, - const size_t lastCol); - - /** - * Train and run evaluation in the case of non-weighted learning. - */ - template::type> - double TrainAndEvaluate(const MLAlgorithmArgs&... args); - - /** - * Train and run evaluation in the case of supporting weighted learning. - */ - template::type, - typename = void> - double TrainAndEvaluate(const MLAlgorithmArgs&... args); -}; - -} // namespace cv -} // namespace mlpack - -// Include implementation -#include "simple_cv_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/cv/simple_cv_impl.hpp b/src/sdk/mlpack/include/mlpack/core/cv/simple_cv_impl.hpp deleted file mode 100644 index 946ce6559..000000000 --- a/src/sdk/mlpack/include/mlpack/core/cv/simple_cv_impl.hpp +++ /dev/null @@ -1,326 +0,0 @@ -/** - * @file simple_cv_impl.hpp - * @author Kirill Mishchenko - * - * The implementation of the class SimpleCV. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_CV_SIMPLE_CV_IMPL_HPP -#define MLPACK_CORE_CV_SIMPLE_CV_IMPL_HPP - -namespace mlpack { -namespace cv { - -template -template -SimpleCV::SimpleCV(const double validationSize, - MIT&& xs, - PIT&& ys) : - SimpleCV(Base(), validationSize, std::forward(xs), - std::forward(ys)) -{ /* Nothing left to do. */ } - -template -template -SimpleCV::SimpleCV(const double validationSize, - MIT&& xs, - PIT&& ys, - const size_t numClasses) : - SimpleCV(Base(numClasses), validationSize, std::forward(xs), - std::forward(ys)) -{ /* Nothing left to do. */ } - -template -template -SimpleCV::SimpleCV(const double validationSize, - MIT&& xs, - const data::DatasetInfo& datasetInfo, - PIT&& ys, - const size_t numClasses) : - SimpleCV(Base(datasetInfo, numClasses), validationSize, - std::forward(xs), std::forward(ys)) -{ /* Nothing left to do. */ } - -template -template -SimpleCV::SimpleCV(const double validationSize, - MIT&& xs, - PIT&& ys, - WIT&& weights) : - SimpleCV(Base(), validationSize, std::forward(xs), - std::forward(ys), std::forward(weights)) -{ /* Nothing left to do. */ } - -template -template -SimpleCV::SimpleCV(const double validationSize, - MIT&& xs, - PIT&& ys, - const size_t numClasses, - WIT&& weights) : - SimpleCV(Base(numClasses), validationSize, std::forward(xs), - std::forward(ys), std::forward(weights)) -{ /* Nothing left to do. */ } - -template -template -SimpleCV::SimpleCV(const double validationSize, - MIT&& xs, - const data::DatasetInfo& datasetInfo, - PIT&& ys, - const size_t numClasses, - WIT&& weights) : - SimpleCV(Base(datasetInfo, numClasses), validationSize, - std::forward(xs), std::forward(ys), - std::forward(weights)) -{ /* Nothing left to do. */ } - -template -template -SimpleCV::SimpleCV(Base&& base, - const double validationSize, - MIT&& xs, - PIT&& ys) : - base(std::move(base)), - xs(std::forward(xs)), - ys(std::forward(ys)) -{ - Base::AssertDataConsistency(this->xs, this->ys); - - size_t numberOfTrainingPoints = CalculateAndAssertNumberOfTrainingPoints( - validationSize); - - trainingXs = GetSubset(this->xs, 0, numberOfTrainingPoints - 1); - trainingYs = GetSubset(this->ys, 0, numberOfTrainingPoints - 1); - - validationXs = GetSubset(this->xs, numberOfTrainingPoints, xs.n_cols - 1); - validationYs = GetSubset(this->ys, numberOfTrainingPoints, xs.n_cols - 1); -} - -template -template -SimpleCV::SimpleCV(Base&& base, - const double validationSize, - MIT&& xs, - PIT&& ys, - WIT&& weights) : - SimpleCV(std::move(base), validationSize, std::forward(xs), - std::forward(ys)) -{ - this->weights = std::forward(weights); - - Base::AssertWeightsConsistency(this->xs, this->weights); - - trainingWeights = GetSubset(this->weights, 0, trainingXs.n_cols - 1); -} - -template -template -double SimpleCV::Evaluate(const MLAlgorithmArgs&... args) -{ - return TrainAndEvaluate(args...); -} - -template -MLAlgorithm& SimpleCV::Model() -{ - if (modelPtr == nullptr) - throw std::logic_error( - "SimpleCV::Model(): attempted to access an uninitialized model"); - - return *modelPtr; -} - -template -size_t SimpleCV::CalculateAndAssertNumberOfTrainingPoints( - const double validationSize) -{ - if (validationSize < 0.0 || validationSize > 1.0) - throw std::invalid_argument("SimpleCV: the validationSize parameter should " - "be more than 0 and less than 1"); - - if (xs.n_cols < 2) - throw std::invalid_argument("SimpleCV: 2 or more data points are expected"); - - size_t trainingPoints = round(xs.n_cols * (1.0 - validationSize)); - - if (trainingPoints == 0 || trainingPoints == xs.n_cols) - throw std::invalid_argument("SimpleCV: the validationSize parameter is " - "either too small or too big"); - - return trainingPoints; -} - -template -template -arma::Mat SimpleCV::GetSubset( - arma::Mat& m, - const size_t firstCol, - const size_t lastCol) -{ - return arma::Mat(m.colptr(firstCol), m.n_rows, - lastCol - firstCol + 1, false, true); -} - -template -template -arma::Row SimpleCV::GetSubset( - arma::Row& r, - const size_t firstCol, - const size_t lastCol) -{ - return arma::Row(r.colptr(firstCol), lastCol - firstCol + 1, - false, true); -} - -template -template -double SimpleCV::TrainAndEvaluate(const MLAlgorithmArgs&... args) -{ - modelPtr.reset(new MLAlgorithm(base.Train(trainingXs, trainingYs, args...))); - - return Metric::Evaluate(*modelPtr, validationXs, validationYs); -} - -template -template -double SimpleCV::TrainAndEvaluate(const MLAlgorithmArgs&... args) -{ - if (trainingWeights.n_elem > 0) - modelPtr.reset(new MLAlgorithm( - base.Train(trainingXs, trainingYs, trainingWeights, args...))); - else - modelPtr.reset(new MLAlgorithm( - base.Train(trainingXs, trainingYs, args...))); - - return Metric::Evaluate(*modelPtr, validationXs, validationYs); -} - -} // namespace cv -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/binarize.hpp b/src/sdk/mlpack/include/mlpack/core/data/binarize.hpp deleted file mode 100644 index c5917b257..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/binarize.hpp +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @file binarize.hpp - * @author Keon Kim - * - * Defines Binarize(), a utility function, sets values to 0 or 1 - * to a given threshold. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_BINARIZE_HPP -#define MLPACK_CORE_DATA_BINARIZE_HPP - -#include - -namespace mlpack { -namespace data { - -/** - * Given an input dataset and threshold, set values greater than threshold to - * 1 and values less than or equal to the threshold to 0. This overload applies - * the changes to all dimensions. - * - * @code - * arma::Mat input = loadData(); - * arma::Mat output; - * double threshold = 0.5; - * - * // Binarize the whole Matrix. All positive values in will be set to 1 and - * // the values less than or equal to 0.5 will become 0. - * Binarize(input, output, threshold); - * @endcode - * - * @param input Input matrix to Binarize. - * @param output Matrix you want to save binarized data into. - * @param threshold Threshold can by any number. - */ -template -void Binarize(const arma::Mat& input, - arma::Mat& output, - const double threshold) -{ - output.copy_size(input); - - const T *inPtr = input.memptr(); - T *outPtr = output.memptr(); - - #pragma omp parallel for - for (omp_size_t i = 0; i < (omp_size_t) input.n_elem; ++i) - outPtr[i] = inPtr[i] > threshold; -} - -/** - * Given an input dataset and threshold, set values greater than threshold to - * 1 and values less than or equal to the threshold to 0. This overload takes - * a dimension and applys the changes to the given dimension. - * - * @code - * arma::Mat input = loadData(); - * arma::Mat output; - * double threshold = 0.5; - * size_t dimension = 0; - * - * // Binarize the first dimension. All positive values in the first dimension - * // will be set to 1 and the values less than or equal to 0 will become 0. - * Binarize(input, output, threshold, dimension); - * @endcode - * - * @param input Input matrix to Binarize. - * @param output Matrix you want to save binarized data into. - * @param threshold Threshold can by any number. - * @param dimension Feature to apply the Binarize function. - */ -template -void Binarize(const arma::Mat& input, - arma::Mat& output, - const double threshold, - const size_t dimension) -{ - output = input; - - #pragma omp parallel for - for (omp_size_t i = 0; i < (omp_size_t) input.n_cols; ++i) - output(dimension, i) = input(dimension, i) > threshold; -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/dataset_mapper.hpp b/src/sdk/mlpack/include/mlpack/core/data/dataset_mapper.hpp deleted file mode 100644 index 8c0dffde7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/dataset_mapper.hpp +++ /dev/null @@ -1,195 +0,0 @@ -/** - * @file dataset_mapper.hpp - * @author Ryan Curtin - * @author Keon Kim - * - * Defines the DatasetMapper class, which holds information about a dataset. - * This is useful when the dataset contains categorical non-numeric features - * that needs to be mapped to categorical numeric features. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_DATASET_INFO_HPP -#define MLPACK_CORE_DATA_DATASET_INFO_HPP - -#include -#include - -#include "map_policies/increment_policy.hpp" - -namespace mlpack { -namespace data { - -/** - * Auxiliary information for a dataset, including mappings to/from strings (or - * other types) and the datatype of each dimension. DatasetMapper objects are - * optionally produced by data::Load(), and store the type of each dimension - * (Datatype::numeric or Datatype::categorical) as well as mappings from strings - * to unsigned integers and vice versa. - * - * DatasetMapper objects can also map from arbitrary types; the type to map from - * can be specified with the InputType template parameter. By default, the - * InputType parameter is std::string. - * - * @tparam PolicyType Mapping policy used to specify MapString(). - * @tparam InputType Type of input to be mapped. - */ -template -class DatasetMapper -{ - public: - /** - * Create the DatasetMapper object with the given dimensionality. Note that - * the dimensionality cannot be changed later; you will have to create a new - * DatasetMapper object. - */ - explicit DatasetMapper(const size_t dimensionality = 0); - - /** - * Create the DatasetMapper object with the given policy and dimensionality. - * Note that the dimensionality cannot be changed later; you will have to - * create a new DatasetMapper object. Policy can be modified by the modifier. - */ - explicit DatasetMapper(PolicyType& policy, const size_t dimensionality = 0); - - /** - * Preprocessing: during a first pass of the data, pass the input on to the - * MapPolicy if they are needed. - * - * @param input Input to map. - * @param dimension Dimension to map for. - */ - template - void MapFirstPass(const InputType& input, const size_t dimension); - - /** - * Given the input and the dimension to which it belongs, return its numeric - * mapping. If no mapping yet exists, the input is added to the list of - * mappings for the given dimension. The dimension parameter refers to the - * index of the dimension of the string (i.e. the row in the dataset). - * - * @tparam T Numeric type to map to (int/double/float/etc.). - * @param input Input to find/create mapping for. - * @param dimension Index of the dimension of the string. - */ - template - T MapString(const InputType& input, - const size_t dimension); - - /** - * Return the input that corresponds to a given value in a given dimension. - * If the value is not a valid mapping in the given dimension, a - * std::invalid_argument is thrown. Note that this does not remove the - * mapping. - * - * If the mapping is non-unique (i.e. many strings can map to the same value), - * then you can pass a different value for unmappingIndex to get a different - * string that maps to the given value. unmappingIndex should be in the range - * from 0 to (NumUnmappings(value, dimension) - 1). - * - * If the mapping is unique (which it is for DatasetInfo), then the - * unmappingIndex parameter can be left as the default. - * - * @param value Mapped value for input. - * @param dimension Dimension to unmap string from. - * @param unmappingIndex Index of non-unique unmapping (optional). - */ - template - const InputType& UnmapString(const T value, - const size_t dimension, - const size_t unmappingIndex = 0) const; - - /** - * Get the number of possible unmappings for a string in a given dimension. - */ - template - size_t NumUnmappings(const T value, const size_t dimension) const; - - /** - * Return the value that corresponds to a given input in a given dimension. - * If the value is not a valid mapping in the given dimension, a - * std::invalid_argument is thrown. Note that this does not remove the - * mapping. - * - * @param input Mapped input for value. - * @param dimension Dimension to unmap input from. - */ - typename PolicyType::MappedType UnmapValue(const InputType& input, - const size_t dimension); - - //! Return the type of a given dimension (numeric or categorical). - Datatype Type(const size_t dimension) const; - //! Modify the type of a given dimension (be careful!). - Datatype& Type(const size_t dimension); - - /** - * Get the number of mappings for a particular dimension. If the dimension - * is numeric, then this will return 0. - */ - size_t NumMappings(const size_t dimension) const; - - /** - * Get the dimensionality of the DatasetMapper object (that is, how many - * dimensions it has information for). If this object was created by a call - * to mlpack::data::Load(), then the dimensionality will be the same as the - * number of rows (dimensions) in the dataset. - */ - size_t Dimensionality() const; - - /** - * Serialize the dataset information. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(types); - ar & BOOST_SERIALIZATION_NVP(maps); - } - - //! Return the policy of the mapper. - const PolicyType& Policy() const; - - //! Modify the policy of the mapper (be careful!). - PolicyType& Policy(); - //! Modify (Replace) the policy of the mapper with a new policy. - void Policy(PolicyType&& policy); - - private: - //! Types of each dimension. - std::vector types; - - // Forward mapping type. - using ForwardMapType = typename std::unordered_map; - - // Reverse mapping type. Multiple inputs may map to a single output, hence - // the need for std::vector. - using ReverseMapType = std::unordered_map>; - - // Mappings from strings to integers. - // Map entries will only exist for dimensions that are categorical. - // MapType = map, numMappings>> - using MapType = std::unordered_map>; - - //! maps object stores string and numerical pairs. - MapType maps; - - //! policy object tells dataset mapper how the categorical values should be - // mapped to the maps object. It is used in MapString() and MapTokens(). - PolicyType policy; -}; - -// Use typedef to provide backward compatibility -using DatasetInfo = DatasetMapper; - -} // namespace data -} // namespace mlpack - -#include "dataset_mapper_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/dataset_mapper_impl.hpp b/src/sdk/mlpack/include/mlpack/core/data/dataset_mapper_impl.hpp deleted file mode 100644 index 5cd103567..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/dataset_mapper_impl.hpp +++ /dev/null @@ -1,246 +0,0 @@ -/** - * @file dataset_mapper_impl.hpp - * @author Ryan Curtin - * @author Keon Kim - * - * An implementation of the DatasetMapper class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_DATASET_INFO_IMPL_HPP -#define MLPACK_CORE_DATA_DATASET_INFO_IMPL_HPP - -// In case it hasn't already been included. -#include "dataset_mapper.hpp" - -namespace mlpack { -namespace data { - -// Default constructor. -template -inline DatasetMapper::DatasetMapper( - const size_t dimensionality) : - types(dimensionality, Datatype::numeric) -{ - // Nothing to initialize here. -} - -template -inline DatasetMapper::DatasetMapper(PolicyType& policy, - const size_t dimensionality) : - types(dimensionality, Datatype::numeric), - policy(std::move(policy)) -{ - // Nothing to initialize here. -} - -// Utility helper function to call MapFirstPass. -template -void CallMapFirstPass( - PolicyType& policy, - const InputType& input, - const size_t dimension, - std::vector& types, - const typename std::enable_if::type* = 0) -{ - policy.template MapFirstPass(input, dimension, types); -} - -// Utility helper function that doesn't call anything. -template -void CallMapFirstPass( - PolicyType& /* policy */, - const InputType& /* input */, - const size_t /* dimension */, - std::vector& /* types */, - const typename std::enable_if::type* = 0) -{ - // Nothing to do here. -} - -template -template -void DatasetMapper::MapFirstPass(const InputType& input, - const size_t dimension) -{ - // Call the correct overload (via SFINAE). - CallMapFirstPass(policy, input, dimension, types); -} - -// When we want to insert value into the map, we use the policy to map the -// input. -template -template -inline T DatasetMapper::MapString( - const InputType& input, - const size_t dimension) -{ - return policy.template MapString(input, dimension, maps, types); -} - -/** - * A safe version of isnan() that only gets called when the type has a NaN at - * all. This is a workaround for Visual Studio, which doesn't seem to support - * isnan(size_t). - */ -template -inline bool isnanSafe(const T& /* t */) -{ - return false; -} - -template<> -inline bool isnanSafe(const double& t) -{ - return std::isnan(t); -} - -template<> -inline bool isnanSafe(const float& t) -{ - return std::isnan(t); -} - -template<> -inline bool isnanSafe(const long double& t) -{ - return std::isnan(t); -} - - -// Return the input corresponding to a value in a given dimension. -template -template -inline const InputType& DatasetMapper::UnmapString( - const T value, - const size_t dimension, - const size_t unmappingIndex) const -{ - // If the value is std::numeric_limits::quiet_NaN(), we can't use it as a - // key---so we will use something else... - const T usedValue = isnanSafe(value) ? - std::nexttoward(std::numeric_limits::max(), T(0)) : - value; - - // Throw an exception if the value doesn't exist. - if (maps.at(dimension).second.count(usedValue) == 0) - { - std::ostringstream oss; - oss << "DatasetMapper::UnmapString(): value '" - << value << "' unknown for dimension " << dimension; - throw std::invalid_argument(oss.str()); - } - - if (unmappingIndex >= maps.at(dimension).second.at(usedValue).size()) - { - std::ostringstream oss; - oss << "DatasetMapper::UnmapString(): value '" - << value << "' only has " - << maps.at(dimension).second.at(usedValue).size() - << " unmappings, but unmappingIndex is " << unmappingIndex << "!"; - throw std::invalid_argument(oss.str()); - } - - return maps.at(dimension).second.at(usedValue)[unmappingIndex]; -} - -template -template -inline size_t DatasetMapper::NumUnmappings( - const T value, - const size_t dimension) const -{ - // If the value is std::numeric_limits::quiet_NaN(), we can't use it as a - // key---so we will use something else... - if (isnanSafe(value)) - { - const T newValue = std::nexttoward(std::numeric_limits::max(), T(0)); - return maps.at(dimension).second.at(newValue).size(); - } - - return maps.at(dimension).second.at(value).size(); -} - -// Return the value corresponding to an input in a given dimension. -template -inline typename PolicyType::MappedType -DatasetMapper::UnmapValue( - const InputType& input, - const size_t dimension) -{ - // Throw an exception if the value doesn't exist. - if (maps[dimension].first.count(input) == 0) - { - std::ostringstream oss; - oss << "DatasetMapper::UnmapValue(): input '" - << input << "' unknown for dimension " << dimension; - throw std::invalid_argument(oss.str()); - } - - return maps[dimension].first.at(input); -} - -// Get the type of a particular dimension. -template -inline Datatype DatasetMapper::Type( - const size_t dimension) const -{ - if (dimension >= types.size()) - { - std::ostringstream oss; - oss << "requested type of dimension " << dimension << ", but dataset only " - << "has " << types.size() << " dimensions"; - throw std::invalid_argument(oss.str()); - } - - return types[dimension]; -} - -template -inline Datatype& DatasetMapper::Type( - const size_t dimension) -{ - if (dimension >= types.size()) - types.resize(dimension + 1, Datatype::numeric); - - return types[dimension]; -} - -template -inline size_t -DatasetMapper::NumMappings(const size_t dimension) const -{ - return (maps.count(dimension) == 0) ? 0 : maps.at(dimension).first.size(); -} - -template -inline size_t DatasetMapper::Dimensionality() const -{ - return types.size(); -} - -template -inline const PolicyType& DatasetMapper::Policy() const -{ - return this->policy; -} - -template -inline PolicyType& DatasetMapper::Policy() -{ - return this->policy; -} - -template -inline void DatasetMapper::Policy(PolicyType&& policy) -{ - this->policy = std::forward(policy); -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/extension.hpp b/src/sdk/mlpack/include/mlpack/core/data/extension.hpp deleted file mode 100644 index 4bf8b6bf7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/extension.hpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @file extension.hpp - * @author Ryan Curtin - * - * Given a filename, extract its extension. This is used by data::Load() and - * data::Save(). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_EXTENSION_HPP -#define MLPACK_CORE_DATA_EXTENSION_HPP - -#include - -namespace mlpack { -namespace data { - -inline std::string Extension(const std::string& filename) -{ - const size_t ext = filename.rfind('.'); - std::string extension; - if (ext == std::string::npos) - return extension; - - extension = filename.substr(ext + 1); - std::transform(extension.begin(), extension.end(), extension.begin(), - ::tolower); - - return extension; -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/format.hpp b/src/sdk/mlpack/include/mlpack/core/data/format.hpp deleted file mode 100644 index 527e21415..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/format.hpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @file formats.hpp - * @author Ryan Curtin - * - * Define the formats that can be used by mlpack's Load() and Save() mechanisms - * via boost::serialization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_FORMATS_HPP -#define MLPACK_CORE_DATA_FORMATS_HPP - -namespace mlpack { -namespace data { - -//! Define the formats we can read through boost::serialization. -enum format -{ - autodetect, - text, - xml, - binary -}; - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/has_serialize.hpp b/src/sdk/mlpack/include/mlpack/core/data/has_serialize.hpp deleted file mode 100644 index 7ae0fa0e3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/has_serialize.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file has_serialize.hpp - * @author Ryan Curtin - * - * This file contains the HasSerialize struct, which can be used to detect - * whether or not a type is serializable. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_HAS_SERIALIZE_HPP -#define MLPACK_CORE_UTIL_HAS_SERIALIZE_HPP - -#include -#include -#include -#include - -namespace mlpack { -namespace data { - -// This gives us a HasSerializeCheck type (where U is a function pointer) -// we can use with SFINAE to catch when a type has a Serialize() function. -HAS_EXACT_METHOD_FORM(serialize, HasSerializeCheck); - -// Don't call this with a non-class. HasSerializeFunction::value is true if the -// type T has a static or non-static Serialize() function. -template -struct HasSerializeFunction -{ - template - using NonStaticSerialize = void(C::*)(boost::archive::xml_oarchive&, - const unsigned int); - template - using StaticSerialize = void(*)(boost::archive::xml_oarchive&, - const unsigned int); - - static const bool value = HasSerializeCheck::value || - HasSerializeCheck::value; -}; - -template -struct HasSerialize -{ - // We have to handle the case where T isn't a class... - typedef char yes[1]; - typedef char no [2]; - template struct check; - template static yes& chk( // This matches classes. - check::value>*, - typename std::enable_if_t::value>*>*); - template static no& chk(...); // This matches non-classes. - - static const bool value = (sizeof(chk(0)) == sizeof(yes)); -}; - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/custom_imputation.hpp b/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/custom_imputation.hpp deleted file mode 100644 index db2044dcd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/custom_imputation.hpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file custom_imputation.hpp - * @author Keon Kim - * - * Definition and Implementation of the empty CustomImputation class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_IMPUTE_STRATEGIES_CUSTOM_IMPUTATION_HPP -#define MLPACK_CORE_DATA_IMPUTE_STRATEGIES_CUSTOM_IMPUTATION_HPP - -#include - -namespace mlpack { -namespace data { -/** - * A simple custom imputation class - * @tparam T Type of armadillo matrix - */ -template -class CustomImputation -{ - public: - CustomImputation(T customValue): - customValue(std::move(customValue)) - { - // nothing to initialize here - } - - /** - * Impute function searches through the input looking for mappedValue and - * replaces it with the user-defined custom value of the given dimension. - * The result is overwritten to the input, not creating any copy. Custom value - * must be set when initializing the CustomImputation object. - * - * @param input Matrix that contains mappedValue. - * @param mappedValue Value that the user wants to get rid of. - * @param dimension Index of the dimension of the mappedValue. - * @param columnMajor State of whether the input matrix is columnMajor or not. - */ - void Impute(arma::Mat& input, - const T& mappedValue, - const size_t dimension, - const bool columnMajor = true) - { - // replace the target value to custom value - if (columnMajor) - { - for (size_t i = 0; i < input.n_cols; ++i) - { - if (input(dimension, i) == mappedValue || - std::isnan(input(dimension, i))) - { - input(dimension, i) = customValue; - } - } - } - else - { - for (size_t i = 0; i < input.n_rows; ++i) - { - if (input(i, dimension) == mappedValue || - std::isnan(input(i, dimension))) - { - input(i, dimension) = customValue; - } - } - } - } - - private: - //! A user-defined value that the user wants to replace missing values with. - T customValue; -}; // class CustomImputation - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/listwise_deletion.hpp b/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/listwise_deletion.hpp deleted file mode 100644 index fe2a4b335..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/listwise_deletion.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file listwise_deletion.hpp - * @author Keon Kim - * - * Definition and Implementation of the empty ListwiseDeletion class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_IMPUTE_STRATEGIES_LISTWISE_DELETION_HPP -#define MLPACK_CORE_DATA_IMPUTE_STRATEGIES_LISTWISE_DELETION_HPP - -#include - -namespace mlpack { -namespace data { -/** - * A complete-case analysis to remove the values containing mappedValue. - * Removes all data for a case that has one or more missing values. - * @tparam T Type of armadillo matrix - */ -template -class ListwiseDeletion -{ - public: - /** - * Impute function searches through the input looking for mappedValue and - * remove the whole row or column. The result is overwritten to the input. - * - * @param input Matrix that contains mappedValue. - * @param mappedValue Value that the user wants to get rid of. - * @param dimension Index of the dimension of the mappedValue. - * @param columnMajor State of whether the input matrix is columnMajor or not. - */ - void Impute(arma::Mat& input, - const T& mappedValue, - const size_t dimension, - const bool columnMajor = true) - { - std::vector colsToKeep; - - if (columnMajor) - { - for (size_t i = 0; i < input.n_cols; ++i) - { - if (!(input(dimension, i) == mappedValue || - std::isnan(input(dimension, i)))) - { - colsToKeep.push_back(i); - } - } - input = input.cols(arma::uvec(colsToKeep)); - } - else - { - for (size_t i = 0; i < input.n_rows; ++i) - { - if (!(input(i, dimension) == mappedValue || - std::isnan(input(i, dimension)))) - { - colsToKeep.push_back(i); - } - } - input = input.rows(arma::uvec(colsToKeep)); - } - } -}; // class ListwiseDeletion - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/mean_imputation.hpp b/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/mean_imputation.hpp deleted file mode 100644 index dbc600044..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/mean_imputation.hpp +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @file mean_imputation.hpp - * @author Keon Kim - * - * Definition and Implementation of the MeanImputation class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_IMPUTE_STRATEGIES_MEAN_IMPUTATION_HPP -#define MLPACK_CORE_DATA_IMPUTE_STRATEGIES_MEAN_IMPUTATION_HPP - -#include - -namespace mlpack { -namespace data { -/** - * A simple mean imputation class - * @tparam T Type of armadillo matrix - */ -template -class MeanImputation -{ - public: - /** - * Impute function searches through the input looking for mappedValue and - * replaces it with the mean of the given dimension. The result is overwritten - * to the input matrix. - * - * @param input Matrix that contains mappedValue. - * @param mappedValue Value that the user wants to get rid of. - * @param dimension Index of the dimension of the mappedValue. - * @param columnMajor State of whether the input matrix is columnMajor or not. - */ - void Impute(arma::Mat& input, - const T& mappedValue, - const size_t dimension, - const bool columnMajor = true) - { - double sum = 0; - size_t elems = 0; // excluding nan or missing target - - using PairType = std::pair; - // dimensions and indexes are saved as pairs inside this vector. - std::vector targets; - - - // calculate number of elements and sum of them excluding mapped value or - // nan. while doing that, remember where mappedValue or NaN exists. - if (columnMajor) - { - for (size_t i = 0; i < input.n_cols; ++i) - { - if (input(dimension, i) == mappedValue || - std::isnan(input(dimension, i))) - { - targets.emplace_back(dimension, i); - } - else - { - elems++; - sum += input(dimension, i); - } - } - } - else - { - for (size_t i = 0; i < input.n_rows; ++i) - { - if (input(i, dimension) == mappedValue || - std::isnan(input(i, dimension))) - { - targets.emplace_back(i, dimension); - } - else - { - elems++; - sum += input(i, dimension); - } - } - } - - if (elems == 0) - Log::Fatal << "it is impossible to calculate mean; no valid elements in " - << "the dimension" << std::endl; - - // calculate mean; - const double mean = sum / elems; - - // Now replace the calculated mean to the missing variables - // It only needs to loop through targets vector, not the whole matrix. - for (const PairType& target : targets) - { - input(target.first, target.second) = mean; - } - } -}; // class MeanImputation - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/median_imputation.hpp b/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/median_imputation.hpp deleted file mode 100644 index d696de377..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/imputation_methods/median_imputation.hpp +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @file median_imputation.hpp - * @author Keon Kim - * - * Definition and Implementation of the MedianImputation class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_IMPUTE_STRATEGIES_MEDIAN_IMPUTATION_HPP -#define MLPACK_CORE_DATA_IMPUTE_STRATEGIES_MEDIAN_IMPUTATION_HPP - -#include - -namespace mlpack { -namespace data { -/** - * This is a class implementation of simple median imputation. - * replace missing value with middle or average of middle values - * @tparam T Type of armadillo matrix - */ -template -class MedianImputation -{ - public: - /** - * Impute function searches through the input looking for mappedValue and - * replaces it with the median of the given dimension. The result is - * overwritten to the input matrix. - * - * @param input Matrix that contains mappedValue. - * @param mappedValue Value that the user wants to get rid of. - * @param dimension Index of the dimension of the mappedValue. - * @param columnMajor State of whether the input matrix is columnMajor or not. - */ - void Impute(arma::Mat& input, - const T& mappedValue, - const size_t dimension, - const bool columnMajor = true) - { - using PairType = std::pair; - // dimensions and indexes are saved as pairs inside this vector. - std::vector targets; - // good elements are kept inside this vector. - std::vector elemsToKeep; - - if (columnMajor) - { - for (size_t i = 0; i < input.n_cols; ++i) - { - if (input(dimension, i) == mappedValue || - std::isnan(input(dimension, i))) - { - targets.emplace_back(dimension, i); - } - else - { - elemsToKeep.push_back(input(dimension, i)); - } - } - } - else - { - for (size_t i = 0; i < input.n_rows; ++i) - { - if (input(i, dimension) == mappedValue || - std::isnan(input(i, dimension))) - { - targets.emplace_back(i, dimension); - } - else - { - elemsToKeep.push_back(input(i, dimension)); - } - } - } - - // calculate median - const double median = arma::median(arma::vec(elemsToKeep)); - - for (const PairType& target : targets) - { - input(target.first, target.second) = median; - } - } -}; // class MedianImputation - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/imputer.hpp b/src/sdk/mlpack/include/mlpack/core/data/imputer.hpp deleted file mode 100644 index afd7a9095..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/imputer.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file imputer.hpp - * @author Keon Kim - * - * Defines Imputer class a utility function to replace missing variables in a - * dataset. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_IMPUTER_HPP -#define MLPACK_CORE_DATA_IMPUTER_HPP - -#include -#include "dataset_mapper.hpp" -#include "map_policies/missing_policy.hpp" -#include "map_policies/increment_policy.hpp" - -namespace mlpack { -namespace data { - -/** - * Given a dataset of a particular datatype, replace user-specified missing - * value with a variable dependent on the StrategyType and MapperType. - * - * @tparam T Type of armadillo matrix used for imputation strategy. - * @tparam MapperType DatasetMapper that is used to hold dataset information. - * @tparam StrategyType Imputation strategy used. - */ -template -class Imputer -{ - public: - Imputer(MapperType mapper, bool columnMajor = true): - mapper(std::move(mapper)), - columnMajor(columnMajor) - { - // Nothing to initialize here. - } - - Imputer(MapperType mapper, StrategyType strategy, bool columnMajor = true): - strategy(std::move(strategy)), - mapper(std::move(mapper)), - columnMajor(columnMajor) - { - // Nothing to initialize here. - } - - /** - * Given an input dataset, replace missing values of a dimension with given - * imputation strategy. This function does not produce output matrix, but - * overwrites the result into the input matrix. - * - * @param input Input dataset to apply imputation. - * @oaran missingValue User defined missing value; it can be anything. - * @param dimension Dimension to apply the imputation. - */ - void Impute(arma::Mat& input, - const std::string& missingValue, - const size_t dimension) - { - T mappedValue = static_cast(mapper.UnmapValue(missingValue, dimension)); - strategy.Impute(input, mappedValue, dimension, columnMajor); - } - - //! Get the strategy - const StrategyType& Strategy() const { return strategy; } - - //! Modify the given given strategy (be careful!) - StrategyType& Strategy() { return strategy; } - - //! Get the mapper - const MapperType& Mapper() const { return mapper; } - - //! Modify the given mapper (be careful!) - MapperType& Mapper() { return mapper; } - - private: - // StrategyType - StrategyType strategy; - - // DatasetMapperType - MapperType mapper; - - // save columnMajor as a member variable since it is rarely changed. - bool columnMajor; -}; // class Imputer - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/is_naninf.hpp b/src/sdk/mlpack/include/mlpack/core/data/is_naninf.hpp deleted file mode 100644 index b365c9937..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/is_naninf.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file is_naninf.hpp - * @author Ryan Curtin - * - * This is an adapted version of Conrad Sanderson's implementation of - * arma::diskio::convert_naninf() from Armadillo. It is here so as to avoid - * using Armadillo internal functionality. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_HAS_NANINF_HPP -#define MLPACK_CORE_DATA_HAS_NANINF_HPP - -#include - -namespace mlpack { -namespace data { - -/** - * See if the token is a NaN or an Inf, and if so, set the value accordingly and - * return a boolean representing whether or not it is. - */ -template -inline bool IsNaNInf(T& val, const std::string& token) -{ - // See if the token represents a NaN or Inf. - if ((token.length() == 3) || (token.length() == 4)) - { - const bool neg = (token[0] == '-'); - const bool pos = (token[0] == '+'); - - const size_t offset = ((neg || pos) && (token.length() == 4)) ? 1 : 0; - - const std::string token2 = token.substr(offset, 3); - - if ((token2 == "inf") || (token2 == "Inf") || (token2 == "INF")) - { - if (std::numeric_limits::has_infinity) - { - val = (!neg) ? std::numeric_limits::infinity() : - -std::numeric_limits::infinity(); - } - else - { - val = (!neg) ? std::numeric_limits::max() : - -std::numeric_limits::max(); - } - - return true; - } - else if ((token2 == "nan") || (token2 == "Nan") || (token2 == "NaN") || - (token2 == "NAN") ) - { - if (std::numeric_limits::has_quiet_NaN) - val = std::numeric_limits::quiet_NaN(); - else - val = T(0); - - return true; - } - } - - return false; -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/load.hpp b/src/sdk/mlpack/include/mlpack/core/data/load.hpp deleted file mode 100644 index 99a91807e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/load.hpp +++ /dev/null @@ -1,298 +0,0 @@ -/** - * @file load.hpp - * @author Ryan Curtin - * - * Load an Armadillo matrix from file. This is necessary because Armadillo does - * not transpose matrices on input, and it allows us to give better error - * output. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_LOAD_HPP -#define MLPACK_CORE_DATA_LOAD_HPP - -#include -#include -#include - -#include "format.hpp" -#include "dataset_mapper.hpp" - -namespace mlpack { -namespace data /** Functions to load and save matrices and models. */ { - -/** - * Loads a matrix from file, guessing the filetype from the extension. This - * will transpose the matrix at load time (unless the transpose parameter is set - * to false). If the filetype cannot be determined, an error will be given. - * - * The supported types of files are the same as found in Armadillo: - * - * - CSV (csv_ascii), denoted by .csv, or optionally .txt - * - TSV (raw_ascii), denoted by .tsv, .csv, or .txt - * - ASCII (raw_ascii), denoted by .txt - * - Armadillo ASCII (arma_ascii), also denoted by .txt - * - PGM (pgm_binary), denoted by .pgm - * - PPM (ppm_binary), denoted by .ppm - * - Raw binary (raw_binary), denoted by .bin - * - Armadillo binary (arma_binary), denoted by .bin - * - HDF5, denoted by .hdf, .hdf5, .h5, or .he5 - * - * If the file extension is not one of those types, an error will be given. - * This is preferable to Armadillo's default behavior of loading an unknown - * filetype as raw_binary, which can have very confusing effects. - * - * If the parameter 'fatal' is set to true, a std::runtime_error exception will - * be thrown if the matrix does not load successfully. The parameter - * 'transpose' controls whether or not the matrix is transposed after loading. - * In most cases, because data is generally stored in a row-major format and - * mlpack requires column-major matrices, this should be left at its default - * value of 'true'. - * - * @param filename Name of file to load. - * @param matrix Matrix to load contents of file into. - * @param fatal If an error should be reported as fatal (default false). - * @param transpose If true, transpose the matrix after loading. - * @return Boolean value indicating success or failure of load. - */ -template -bool Load(const std::string& filename, - arma::Mat& matrix, - const bool fatal = false, - const bool transpose = true); - -/** - * Don't document these with doxygen; these declarations aren't helpful to - * users. - * - * @cond - */ - -extern template bool Load(const std::string&, - arma::Mat&, - const bool, - const bool); - -// size_t and uword should be one of these three typedefs. -extern template bool Load(const std::string&, - arma::Mat&, - const bool, - const bool); - -extern template bool Load(const std::string&, - arma::Mat&, - const bool, - const bool); - -extern template bool Load(const std::string&, - arma::Mat&, - const bool, - const bool); - -extern template bool Load(const std::string&, - arma::Mat&, - const bool, - const bool); - -extern template bool Load(const std::string&, - arma::Mat&, - const bool, - const bool); - -/** - * @endcond - */ - -/** - * Load a column vector from a file, guessing the filetype from the extension. - * - * The supported types of files are the same as found in Armadillo: - * - * - CSV (csv_ascii), denoted by .csv, or optionally .txt - * - TSV (raw_ascii), denoted by .tsv, .csv, or .txt - * - ASCII (raw_ascii), denoted by .txt - * - Armadillo ASCII (arma_ascii), also denoted by .txt - * - PGM (pgm_binary), denoted by .pgm - * - PPM (ppm_binary), denoted by .ppm - * - Raw binary (raw_binary), denoted by .bin - * - Armadillo binary (arma_binary), denoted by .bin - * - HDF5, denoted by .hdf, .hdf5, .h5, or .he5 - * - * If the file extension is not one of those types, an error will be given. - * This is preferable to Armadillo's default behavior of loading an unknown - * filetype as raw_binary, which can have very confusing effects. - * - * If the parameter 'fatal' is set to true, a std::runtime_error exception will - * be thrown if the matrix does not load successfully. - * - * @param filename Name of file to load. - * @param colvec Column vector to load contents of file into. - * @param fatal If an error should be reported as fatal (default false). - * @return Boolean value indicating success or failure of load. - */ -template -bool Load(const std::string& filename, - arma::Col& vec, - const bool fatal = false); - -/** - * Load a row vector from a file, guessing the filetype from the extension. - * - * The supported types of files are the same as found in Armadillo: - * - * - CSV (csv_ascii), denoted by .csv, or optionally .txt - * - TSV (raw_ascii), denoted by .tsv, .csv, or .txt - * - ASCII (raw_ascii), denoted by .txt - * - Armadillo ASCII (arma_ascii), also denoted by .txt - * - PGM (pgm_binary), denoted by .pgm - * - PPM (ppm_binary), denoted by .ppm - * - Raw binary (raw_binary), denoted by .bin - * - Armadillo binary (arma_binary), denoted by .bin - * - HDF5, denoted by .hdf, .hdf5, .h5, or .he5 - * - * If the file extension is not one of those types, an error will be given. - * This is preferable to Armadillo's default behavior of loading an unknown - * filetype as raw_binary, which can have very confusing effects. - * - * If the parameter 'fatal' is set to true, a std::runtime_error exception will - * be thrown if the matrix does not load successfully. - * - * @param filename Name of file to load. - * @param colvec Column vector to load contents of file into. - * @param fatal If an error should be reported as fatal (default false). - * @return Boolean value indicating success or failure of load. - */ -template -bool Load(const std::string& filename, - arma::Row& rowvec, - const bool fatal = false); - -/** - * Loads a matrix from a file, guessing the filetype from the extension and - * mapping categorical features with a DatasetMapper object. This will - * transpose the matrix (unless the transpose parameter is set to false). - * This particular overload of Load() can only load text-based formats, such as - * those given below: - * - * - CSV (csv_ascii), denoted by .csv, or optionally .txt - * - TSV (raw_ascii), denoted by .tsv, .csv, or .txt - * - ASCII (raw_ascii), denoted by .txt - * - * If the file extension is not one of those types, an error will be given. - * This is preferable to Armadillo's default behavior of loading an unknown - * filetype as raw_binary, which can have very confusing effects. - * - * If the parameter 'fatal' is set to true, a std::runtime_error exception will - * be thrown if the matrix does not load successfully. The parameter - * 'transpose' controls whether or not the matrix is transposed after loading. - * In most cases, because data is generally stored in a row-major format and - * mlpack requires column-major matrices, this should be left at its default - * value of 'true'. - * - * The DatasetMapper object passed to this function will be re-created, so any - * mappings from previous loads will be lost. - * - * @param filename Name of file to load. - * @param matrix Matrix to load contents of file into. - * @param info DatasetMapper object to populate with mappings and data types. - * @param fatal If an error should be reported as fatal (default false). - * @param transpose If true, transpose the matrix after loading. - * @return Boolean value indicating success or failure of load. - */ -template -bool Load(const std::string& filename, - arma::Mat& matrix, - DatasetMapper& info, - const bool fatal = false, - const bool transpose = true); - -/** - * Don't document these with doxygen; they aren't helpful for users to know - * about. - * - * @cond - */ - -extern template bool Load( - const std::string&, - arma::Mat&, - DatasetMapper&, - const bool, - const bool); - -extern template bool Load( - const std::string&, - arma::Mat&, - DatasetMapper&, - const bool, - const bool); - -extern template bool Load( - const std::string&, - arma::Mat&, - DatasetMapper&, - const bool, - const bool); - -extern template bool Load( - const std::string&, - arma::Mat&, - DatasetMapper&, - const bool, - const bool); - -extern template bool Load( - const std::string&, - arma::Mat&, - DatasetMapper&, - const bool, - const bool); - -/** - * @endcond - */ - -/** - * Load a model from a file, guessing the filetype from the extension, or, - * optionally, loading the specified format. If automatic extension detection - * is used and the filetype cannot be determined, an error will be given. - * - * The supported types of files are the same as what is supported by the - * boost::serialization library: - * - * - text, denoted by .txt - * - xml, denoted by .xml - * - binary, denoted by .bin - * - * The format parameter can take any of the values in the 'format' enum: - * 'format::autodetect', 'format::text', 'format::xml', and 'format::binary'. - * The autodetect functionality operates on the file extension (so, "file.txt" - * would be autodetected as text). - * - * The name parameter should be specified to indicate the name of the structure - * to be loaded. This should be the same as the name that was used to save the - * structure (otherwise, the loading procedure will fail). - * - * If the parameter 'fatal' is set to true, then an exception will be thrown in - * the event of load failure. Otherwise, the method will return false and the - * relevant error information will be printed to Log::Warn. - */ -template -bool Load(const std::string& filename, - const std::string& name, - T& t, - const bool fatal = false, - format f = format::autodetect); - -} // namespace data -} // namespace mlpack - -// Include implementation of model-loading Load() overload. -#include "load_model_impl.hpp" -// Include implementation of Load() for vectors. -#include "load_vec_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/load_arff.hpp b/src/sdk/mlpack/include/mlpack/core/data/load_arff.hpp deleted file mode 100644 index d5af83360..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/load_arff.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file load_arff.hpp - * @author Ryan Curtin - * - * Load an ARFF dataset. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_LOAD_ARFF_HPP -#define MLPACK_CORE_DATA_LOAD_ARFF_HPP - -#include -#include "dataset_mapper.hpp" -#include - -namespace mlpack { -namespace data { - -/** - * A utility function to load an ARFF dataset as numeric features (that is, as - * an Armadillo matrix without any modification). An exception will be thrown - * if any features are non-numeric. - */ -template -void LoadARFF(const std::string& filename, arma::Mat& matrix); - -/** - * A utility function to load an ARFF dataset as numeric and categorical - * features, using the DatasetInfo structure for mapping. An exception will be - * thrown upon failure. - * - * A pre-existing DatasetInfo object can be passed in, but if the dimensionality - * of the given DatasetInfo object (info.Dimensionality()) does not match the - * dimensionality of the data, a std::invalid_argument exception will be thrown. - * If an empty DatasetInfo object is given (constructed with the default - * constructor or otherwise, so that info.Dimensionality() is 0), it will be set - * to the right dimensionality. - * - * This ability to pass in pre-existing DatasetInfo objects is very necessary - * when, e.g., loading a test set after training. If the same DatasetInfo from - * loading the training set is not used, then the test set may be loaded with - * different mappings---which can cause horrible problems! - * - * @param filename Name of ARFF file to load. - * @param matrix Matrix to load data into. - * @param info DatasetInfo object; can be default-constructed or pre-existing - * from another call to LoadARFF(). - */ -template -void LoadARFF(const std::string& filename, - arma::Mat& matrix, - DatasetMapper& info); - -} // namespace data -} // namespace mlpack - -// Include implementation. -#include "load_arff_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/load_arff_impl.hpp b/src/sdk/mlpack/include/mlpack/core/data/load_arff_impl.hpp deleted file mode 100644 index b7d3549b4..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/load_arff_impl.hpp +++ /dev/null @@ -1,231 +0,0 @@ -/** - * @file load_arff_impl.hpp - * @author Ryan Curtin - * - * Load an ARFF dataset. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_LOAD_ARFF_IMPL_HPP -#define MLPACK_CORE_DATA_LOAD_ARFF_IMPL_HPP - -// In case it hasn't been included yet. -#include "load_arff.hpp" - -#include -#include "is_naninf.hpp" - -namespace mlpack { -namespace data { - -template -void LoadARFF(const std::string& filename, - arma::Mat& matrix, - DatasetMapper& info) -{ - // First, open the file. - std::ifstream ifs; - ifs.open(filename); - - std::string line; - size_t dimensionality = 0; - std::vector types; - size_t headerLines = 0; - while (!ifs.eof()) - { - // Read the next line, then strip whitespace from either side. - std::getline(ifs, line, '\n'); - boost::trim(line); - ++headerLines; - - // Is the first character a comment, or is the line empty? - if (line[0] == '%' || line.empty()) - continue; // Ignore this line. - - // If the first character is @, we are looking at @relation, @attribute, or - // @data. - if (line[0] == '@') - { - typedef boost::tokenizer> Tokenizer; - std::string separators = " \t%"; // Split on comments too. - boost::escaped_list_separator sep("\\", separators, "{\""); - Tokenizer tok(line, sep); - Tokenizer::iterator it = tok.begin(); - - // Get the annotation we are looking at. - std::string annotation(*it); - std::transform(annotation.begin(), annotation.end(), annotation.begin(), - ::tolower); - - if (annotation == "@relation") - { - // We don't actually have anything to do with the name of the dataset. - continue; - } - else if (annotation == "@attribute") - { - ++dimensionality; - // We need to mark this dimension with its according type. - ++it; // Ignore the dimension name. - std::string dimType = *(++it); - std::transform(dimType.begin(), dimType.end(), dimType.begin(), - ::tolower); - - if (dimType == "numeric" || dimType == "integer" || dimType == "real") - { - types.push_back(false); // The feature is numeric. - } - else if (dimType == "string") - { - types.push_back(true); // The feature is categorical. - } - else if (dimType[0] == '{') - { - throw std::logic_error("list of ARFF values not yet supported"); - } - } - else if (annotation == "@data") - { - // We are in the data section. So we can move out of this loop. - break; - } - else - { - throw std::runtime_error("unknown ARFF annotation '" + (*tok.begin()) + - "'"); - } - } - } - - if (ifs.eof()) - throw std::runtime_error("no @data section found"); - - // Reset the DatasetInfo object, if needed. - if (info.Dimensionality() == 0) - { - info = DatasetMapper(dimensionality); - } - else if (info.Dimensionality() != dimensionality) - { - std::ostringstream oss; - oss << "data::LoadARFF(): given DatasetInfo has dimensionality " - << info.Dimensionality() << ", but data has dimensionality " - << dimensionality; - throw std::invalid_argument(oss.str()); - } - - for (size_t i = 0; i < types.size(); ++i) - { - if (types[i]) - info.Type(i) = Datatype::categorical; - else - info.Type(i) = Datatype::numeric; - } - - // We need to find out how many lines of data are in the file. - std::streampos pos = ifs.tellg(); - size_t row = 0; - while (!ifs.eof()) - { - std::getline(ifs, line, '\n'); - ++row; - } - // Uncount the EOF row. - --row; - - // Since we've hit the EOF, we have to call clear() so we can seek again. - ifs.clear(); - ifs.seekg(pos); - - // Now, set the size of the matrix. - matrix.set_size(dimensionality, row); - - // Now we are looking at the @data section. - row = 0; - while (!ifs.eof()) - { - std::getline(ifs, line, '\n'); - boost::trim(line); - // Each line of the @data section must be a CSV (except sparse data, which - // we will handle later). So now we can tokenize the - // CSV and parse it. The '?' representing a missing value is not allowed, - // so if that occurs we throw an exception. We also throw an exception if - // any piece of data does not match its type (categorical or numeric). - - // If the first character is {, it is sparse data, and we can just say this - // is not handled for now... - if (line[0] == '{') - throw std::runtime_error("cannot yet parse sparse ARFF data"); - - // Tokenize the line. - typedef boost::tokenizer> Tokenizer; - boost::escaped_list_separator sep("\\", ",", "\""); - Tokenizer tok(line, sep); - - size_t col = 0; - std::stringstream token; - for (Tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) - { - // Check that we are not too many columns in. - if (col >= matrix.n_rows) - { - std::stringstream error; - error << "Too many columns in line " << (headerLines + row) << "."; - throw std::runtime_error(error.str()); - } - - // What should this token be? - if (info.Type(col) == Datatype::categorical) - { - // Strip spaces before mapping. - std::string token = *it; - boost::trim(token); - // We load transposed. - matrix(col, row) = info.template MapString(token, col); - } - else if (info.Type(col) == Datatype::numeric) - { - // Attempt to read as numeric. - token.clear(); - token.str(*it); - - eT val = eT(0); - token >> val; - - if (token.fail()) - { - // Check for NaN or inf. - if (!IsNaNInf(val, token.str())) - { - // Okay, it's not NaN or inf. If it's '?', we issue a specific - // error, otherwise we issue a general error. - std::stringstream error; - std::string tokenStr = token.str(); - boost::trim(tokenStr); - if (tokenStr == "?") - error << "Missing values ('?') not supported, "; - else - error << "Parse error "; - error << "at line " << (headerLines + row) << " token " << col - << ": \"" << tokenStr << "\"."; - throw std::runtime_error(error.str()); - } - } - - // If we made it to here, we have a value. - matrix(col, row) = val; // We load transposed. - } - - ++col; - } - ++row; - } -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/load_csv.hpp b/src/sdk/mlpack/include/mlpack/core/data/load_csv.hpp deleted file mode 100644 index 87c722fdf..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/load_csv.hpp +++ /dev/null @@ -1,376 +0,0 @@ -/** - * @file load_csv.hpp - * @author ThamNgapWei - * - * This is a csv parsers which use to parse the csv file format - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_LOAD_CSV_HPP -#define MLPACK_CORE_DATA_LOAD_CSV_HPP - -#include -#include - -#include -#include - -#include -#include - -#include "extension.hpp" -#include "format.hpp" -#include "dataset_mapper.hpp" - -namespace mlpack { -namespace data { - -/** - *Load the csv file.This class use boost::spirit - *to implement the parser, please refer to following link - *http://theboostcpplibraries.com/boost.spirit for quick review. - */ -class LoadCSV -{ - public: - /** - * Construct the LoadCSV object on the given file. This will construct the - * rules necessary for loading and attempt to open the file. - */ - LoadCSV(const std::string& file); - - /** - * Load the file into the given matrix with the given DatasetMapper object. - * Throws exceptions on errors. - * - * @param inout Matrix to load into. - * @param infoSet DatasetMapper to use while loading. - * @param transpose If true, the matrix should be transposed on loading - * (default). - */ - template - void Load(arma::Mat &inout, - DatasetMapper &infoSet, - const bool transpose = true) - { - CheckOpen(); - - if (transpose) - TransposeParse(inout, infoSet); - else - NonTransposeParse(inout, infoSet); - } - - /** - * Peek at the file to determine the number of rows and columns in the matrix, - * assuming a non-transposed matrix. This will also take a first pass over - * the data for DatasetMapper, if MapPolicy::NeedsFirstPass is true. The info - * object will be re-initialized with the correct dimensionality. - * - * @param rows Variable to be filled with the number of rows. - * @param cols Variable to be filled with the number of columns. - * @param info DatasetMapper object to use for first pass. - */ - template - void GetMatrixSize(size_t& rows, size_t& cols, DatasetMapper& info) - { - using namespace boost::spirit; - - // Take a pass through the file. If the DatasetMapper policy requires it, - // we will pass everything string through MapString(). This might be useful - // if, e.g., the MapPolicy needs to find which dimensions are numeric or - // categorical. - - // Reset to the start of the file. - inFile.clear(); - inFile.seekg(0, std::ios::beg); - rows = 0; - cols = 0; - - // First, count the number of rows in the file (this is the dimensionality). - std::string line; - while (std::getline(inFile, line)) - { - ++rows; - } - info = DatasetMapper(rows); - - // Now, jump back to the beginning of the file. - inFile.clear(); - inFile.seekg(0, std::ios::beg); - rows = 0; - - while (std::getline(inFile, line)) - { - ++rows; - // Remove whitespace from either side. - boost::trim(line); - - if (rows == 1) - { - // Extract the number of columns. - auto findColSize = [&cols](iter_type) { ++cols; }; - qi::parse(line.begin(), line.end(), - stringRule[findColSize] % delimiterRule); - } - - // I guess this is technically a second pass, but that's ok... still the - // same idea... - if (MapPolicy::NeedsFirstPass) - { - // In this case we must pass everything we parse to the MapPolicy. - auto firstPassMap = [&](const iter_type& iter) - { - std::string str(iter.begin(), iter.end()); - boost::trim(str); - - info.template MapFirstPass(std::move(str), rows - 1); - }; - - // Now parse the line. - qi::parse(line.begin(), line.end(), - stringRule[firstPassMap] % delimiterRule); - } - } - } - - /** - * Peek at the file to determine the number of rows and columns in the matrix, - * assuming a transposed matrix. This will also take a first pass over the - * data for DatasetMapper, if MapPolicy::NeedsFirstPass is true. The info - * object will be re-initialized with the correct dimensionality. - * - * @param rows Variable to be filled with the number of rows. - * @param cols Variable to be filled with the number of columns. - * @param info DatasetMapper object to use for first pass. - */ - template - void GetTransposeMatrixSize(size_t& rows, - size_t& cols, - DatasetMapper& info) - { - using namespace boost::spirit; - - // Take a pass through the file. If the DatasetMapper policy requires it, - // we will pass everything string through MapString(). This might be useful - // if, e.g., the MapPolicy needs to find which dimensions are numeric or - // categorical. - - // Reset to the start of the file. - inFile.clear(); - inFile.seekg(0, std::ios::beg); - rows = 0; - cols = 0; - - std::string line; - while (std::getline(inFile, line)) - { - ++cols; - // Remove whitespace from either side. - boost::trim(line); - - if (cols == 1) - { - // Extract the number of dimensions. - auto findRowSize = [&rows](iter_type) { ++rows; }; - qi::parse(line.begin(), line.end(), - stringRule[findRowSize] % delimiterRule); - - // Now that we know the dimensionality, initialize the DatasetMapper. - info = DatasetMapper(rows); - } - - // If we need to do a first pass for the DatasetMapper, do it. - if (MapPolicy::NeedsFirstPass) - { - size_t dim = 0; - - // In this case we must pass everything we parse to the MapPolicy. - auto firstPassMap = [&](const iter_type& iter) - { - std::string str(iter.begin(), iter.end()); - boost::trim(str); - - info.template MapFirstPass(std::move(str), dim++); - }; - - // Now parse the line. - qi::parse(line.begin(), line.end(), - stringRule[firstPassMap] % delimiterRule); - } - } - } - - private: - using iter_type = boost::iterator_range; - - /** - * Check whether or not the file has successfully opened; throw an exception - * if not. - */ - void CheckOpen(); - - /** - * Parse a non-transposed matrix. - * - * @param inout Matrix to load into. - * @param infoSet DatasetMapper object to load with. - */ - template - void NonTransposeParse(arma::Mat& inout, - DatasetMapper& infoSet) - { - using namespace boost::spirit; - - // Get the size of the matrix. - size_t rows, cols; - GetMatrixSize(rows, cols, infoSet); - - // Set up output matrix. - inout.set_size(rows, cols); - size_t row = 0; - size_t col = 0; - - // Reset file position. - std::string line; - inFile.clear(); - inFile.seekg(0, std::ios::beg); - - auto setCharClass = [&](iter_type const &iter) - { - std::string str(iter.begin(), iter.end()); - if (str == "\t") - { - str.clear(); - } - boost::trim(str); - - inout(row, col++) = infoSet.template MapString(std::move(str), row); - }; - - while (std::getline(inFile, line)) - { - // Remove whitespace from either side. - boost::trim(line); - - // Parse the numbers from a line (ex: 1,2,3,4); if the parser finds a - // number it will execute the setNum function. - const bool canParse = qi::parse(line.begin(), line.end(), - stringRule[setCharClass] % delimiterRule); - - // Make sure we got the right number of rows. - if (col != cols) - { - std::ostringstream oss; - oss << "LoadCSV::NonTransposeParse(): wrong number of dimensions (" - << col << ") on line " << row << "; should be " << cols - << " dimensions."; - throw std::runtime_error(oss.str()); - } - - if (!canParse) - { - std::ostringstream oss; - oss << "LoadCSV::NonTransposeParse(): parsing error on line " << col - << "!"; - throw std::runtime_error(oss.str()); - } - - ++row; col = 0; - } - } - - /** - * Parse a transposed matrix. - * - * @param inout Matrix to load into. - * @param infoSet DatasetMapper to load with. - */ - template - void TransposeParse(arma::Mat& inout, DatasetMapper& infoSet) - { - using namespace boost::spirit; - - // Get matrix size. This also initializes infoSet correctly. - size_t rows, cols; - GetTransposeMatrixSize(rows, cols, infoSet); - - // Set the matrix size. - inout.set_size(rows, cols); - - // Initialize auxiliary variables. - size_t row = 0; - size_t col = 0; - std::string line; - inFile.clear(); - inFile.seekg(0, std::ios::beg); - - /** - * This is the parse rule for strings. When we get a string we have to pass - * it to the DatasetMapper. - */ - auto parseString = [&](iter_type const &iter) - { - // All parsed values must be mapped. - std::string str(iter.begin(), iter.end()); - boost::trim(str); - - inout(row, col) = infoSet.template MapString(std::move(str), row); - ++row; - }; - - while (std::getline(inFile, line)) - { - // Remove whitespace from either side. - boost::trim(line); - - // Reset the row we are looking at. (Remember this is transposed.) - row = 0; - - // Now use boost::spirit to parse the characters of the line; - // parseString() will be called when a token is detected. - const bool canParse = qi::parse(line.begin(), line.end(), - stringRule[parseString] % delimiterRule); - - // Make sure we got the right number of rows. - if (row != rows) - { - std::ostringstream oss; - oss << "LoadCSV::TransposeParse(): wrong number of dimensions (" << row - << ") on line " << col << "; should be " << rows << " dimensions."; - throw std::runtime_error(oss.str()); - } - - if (!canParse) - { - std::ostringstream oss; - oss << "LoadCSV::TransposeParse(): parsing error on line " << col - << "!"; - throw std::runtime_error(oss.str()); - } - - // Increment the column index. - ++col; - } - } - - //! Spirit rule for parsing. - boost::spirit::qi::rule stringRule; - //! Spirit rule for delimiters (i.e. ',' for CSVs). - boost::spirit::qi::rule delimiterRule; - - //! Extension (type) of file. - std::string extension; - //! Name of file. - std::string filename; - //! Opened stream for reading. - std::ifstream inFile; -}; - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/load_impl.hpp b/src/sdk/mlpack/include/mlpack/core/data/load_impl.hpp deleted file mode 100644 index 1d6574345..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/load_impl.hpp +++ /dev/null @@ -1,399 +0,0 @@ -/** - * @file load_impl.hpp - * @author Ryan Curtin - * - * Implementation of templatized load() function defined in load.hpp. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_LOAD_IMPL_HPP -#define MLPACK_CORE_DATA_LOAD_IMPL_HPP - -// In case it hasn't already been included. - -#include -#include -#include - -#include "load_csv.hpp" -#include "load.hpp" -#include "extension.hpp" - -#include -#include -#include - -#include "load_arff.hpp" - -namespace mlpack { -namespace data { - -namespace details{ - -template -std::vector ToTokens(Tokenizer &lineTok) -{ - std::vector tokens; - std::transform(std::begin(lineTok), std::end(lineTok), - std::back_inserter(tokens), - [&tokens](std::string const &str) - { - std::string trimmedToken(str); - boost::trim(trimmedToken); - return std::move(trimmedToken); - }); - - return tokens; -} - -inline -void TransposeTokens(std::vector> const &input, - std::vector &output, - size_t index) -{ - output.clear(); - for (size_t i = 0; i != input.size(); ++i) - { - output.emplace_back(input[i][index]); - } -} - -} // namespace details - -template -bool inline inplace_transpose(arma::Mat& X) -{ - try - { - X = arma::trans(X); - return false; - } - catch (std::bad_alloc&) - { - return true; - } -} - -template -bool Load(const std::string& filename, - arma::Mat& matrix, - const bool fatal, - const bool transpose) -{ - Timer::Start("loading_data"); - - // Get the extension. - std::string extension = Extension(filename); - - // Catch nonexistent files by opening the stream ourselves. - std::fstream stream; -#ifdef _WIN32 // Always open in binary mode on Windows. - stream.open(filename.c_str(), std::fstream::in | std::fstream::binary); -#else - stream.open(filename.c_str(), std::fstream::in); -#endif - if (!stream.is_open()) - { - Timer::Stop("loading_data"); - if (fatal) - Log::Fatal << "Cannot open file '" << filename << "'. " << std::endl; - else - Log::Warn << "Cannot open file '" << filename << "'; load failed." - << std::endl; - - return false; - } - - bool unknownType = false; - arma::file_type loadType; - std::string stringType; - - if (extension == "csv" || extension == "tsv") - { - loadType = arma::diskio::guess_file_type(stream); - if (loadType == arma::csv_ascii) - { - if (extension == "tsv") - Log::Warn << "'" << filename << "' is comma-separated, not " - "tab-separated!" << std::endl; - stringType = "CSV data"; - } - else if (loadType == arma::raw_ascii) // .csv file can be tsv. - { - if (extension == "csv") - { - // We should issue a warning, but we don't want to issue the warning if - // there is only one column in the CSV (since there will be no commas - // anyway, and it will be detected as arma::raw_ascii). - const std::streampos pos = stream.tellg(); - std::string line; - std::getline(stream, line, '\n'); - boost::trim(line); - - // Reset stream position. - stream.seekg(pos); - - // If there are no spaces or whitespace in the line, then we shouldn't - // print the warning. - if ((line.find(' ') != std::string::npos) || - (line.find('\t') != std::string::npos)) - { - Log::Warn << "'" << filename << "' is not a standard csv file." - << std::endl; - } - } - stringType = "raw ASCII formatted data"; - } - else - { - unknownType = true; - loadType = arma::raw_binary; // Won't be used; prevent a warning. - stringType = ""; - } - } - else if (extension == "txt") - { - // This could be raw ASCII or Armadillo ASCII (ASCII with size header). - // We'll let Armadillo do its guessing (although we have to check if it is - // arma_ascii ourselves) and see what we come up with. - - // This is taken from load_auto_detect() in diskio_meat.hpp - const std::string ARMA_MAT_TXT = "ARMA_MAT_TXT"; - // char* rawHeader = new char[ARMA_MAT_TXT.length() + 1]; - std::string rawHeader(ARMA_MAT_TXT.length(), '\0'); - std::streampos pos = stream.tellg(); - - stream.read(&rawHeader[0], std::streamsize(ARMA_MAT_TXT.length())); - stream.clear(); - stream.seekg(pos); // Reset stream position after peeking. - - if (rawHeader == ARMA_MAT_TXT) - { - loadType = arma::arma_ascii; - stringType = "Armadillo ASCII formatted data"; - } - else // It's not arma_ascii. Now we let Armadillo guess. - { - loadType = arma::diskio::guess_file_type(stream); - - if (loadType == arma::raw_ascii) // Raw ASCII (space-separated). - stringType = "raw ASCII formatted data"; - else if (loadType == arma::csv_ascii) // CSV can be .txt too. - stringType = "CSV data"; - else // Unknown .txt... we will throw an error. - unknownType = true; - } - } - else if (extension == "bin") - { - // This could be raw binary or Armadillo binary (binary with header). We - // will check to see if it is Armadillo binary. - const std::string ARMA_MAT_BIN = "ARMA_MAT_BIN"; - std::string rawHeader(ARMA_MAT_BIN.length(), '\0'); - - std::streampos pos = stream.tellg(); - - stream.read(&rawHeader[0], std::streamsize(ARMA_MAT_BIN.length())); - stream.clear(); - stream.seekg(pos); // Reset stream position after peeking. - - if (rawHeader == ARMA_MAT_BIN) - { - stringType = "Armadillo binary formatted data"; - loadType = arma::arma_binary; - } - else // We can only assume it's raw binary. - { - stringType = "raw binary formatted data"; - loadType = arma::raw_binary; - } - } - else if (extension == "pgm") - { - loadType = arma::pgm_binary; - stringType = "PGM data"; - } - else if (extension == "h5" || extension == "hdf5" || extension == "hdf" || - extension == "he5") - { -#ifdef ARMA_USE_HDF5 - loadType = arma::hdf5_binary; - stringType = "HDF5 data"; -#else - Timer::Stop("loading_data"); - if (fatal) - Log::Fatal << "Attempted to load '" << filename << "' as HDF5 data, but " - << "Armadillo was compiled without HDF5 support. Load failed." - << std::endl; - else - Log::Warn << "Attempted to load '" << filename << "' as HDF5 data, but " - << "Armadillo was compiled without HDF5 support. Load failed." - << std::endl; - - return false; -#endif - } - else // Unknown extension... - { - unknownType = true; - loadType = arma::raw_binary; // Won't be used; prevent a warning. - stringType = ""; - } - - // Provide error if we don't know the type. - if (unknownType) - { - Timer::Stop("loading_data"); - if (fatal) - Log::Fatal << "Unable to detect type of '" << filename << "'; " - << "incorrect extension?" << std::endl; - else - Log::Warn << "Unable to detect type of '" << filename << "'; load failed." - << " Incorrect extension?" << std::endl; - - return false; - } - - // Try to load the file; but if it's raw_binary, it could be a problem. - if (loadType == arma::raw_binary) - Log::Warn << "Loading '" << filename << "' as " << stringType << "; " - << "but this may not be the actual filetype!" << std::endl; - else - Log::Info << "Loading '" << filename << "' as " << stringType << ". " - << std::flush; - - // We can't use the stream if the type is HDF5. - bool success; - if (loadType != arma::hdf5_binary) - success = matrix.load(stream, loadType); - else - success = matrix.load(filename, loadType); - - if (!success) - { - Log::Info << std::endl; - Timer::Stop("loading_data"); - if (fatal) - Log::Fatal << "Loading from '" << filename << "' failed." << std::endl; - else - Log::Warn << "Loading from '" << filename << "' failed." << std::endl; - - return false; - } - else - Log::Info << "Size is " << (transpose ? matrix.n_cols : matrix.n_rows) - << " x " << (transpose ? matrix.n_rows : matrix.n_cols) << ".\n"; - - // Now transpose the matrix, if necessary. - if (transpose) - { - inplace_transpose(matrix); - } - - Timer::Stop("loading_data"); - - // Finally, return the success indicator. - return success; -} - -// Load with mappings. Unfortunately we have to implement this ourselves. -template -bool Load(const std::string& filename, - arma::Mat& matrix, - DatasetMapper& info, - const bool fatal, - const bool transpose) -{ - // Get the extension and load as necessary. - Timer::Start("loading_data"); - - // Get the extension. - std::string extension = Extension(filename); - - // Catch nonexistent files by opening the stream ourselves. - std::fstream stream; - stream.open(filename.c_str(), std::fstream::in); - - if (!stream.is_open()) - { - Timer::Stop("loading_data"); - if (fatal) - Log::Fatal << "Cannot open file '" << filename << "'. " << std::endl; - else - Log::Warn << "Cannot open file '" << filename << "'; load failed." - << std::endl; - - return false; - } - - if (extension == "csv" || extension == "tsv" || extension == "txt") - { - Log::Info << "Loading '" << filename << "' as CSV dataset. " << std::flush; - try - { - LoadCSV loader(filename); - loader.Load(matrix, info, transpose); - } - catch (std::exception& e) - { - Timer::Stop("loading_data"); - if (fatal) - Log::Fatal << e.what() << std::endl; - else - Log::Warn << e.what() << std::endl; - - return false; - } - } - else if (extension == "arff") - { - Log::Info << "Loading '" << filename << "' as ARFF dataset. " - << std::flush; - try - { - LoadARFF(filename, matrix, info); - - // We transpose by default. So, un-transpose if necessary... - if (!transpose) - inplace_transpose(matrix); - } - catch (std::exception& e) - { - Timer::Stop("loading_data"); - if (fatal) - Log::Fatal << e.what() << std::endl; - else - Log::Warn << e.what() << std::endl; - - return false; - } - } - else - { - // The type is unknown. - Timer::Stop("loading_data"); - if (fatal) - Log::Fatal << "Unable to detect type of '" << filename << "'; " - << "incorrect extension?" << std::endl; - else - Log::Warn << "Unable to detect type of '" << filename << "'; load failed." - << " Incorrect extension?" << std::endl; - - return false; - } - - Log::Info << "Size is " << (transpose ? matrix.n_cols : matrix.n_rows) - << " x " << (transpose ? matrix.n_rows : matrix.n_cols) << ".\n"; - - Timer::Stop("loading_data"); - - return true; -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/load_model_impl.hpp b/src/sdk/mlpack/include/mlpack/core/data/load_model_impl.hpp deleted file mode 100644 index 7f889d255..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/load_model_impl.hpp +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @file load_model_impl.hpp - * @author Ryan Curtin - * - * Implementation of model-specific Load() function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_LOAD_MODEL_IMPL_HPP -#define MLPACK_CORE_DATA_LOAD_MODEL_IMPL_HPP - -// In case it hasn't already been included. -#include "load.hpp" - -#include -#include - -#include "extension.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace mlpack { -namespace data { - -// Load a model from file. -template -bool Load(const std::string& filename, - const std::string& name, - T& t, - const bool fatal, - format f) -{ - if (f == format::autodetect) - { - std::string extension = Extension(filename); - - if (extension == "xml") - f = format::xml; - else if (extension == "bin") - f = format::binary; - else if (extension == "txt") - f = format::text; - else - { - if (fatal) - Log::Fatal << "Unable to detect type of '" << filename << "'; incorrect" - << " extension?" << std::endl; - else - Log::Warn << "Unable to detect type of '" << filename << "'; load " - << "failed. Incorrect extension?" << std::endl; - - return false; - } - } - - // Now load the given format. - std::ifstream ifs; -#ifdef _WIN32 // Open non-text in binary mode on Windows. - if (f == format::binary) - ifs.open(filename, std::ifstream::in | std::ifstream::binary); - else - ifs.open(filename, std::ifstream::in); -#else - ifs.open(filename, std::ifstream::in); -#endif - - if (!ifs.is_open()) - { - if (fatal) - Log::Fatal << "Unable to open file '" << filename << "' to load object '" - << name << "'." << std::endl; - else - Log::Warn << "Unable to open file '" << filename << "' to load object '" - << name << "'." << std::endl; - - return false; - } - - try - { - if (f == format::xml) - { - boost::archive::xml_iarchive ar(ifs); - ar >> boost::serialization::make_nvp(name.c_str(), t); - } - else if (f == format::text) - { - boost::archive::text_iarchive ar(ifs); - ar >> boost::serialization::make_nvp(name.c_str(), t); - } - else if (f == format::binary) - { - boost::archive::binary_iarchive ar(ifs); - ar >> boost::serialization::make_nvp(name.c_str(), t); - } - - return true; - } - catch (boost::archive::archive_exception& e) - { - if (fatal) - Log::Fatal << e.what() << std::endl; - else - Log::Warn << e.what() << std::endl; - - return false; - } -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/load_vec_impl.hpp b/src/sdk/mlpack/include/mlpack/core/data/load_vec_impl.hpp deleted file mode 100644 index 067d5bb3f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/load_vec_impl.hpp +++ /dev/null @@ -1,150 +0,0 @@ -/** - * @file load_impl.hpp - * @author Ryan Curtin - * - * Implementation of templatized load() function defined in load.hpp for - * vectors. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_LOAD_VEC_IMPL_HPP -#define MLPACK_CORE_DATA_LOAD_VEC_IMPL_HPP - -// In case it hasn't already been included. -#include "load.hpp" - -namespace mlpack { -namespace data { - -// Load column vector. -template -bool Load(const std::string& filename, - arma::Col& vec, - const bool fatal) -{ - // First load into auxiliary matrix. - arma::Mat tmp; - bool success = Load(filename, tmp, fatal, false); - if (!success) - { - vec.clear(); - return false; - } - - // Now check the size to see that it is a vector, and return a vector. - if (tmp.n_cols > 1) - { - if (tmp.n_rows > 1) - { - // Problem: invalid size! - if (fatal) - { - Log::Fatal << "Matrix in file '" << filename << "' is not a vector, but" - << " instead has size " << tmp.n_rows << "x" << tmp.n_cols << "!" - << std::endl; - } - else - { - Log::Warn << "Matrix in file '" << filename << "' is not a vector, but " - << "instead has size " << tmp.n_rows << "x" << tmp.n_cols << "!" - << std::endl; - } - - vec.clear(); - return false; - } - else - { - /** - * It's loaded as a row vector (more than one column). So we need to - * manually modify the shape of the matrix. We can do this without - * damaging the data since it is only a vector. - */ - arma::access::rw(tmp.n_rows) = tmp.n_cols; - arma::access::rw(tmp.n_cols) = 1; - - /** - * Now we can call the move operator, but it has to be the move operator - * for Mat, not for Col. This will avoid copying the data. - */ - *((arma::Mat*) &vec) = std::move(tmp); - return true; - } - } - else - { - // It's loaded as a column vector. We can call the move constructor - // directly. - *((arma::Mat*) &vec) = std::move(tmp); - return true; - } -} - -// Load row vector. -template -bool Load(const std::string& filename, - arma::Row& rowvec, - const bool fatal) -{ - arma::Mat tmp; - bool success = Load(filename, tmp, fatal, false); - if (!success) - { - rowvec.clear(); - return false; - } - - if (tmp.n_rows > 1) - { - if (tmp.n_cols > 1) - { - // Problem: invalid size! - if (fatal) - { - Log::Fatal << "Matrix in file '" << filename << "' is not a vector, but" - << " instead has size " << tmp.n_rows << "x" << tmp.n_cols << "!" - << std::endl; - } - else - { - Log::Warn << "Matrix in file '" << filename << "' is not a vector, but " - << "instead has size " << tmp.n_rows << "x" << tmp.n_cols << "!" - << std::endl; - } - - rowvec.clear(); - return false; - } - else - { - /** - * It's loaded as a column vector (more than one row). So we need to - * manually modify the shape of the matrix. We can do this without - * damaging the data since it is only a vector. - */ - arma::access::rw(tmp.n_cols) = tmp.n_rows; - arma::access::rw(tmp.n_rows) = 1; - - /** - * Now we can call the move operator, but it has to be the move operator - * for Mat, not for Col. This will avoid copying the data. - */ - *((arma::Mat*) &rowvec) = std::move(tmp); - return true; - } - } - else - { - // It's loaded as a row vector. We can call the move constructor directly. - *((arma::Mat*) &rowvec) = std::move(tmp); - return true; - } -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/map_policies/datatype.hpp b/src/sdk/mlpack/include/mlpack/core/data/map_policies/datatype.hpp deleted file mode 100644 index 73abad47a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/map_policies/datatype.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * @file missing_policy.hpp - * @author Keon Kim - * - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_MAP_POLICIES_DATATYPE_HPP -#define MLPACK_CORE_DATA_MAP_POLICIES_DATATYPE_HPP - -#include - -namespace mlpack { -namespace data { -/** - * The Datatype enum specifies the types of data mlpack algorithms can use. - * The vast majority of mlpack algorithms can only use numeric data (i.e. - * float/double/etc.), but some algorithms can use categorical data, specified - * via this Datatype enum and the DatasetMapper class. - */ -enum Datatype : bool /* [> bool is all the precision we need for two types <] */ -{ - numeric = 0, - categorical = 1 -}; - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/map_policies/increment_policy.hpp b/src/sdk/mlpack/include/mlpack/core/data/map_policies/increment_policy.hpp deleted file mode 100644 index 33cc59341..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/map_policies/increment_policy.hpp +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @file increment_policy.hpp - * @author Keon Kim - * - * Default increment maping policy for dataset info. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_MAP_POLICIES_INCREMENT_POLICY_HPP -#define MLPACK_CORE_DATA_MAP_POLICIES_INCREMENT_POLICY_HPP - -#include -#include -#include - -namespace mlpack { -namespace data { - -/** - * IncrementPolicy is used as a helper class for DatasetMapper. It tells how the - * strings should be mapped. Purpose of this policy is to map all dimension if - * one if the variables in a dimension turns out to be a categorical variable. - * IncrementPolicy maps strings to incrementing unsigned integers (size_t). - * The first input to be mapped will be mapped to 0, the next to 1 and so on. - * - * If the 'forceAllMappings' parameter is set to true, this will always map. - * Otherwise, inputs will only be mapped if they cannot be cast to the output - * type via a stringstream extraction. - */ -class IncrementPolicy -{ - public: - IncrementPolicy(const bool forceAllMappings = false) : - forceAllMappings(forceAllMappings) { } - - // typedef of MappedType - using MappedType = size_t; - - //! We do need a first pass over the data to set the dimension types right. - static const bool NeedsFirstPass = true; - - /** - * Determine if the dimension is numeric or categorical. - */ - template - void MapFirstPass(const InputType& input, - const size_t dim, - std::vector& types) - { - if (types[dim] == Datatype::categorical) - { - // No need to check; it's already categorical. - return; - } - - if (forceAllMappings) - { - types[dim] = Datatype::categorical; - } - else - { - // Attempt to convert the input to an output type via a stringstream. - std::stringstream token; - token << input; - T val; - token >> val; - - if (token.fail() || !token.eof()) - types[dim] = Datatype::categorical; - } - } - - /** - * Given the input and the dimension to which the it belongs, and the maps - * and types given by the DatasetMapper class, returns its numeric mapping. - * If no mapping yet exists, the input is added to the list of mappings for - * the given dimension. This function is used as a helper function for - * DatasetMapper class. - * - * @tparam MapType Type of unordered_map that contains mapped value pairs - * @param input Input to find/create mapping for. - * @param dimension Index of the dimension of the input. - * @param maps Unordered map given by the DatasetMapper. - * @param types Vector containing the type information about each dimensions. - */ - template - T MapString(const InputType& input, - const size_t dimension, - MapType& maps, - std::vector& types) - { - // If we are in a categorical dimension we already know we need to map. - if (types[dimension] == Datatype::numeric && !forceAllMappings) - { - // Check if this input needs to be mapped or if it can be read - // directly as a number. This will be true if nothing else in this - // dimension has yet been mapped, but this can't be read as a number. - std::stringstream token; - token << input; - T val; - token >> val; - - if (!token.fail() && token.eof()) - return val; - - // Otherwise, we must map. - } - - // If this condition is true, either we have no mapping for the given input - // or we have no mappings for the given dimension at all. In either case, - // we create a mapping. - if (maps.count(dimension) == 0 || - maps[dimension].first.count(input) == 0) - { - // This input does not exist yet. - size_t numMappings = maps[dimension].first.size(); - - // Change type of the feature to categorical. - if (numMappings == 0) - types[dimension] = Datatype::categorical; - - typedef typename std::pair PairType; - maps[dimension].first.insert(PairType(input, numMappings)); - - // Do we need to create the second map? - if (maps[dimension].second.count(numMappings) == 0) - { - maps[dimension].second.insert(std::make_pair(numMappings, - std::vector())); - } - maps[dimension].second[numMappings].push_back(input); - - return T(numMappings); - } - else - { - // This input already exists in the mapping. - return maps[dimension].first.at(input); - } - } - - private: - // Whether or not we should map all tokens. - bool forceAllMappings; -}; // class IncrementPolicy - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/map_policies/missing_policy.hpp b/src/sdk/mlpack/include/mlpack/core/data/map_policies/missing_policy.hpp deleted file mode 100644 index c650237db..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/map_policies/missing_policy.hpp +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @file missing_policy.hpp - * @author Keon Kim - * - * Missing map policy for dataset info. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_MAP_POLICIES_MISSING_POLICY_HPP -#define MLPACK_CORE_DATA_MAP_POLICIES_MISSING_POLICY_HPP - -#include -#include -#include -#include - -namespace mlpack { -namespace data { - -/** - * MissingPolicy is used as a helper class for DatasetMapper. It tells how the - * strings should be mapped. Purpose of this policy is to map all user-defined - * missing variables into maps so that users can decide what to do with the - * corrupted data. User-defined missing variables are given by the missingSet. - * Note that MissingPolicy does not change type of features. - */ -class MissingPolicy -{ - public: - // typedef of MappedType - using MappedType = double; - - MissingPolicy() - { - // Nothing to initialize here. - } - - /** - * Create the MissingPolicy object with the given missingSet. Note that the - * missingSet cannot be changed later; you will have to create a new - * MissingPolicy object. - * - * @param missingSet Set of strings that should be mapped. - */ - explicit MissingPolicy(std::set missingSet) : - missingSet(std::move(missingSet)) - { - // Nothing to initialize here. - } - - //! This doesn't need a first pass over the data to set up. - static const bool NeedsFirstPass = false; - - /** - * There is nothing for us to do here, but this is required by the MapPolicy - * type. - */ - template - void MapFirstPass(const std::string& /* string */, const size_t /* dim */) - { - // Nothing to do. - } - - /** - * Given the string and the dimension to which it belongs by the user, and - * the maps and types given by the DatasetMapper class, returns its numeric - * mapping. If no mapping yet exists and the string is included in the - * missingSet, the string is added to the list of mappings for the given - * dimension. This function is used as a helper function for DatasetMapper - * class. - * - * @tparam MapType Type of unordered_map that contains mapped value pairs - * @param string String to find/create mapping for. - * @param dimension Index of the dimension of the string. - * @param maps Unordered map given by the DatasetMapper. - * @param types Vector containing the type information about each dimensions. - */ - template - T MapString(const std::string& string, - const size_t dimension, - MapType& maps, - std::vector& /* types */) - { - static_assert(std::numeric_limits::has_quiet_NaN == true, - "Cannot use MissingPolicy with types where has_quiet_NaN() is false!"); - - // If we can load the string then there is no need for mapping. - std::stringstream token; - token.str(string); - T t; - token >> t; // Could be sped up by only doing this if we need to. - - MappedType value = std::numeric_limits::quiet_NaN(); - // But we can't use that for the map, so we need some other thing that will - // represent quiet_NaN(). - const MappedType mapValue = std::nexttoward( - std::numeric_limits::max(), MappedType(0)); - - // If extraction of the value fails, or if it is a value that is supposed to - // be mapped, then do mapping. - if (token.fail() || !token.eof() || - missingSet.find(string) != std::end(missingSet)) - { - // Everything is mapped to NaN. However we must still keep track of - // everything that we have mapped, so we add it to the maps if needed. - if (maps.count(dimension) == 0 || - maps[dimension].first.count(string) == 0) - { - // This string does not exist yet. - typedef std::pair PairType; - maps[dimension].first.insert(PairType(string, value)); - - // Insert right mapping too. - if (maps[dimension].second.count(mapValue) == 0) - { - // Create new element in reverse map. - maps[dimension].second.insert(std::make_pair(mapValue, - std::vector())); - } - maps[dimension].second[mapValue].push_back(string); - } - - return value; - } - else - { - // We can just return the value that we read. - return t; - } - } - - private: - // Note that missingSet and maps are different. - // missingSet specifies which value/string should be mapped and may be a - // superset of 'maps'. - std::set missingSet; -}; // class MissingPolicy - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/normalize_labels.hpp b/src/sdk/mlpack/include/mlpack/core/data/normalize_labels.hpp deleted file mode 100644 index 9dba859bd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/normalize_labels.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @file normalize_labels.hpp - * @author Ryan Curtin - * - * Often labels are not given as {0, 1, 2, ...} but instead {1, 2, ...} or even - * {-1, 1} or otherwise. The purpose of this function is to normalize labels to - * {0, 1, 2, ...} and provide a mapping back to those labels. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_NORMALIZE_LABELS_HPP -#define MLPACK_CORE_DATA_NORMALIZE_LABELS_HPP - -#include - -namespace mlpack { -namespace data { - -/** - * Given a set of labels of a particular datatype, convert them to unsigned - * labels in the range [0, n) where n is the number of different labels. Also, - * a reverse mapping from the new label to the old value is stored in the - * 'mapping' vector. - * - * @param labelsIn Input labels of arbitrary datatype. - * @param labels Vector that unsigned labels will be stored in. - * @param mapping Reverse mapping to convert new labels back to old labels. - */ -template -void NormalizeLabels(const RowType& labelsIn, - arma::Row& labels, - arma::Col& mapping); - -/** - * Given a set of labels that have been mapped to the range [0, n), map them - * back to the original labels given by the 'mapping' vector. - * - * @param labels Set of normalized labels to convert. - * @param mapping Mapping to use to convert labels. - * @param labelsOut Vector to store new labels in. - */ -template -void RevertLabels(const arma::Row& labels, - const arma::Col& mapping, - arma::Row& labelsOut); - -} // namespace data -} // namespace mlpack - -// Include implementation. -#include "normalize_labels_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/normalize_labels_impl.hpp b/src/sdk/mlpack/include/mlpack/core/data/normalize_labels_impl.hpp deleted file mode 100644 index cfa043dc1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/normalize_labels_impl.hpp +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @file normalize_labels_impl.hpp - * @author Ryan Curtin - * - * Implementation of label normalization functions; these are useful for mapping - * labels to the range [0, n). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_NORMALIZE_LABELS_IMPL_HPP -#define MLPACK_CORE_DATA_NORMALIZE_LABELS_IMPL_HPP - -// In case it hasn't been included yet. -#include "normalize_labels.hpp" - -namespace mlpack { -namespace data { - -/** - * Given a set of labels of a particular datatype, convert them to unsigned - * labels in the range [0, n) where n is the number of different labels. Also, - * a reverse mapping from the new label to the old value is stored in the - * 'mapping' vector. - * - * @param labelsIn Input labels of arbitrary datatype. - * @param labels Vector that unsigned labels will be stored in. - * @param mapping Reverse mapping to convert new labels back to old labels. - */ -template -void NormalizeLabels(const RowType& labelsIn, - arma::Row& labels, - arma::Col& mapping) -{ - // Loop over the input labels, and develop the mapping. We'll first naively - // resize the mapping to the maximum possible size, and then when we fill it, - // we'll resize it back down to its actual size. - mapping.set_size(labelsIn.n_elem); - labels.set_size(labelsIn.n_elem); - size_t curLabel = 0; - for (size_t i = 0; i < labelsIn.n_elem; ++i) - { - bool found = false; - for (size_t j = 0; j < curLabel; ++j) - { - // Is the label already in the list of labels we have seen? - if (labelsIn[i] == mapping[j]) - { - labels[i] = j; - found = true; - break; - } - } - - // Do we need to add this new label? - if (!found) - { - mapping[curLabel] = labelsIn[i]; - labels[i] = curLabel; - ++curLabel; - } - } - - // Resize mapping back down to necessary size. - mapping.resize(curLabel); -} - -/** - * Given a set of labels that have been mapped to the range [0, n), map them - * back to the original labels given by the 'mapping' vector. - * - * @param labels Set of normalized labels to convert. - * @param mapping Mapping to use to convert labels. - * @param labelsOut Vector to store new labels in. - */ -template -void RevertLabels(const arma::Row& labels, - const arma::Col& mapping, - arma::Row& labelsOut) -{ - // We already have the mapping, so we just need to loop over each element. - labelsOut.set_size(labels.n_elem); - - for (size_t i = 0; i < labels.n_elem; ++i) - labelsOut[i] = mapping[labels[i]]; -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/save.hpp b/src/sdk/mlpack/include/mlpack/core/data/save.hpp deleted file mode 100644 index 52c1b57d1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/save.hpp +++ /dev/null @@ -1,99 +0,0 @@ -/** - * @file save.hpp - * @author Ryan Curtin - * - * Save an Armadillo matrix to file. This is necessary because Armadillo does - * not transpose matrices upon saving, and it allows us to give better error - * output. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_SAVE_HPP -#define MLPACK_CORE_DATA_SAVE_HPP - -#include -#include // Includes Armadillo. -#include - -#include "format.hpp" - -namespace mlpack { -namespace data /** Functions to load and save matrices. */ { - -/** - * Saves a matrix to file, guessing the filetype from the extension. This - * will transpose the matrix at save time. If the filetype cannot be - * determined, an error will be given. - * - * The supported types of files are the same as found in Armadillo: - * - * - CSV (csv_ascii), denoted by .csv, or optionally .txt - * - ASCII (raw_ascii), denoted by .txt - * - Armadillo ASCII (arma_ascii), also denoted by .txt - * - PGM (pgm_binary), denoted by .pgm - * - PPM (ppm_binary), denoted by .ppm - * - Raw binary (raw_binary), denoted by .bin - * - Armadillo binary (arma_binary), denoted by .bin - * - HDF5 (hdf5_binary), denoted by .hdf5, .hdf, .h5, or .he5 - * - * If the file extension is not one of those types, an error will be given. If - * the 'fatal' parameter is set to true, a std::runtime_error exception will be - * thrown upon failure. If the 'transpose' parameter is set to true, the matrix - * will be transposed before saving. Generally, because mlpack stores matrices - * in a column-major format and most datasets are stored on disk as row-major, - * this parameter should be left at its default value of 'true'. - * - * @param filename Name of file to save to. - * @param matrix Matrix to save into file. - * @param fatal If an error should be reported as fatal (default false). - * @param transpose If true, transpose the matrix before saving. - * @return Boolean value indicating success or failure of save. - */ -template -bool Save(const std::string& filename, - const arma::Mat& matrix, - const bool fatal = false, - bool transpose = true); - -/** - * Saves a model to file, guessing the filetype from the extension, or, - * optionally, saving the specified format. If automatic extension detection is - * used and the filetype cannot be determined, and error will be given. - * - * The supported types of files are the same as what is supported by the - * boost::serialization library: - * - * - text, denoted by .txt - * - xml, denoted by .xml - * - binary, denoted by .bin - * - * The format parameter can take any of the values in the 'format' enum: - * 'format::autodetect', 'format::text', 'format::xml', and 'format::binary'. - * The autodetect functionality operates on the file extension (so, "file.txt" - * would be autodetected as text). - * - * The name parameter should be specified to indicate the name of the structure - * to be saved. If Load() is later called on the generated file, the name used - * to load should be the same as the name used for this call to Save(). - * - * If the parameter 'fatal' is set to true, then an exception will be thrown in - * the event of a save failure. Otherwise, the method will return false and the - * relevant error information will be printed to Log::Warn. - */ -template -bool Save(const std::string& filename, - const std::string& name, - T& t, - const bool fatal = false, - format f = format::autodetect); - -} // namespace data -} // namespace mlpack - -// Include implementation. -#include "save_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/save_impl.hpp b/src/sdk/mlpack/include/mlpack/core/data/save_impl.hpp deleted file mode 100644 index 94d3547ac..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/save_impl.hpp +++ /dev/null @@ -1,289 +0,0 @@ -/** - * @file save_impl.hpp - * @author Ryan Curtin - * - * Implementation of save functionality. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_SAVE_IMPL_HPP -#define MLPACK_CORE_DATA_SAVE_IMPL_HPP - -// In case it hasn't already been included. -#include "save.hpp" -#include "extension.hpp" - -#include -#include -#include -#include - -namespace mlpack { -namespace data { - -template -bool Save(const std::string& filename, - const arma::Col& vec, - const bool fatal) -{ - // Don't transpose: one observation per line (for CSVs at least). - return Save(filename, vec, fatal, false); -} - -template -bool Save(const std::string& filename, - const arma::Row& rowvec, - const bool fatal) -{ - return Save(filename, rowvec, fatal, true); -} - -template -bool Save(const std::string& filename, - const arma::Mat& matrix, - const bool fatal, - bool transpose) -{ - Timer::Start("saving_data"); - - // First we will try to discriminate by file extension. - std::string extension = Extension(filename); - if (extension == "") - { - Timer::Stop("saving_data"); - if (fatal) - Log::Fatal << "No extension given with filename '" << filename << "'; " - << "type unknown. Save failed." << std::endl; - else - Log::Warn << "No extension given with filename '" << filename << "'; " - << "type unknown. Save failed." << std::endl; - - return false; - } - - // Catch errors opening the file. - std::fstream stream; -#ifdef _WIN32 // Always open in binary mode on Windows. - stream.open(filename.c_str(), std::fstream::out | std::fstream::binary); -#else - stream.open(filename.c_str(), std::fstream::out); -#endif - if (!stream.is_open()) - { - Timer::Stop("saving_data"); - if (fatal) - Log::Fatal << "Cannot open file '" << filename << "' for writing. " - << "Save failed." << std::endl; - else - Log::Warn << "Cannot open file '" << filename << "' for writing; save " - << "failed." << std::endl; - - return false; - } - - bool unknownType = false; - arma::file_type saveType; - std::string stringType; - - if (extension == "csv") - { - saveType = arma::csv_ascii; - stringType = "CSV data"; - } - else if (extension == "txt") - { - saveType = arma::raw_ascii; - stringType = "raw ASCII formatted data"; - } - else if (extension == "bin") - { - saveType = arma::arma_binary; - stringType = "Armadillo binary formatted data"; - } - else if (extension == "pgm") - { - saveType = arma::pgm_binary; - stringType = "PGM data"; - } - else if (extension == "h5" || extension == "hdf5" || extension == "hdf" || - extension == "he5") - { -#ifdef ARMA_USE_HDF5 - saveType = arma::hdf5_binary; - stringType = "HDF5 data"; -#else - Timer::Stop("saving_data"); - if (fatal) - Log::Fatal << "Attempted to save HDF5 data to '" << filename << "', but " - << "Armadillo was compiled without HDF5 support. Save failed." - << std::endl; - else - Log::Warn << "Attempted to save HDF5 data to '" << filename << "', but " - << "Armadillo was compiled without HDF5 support. Save failed." - << std::endl; - - return false; -#endif - } - else - { - unknownType = true; - saveType = arma::raw_binary; // Won't be used; prevent a warning. - stringType = ""; - } - - // Provide error if we don't know the type. - if (unknownType) - { - Timer::Stop("saving_data"); - if (fatal) - Log::Fatal << "Unable to determine format to save to from filename '" - << filename << "'. Save failed." << std::endl; - else - Log::Warn << "Unable to determine format to save to from filename '" - << filename << "'. Save failed." << std::endl; - - return false; - } - - // Try to save the file. - Log::Info << "Saving " << stringType << " to '" << filename << "'." - << std::endl; - - // Transpose the matrix. - if (transpose) - { - arma::Mat tmp = trans(matrix); - - // We can't save with streams for HDF5. - const bool success = (saveType == arma::hdf5_binary) ? - tmp.quiet_save(filename, saveType) : - tmp.quiet_save(stream, saveType); - if (!success) - { - Timer::Stop("saving_data"); - if (fatal) - Log::Fatal << "Save to '" << filename << "' failed." << std::endl; - else - Log::Warn << "Save to '" << filename << "' failed." << std::endl; - - return false; - } - } - else - { - // We can't save with streams for HDF5. - const bool success = (saveType == arma::hdf5_binary) ? - matrix.quiet_save(filename, saveType) : - matrix.quiet_save(stream, saveType); - if (!success) - { - Timer::Stop("saving_data"); - if (fatal) - Log::Fatal << "Save to '" << filename << "' failed." << std::endl; - else - Log::Warn << "Save to '" << filename << "' failed." << std::endl; - - return false; - } - } - - Timer::Stop("saving_data"); - - // Finally return success. - return true; -} - -//! Save a model to file. -template -bool Save(const std::string& filename, - const std::string& name, - T& t, - const bool fatal, - format f) -{ - if (f == format::autodetect) - { - std::string extension = Extension(filename); - - if (extension == "xml") - f = format::xml; - else if (extension == "bin") - f = format::binary; - else if (extension == "txt") - f = format::text; - else - { - if (fatal) - Log::Fatal << "Unable to detect type of '" << filename << "'; incorrect" - << " extension? (allowed: xml/bin/txt)" << std::endl; - else - Log::Warn << "Unable to detect type of '" << filename << "'; save " - << "failed. Incorrect extension? (allowed: xml/bin/txt)" - << std::endl; - - return false; - } - } - - // Open the file to save to. - std::ofstream ofs; -#ifdef _WIN32 - if (f == format::binary) // Open non-text types in binary mode on Windows. - ofs.open(filename, std::ofstream::out | std::ofstream::binary); - else - ofs.open(filename, std::ofstream::out); -#else - ofs.open(filename, std::ofstream::out); -#endif - - if (!ofs.is_open()) - { - if (fatal) - Log::Fatal << "Unable to open file '" << filename << "' to save object '" - << name << "'." << std::endl; - else - Log::Warn << "Unable to open file '" << filename << "' to save object '" - << name << "'." << std::endl; - - return false; - } - - try - { - if (f == format::xml) - { - boost::archive::xml_oarchive ar(ofs); - ar << boost::serialization::make_nvp(name.c_str(), t); - } - else if (f == format::text) - { - boost::archive::text_oarchive ar(ofs); - ar << boost::serialization::make_nvp(name.c_str(), t); - } - else if (f == format::binary) - { - boost::archive::binary_oarchive ar(ofs); - ar << boost::serialization::make_nvp(name.c_str(), t); - } - - return true; - } - catch (boost::archive::archive_exception& e) - { - if (fatal) - Log::Fatal << e.what() << std::endl; - else - Log::Warn << e.what() << std::endl; - - return false; - } -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/serialization_template_version.hpp b/src/sdk/mlpack/include/mlpack/core/data/serialization_template_version.hpp deleted file mode 100644 index 042232722..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/serialization_template_version.hpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @file serialization_template_version.hpp - * @author Ryan Curtin - * - * A better version of the BOOST_CLASS_VERSION() macro that supports templated - * classes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_SERIALIZATION_TEMPLATE_VERSION_HPP -#define MLPACK_CORE_DATA_SERIALIZATION_TEMPLATE_VERSION_HPP - -/** - * Use this like BOOST_CLASS_VERSION(), but for templated classes. The first - * argument is the signature for the template. Here is an example for - * math::Range: - * - * BOOST_TEMPLATE_CLASS_VERSION(template, math::Range, 1); - */ -#define BOOST_TEMPLATE_CLASS_VERSION(SIGNATURE, T, N) \ -namespace boost { \ -namespace serialization { \ -SIGNATURE \ -struct version \ -{ \ - typedef mpl::int_ type; \ - typedef mpl::integral_c_tag tag; \ - BOOST_STATIC_CONSTANT(int, value = version::type::value); \ - BOOST_MPL_ASSERT((boost::mpl::less, \ - boost::mpl::int_<256>>)); \ -}; \ -} /* namespace serialization */ \ -} /* namespace boost */ - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/data/split_data.hpp b/src/sdk/mlpack/include/mlpack/core/data/split_data.hpp deleted file mode 100644 index 28b0bcf96..000000000 --- a/src/sdk/mlpack/include/mlpack/core/data/split_data.hpp +++ /dev/null @@ -1,198 +0,0 @@ -/** - * @file split_data.hpp - * @author Tham Ngap Wei, Keon Kim - * - * Defines Split(), a utility function to split a dataset into a - * training set and a test set. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DATA_SPLIT_DATA_HPP -#define MLPACK_CORE_DATA_SPLIT_DATA_HPP - -#include - -namespace mlpack { -namespace data { -/** - * Given an input dataset and labels, split into a training set and test set. - * Example usage below. This overload places the split dataset into the four - * output parameters given (trainData, testData, trainLabel, and testLabel). - * - * @code - * arma::mat input = loadData(); - * arma::Row label = loadLabel(); - * arma::mat trainData; - * arma::mat testData; - * arma::Row trainLabel; - * arma::Row testLabel; - * math::RandomSeed(100); // Set the seed if you like. - * - * // Split the dataset into a training and test set, with 30% of the data being - * // held out for the test set. - * Split(input, label, trainData, - * testData, trainLabel, testLabel, 0.3); - * @endcode - * - * @param input Input dataset to split. - * @param label Input labels to split. - * @param trainData Matrix to store training data into. - * @param testData Matrix to store test data into. - * @param trainLabel Vector to store training labels into. - * @param testLabel Vector to store test labels into. - * @param testRatio Percentage of dataset to use for test set (between 0 and 1). - */ -template -void Split(const arma::Mat& input, - const arma::Row& inputLabel, - arma::Mat& trainData, - arma::Mat& testData, - arma::Row& trainLabel, - arma::Row& testLabel, - const double testRatio) -{ - const size_t testSize = static_cast(input.n_cols * testRatio); - const size_t trainSize = input.n_cols - testSize; - trainData.set_size(input.n_rows, trainSize); - testData.set_size(input.n_rows, testSize); - trainLabel.set_size(trainSize); - testLabel.set_size(testSize); - - const arma::Col order = - arma::shuffle(arma::linspace>(0, input.n_cols - 1, - input.n_cols)); - - for (size_t i = 0; i != trainSize; ++i) - { - trainData.col(i) = input.col(order[i]); - trainLabel(i) = inputLabel(order[i]); - } - - for (size_t i = 0; i != testSize; ++i) - { - testData.col(i) = input.col(order[i + trainSize]); - testLabel(i) = inputLabel(order[i + trainSize]); - } -} - -/** - * Given an input dataset, split into a training set and test set. - * Example usage below. This overload places the split dataset into the two - * output parameters given (trainData, testData). - * - * @code - * arma::mat input = loadData(); - * arma::mat trainData; - * arma::mat testData; - * math::RandomSeed(100); // Set the seed if you like. - * - * // Split the dataset into a training and test set, with 30% of the data being - * // held out for the test set. - * Split(input, trainData, testData, 0.3); - * @endcode - * - * @param input Input dataset to split. - * @param trainData Matrix to store training data into. - * @param testData Matrix to store test data into. - * @param testRatio Percentage of dataset to use for test set (between 0 and 1). - */ -template -void Split(const arma::Mat& input, - arma::Mat& trainData, - arma::Mat& testData, - const double testRatio) -{ - const size_t testSize = static_cast(input.n_cols * testRatio); - const size_t trainSize = input.n_cols - testSize; - trainData.set_size(input.n_rows, trainSize); - testData.set_size(input.n_rows, testSize); - - const arma::Col order = - arma::shuffle(arma::linspace>(0, input.n_cols -1, - input.n_cols)); - - for (size_t i = 0; i != trainSize; ++i) - { - trainData.col(i) = input.col(order[i]); - } - for (size_t i = 0; i != testSize; ++i) - { - testData.col(i) = input.col(order[i + trainSize]); - } -} - -/** - * Given an input dataset and labels, split into a training set and test set. - * Example usage below. This overload returns the split dataset as a std::tuple - * with four elements: an arma::Mat containing the training data, an - * arma::Mat containing the test data, an arma::Row containing the - * training labels, and an arma::Row containing the test labels. - * - * @code - * arma::mat input = loadData(); - * arma::Row label = loadLabel(); - * auto splitResult = Split(input, label, 0.2); - * @endcode - * - * @param input Input dataset to split. - * @param label Input labels to split. - * @param testRatio Percentage of dataset to use for test set (between 0 and 1). - * @return std::tuple containing trainData (arma::Mat), testData - * (arma::Mat), trainLabel (arma::Row), and testLabel (arma::Row). - */ -template -std::tuple, arma::Mat, arma::Row, arma::Row> -Split(const arma::Mat& input, - const arma::Row& inputLabel, - const double testRatio) -{ - arma::Mat trainData; - arma::Mat testData; - arma::Row trainLabel; - arma::Row testLabel; - - Split(input, inputLabel, trainData, testData, trainLabel, testLabel, - testRatio); - - return std::make_tuple(std::move(trainData), - std::move(testData), - std::move(trainLabel), - std::move(testLabel)); -} - -/** - * Given an input dataset, split into a training set and test set. - * Example usage below. This overload returns the split dataset as a std::tuple - * with two elements: an arma::Mat containing the training data and an - * arma::Mat containing the test data. - * - * @code - * arma::mat input = loadData(); - * auto splitResult = Split(input, 0.2); - * @endcode - * - * @param input Input dataset to split. - * @param testRatio Percentage of dataset to use for test set (between 0 and 1). - * @return std::tuple containing trainData (arma::Mat) - * and testData (arma::Mat). - */ -template -std::tuple, arma::Mat> -Split(const arma::Mat& input, - const double testRatio) -{ - arma::Mat trainData; - arma::Mat testData; - Split(input, trainData, testData, testRatio); - - return std::make_tuple(std::move(trainData), - std::move(testData)); -} - -} // namespace data -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/dists/discrete_distribution.hpp b/src/sdk/mlpack/include/mlpack/core/dists/discrete_distribution.hpp deleted file mode 100644 index af979f02f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/dists/discrete_distribution.hpp +++ /dev/null @@ -1,225 +0,0 @@ -/** - * @file discrete_distribution.hpp - * @author Ryan Curtin - * - * Implementation of the discrete distribution, where each discrete observation - * has a given probability. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DISTRIBUTIONS_DISCRETE_DISTRIBUTION_HPP -#define MLPACK_CORE_DISTRIBUTIONS_DISCRETE_DISTRIBUTION_HPP - -#include -#include -#include - -namespace mlpack { -namespace distribution /** Probability distributions. */ { - -/** - * A discrete distribution where the only observations are discrete - * observations. This is useful (for example) with discrete Hidden Markov - * Models, where observations are non-negative integers representing specific - * emissions. - * - * No bounds checking is performed for observations, so if an invalid - * observation is passed (i.e. observation > numObservations), a crash will - * probably occur. - * - * This distribution only supports one-dimensional observations, so when passing - * an arma::vec as an observation, it should only have one dimension - * (vec.n_rows == 1). Any additional dimensions will simply be ignored. - * - * @note - * This class, like every other class in mlpack, uses arma::vec to represent - * observations. While a discrete distribution only has positive integers - * (size_t) as observations, these can be converted to doubles (which is what - * arma::vec holds). This distribution internally converts those doubles back - * into size_t before comparisons. - * @endnote - */ -class DiscreteDistribution -{ - public: - /** - * Default constructor, which creates a distribution that has no observations. - */ - DiscreteDistribution() : - probabilities(std::vector(1)){ /* Nothing to do. */ } - - /** - * Define the discrete distribution as having numObservations possible - * observations. The probability in each state will be set to (1 / - * numObservations). - * - * @param numObservations Number of possible observations this distribution - * can have. - */ - DiscreteDistribution(const size_t numObservations) : - probabilities(std::vector(1, - arma::ones(numObservations) / numObservations)) - { /* Nothing to do. */ } - - /** - * Define the multidimensional discrete distribution as having numObservations possible - * observations. The probability in each state will be set to (1 / - * numObservations of each dimension). - * - * @param numObservations Number of possible observations this distribution - * can have. - */ - DiscreteDistribution(const arma::Col& numObservations) - { - for (size_t i = 0; i < numObservations.n_elem; i++) - { - const size_t numObs = size_t(numObservations[i]); - if (numObs <= 0) - { - std::ostringstream oss; - oss << "number of observations for dimension " << i << " is 0, but " - << "must be greater than 0"; - throw std::invalid_argument(oss.str()); - } - probabilities.push_back(arma::ones(numObs) / numObs); - } - } - - /** - * Define the multidimensional discrete distribution as having the given probabilities for each - * observation. - * - * @param probabilities Probabilities of each possible observation. - */ - DiscreteDistribution(const std::vector& probabilities) - { - for (size_t i = 0; i < probabilities.size(); i++) - { - arma::vec temp = probabilities[i]; - double sum = accu(temp); - if (sum > 0) - this->probabilities.push_back(temp / sum); - else - { - this->probabilities.push_back(arma::ones(temp.n_elem) - / temp.n_elem); - } - } - } - - /** - * Get the dimensionality of the distribution. - */ - size_t Dimensionality() const { return probabilities.size(); } - - /** - * Return the probability of the given observation. If the observation is - * greater than the number of possible observations, then a crash will - * probably occur -- bounds checking is not performed. - * - * @param observation Observation to return the probability of. - * @return Probability of the given observation. - */ - double Probability(const arma::vec& observation) const - { - double probability = 1.0; - // Ensure the observation has the same dimension with the probabilities - if (observation.n_elem != probabilities.size()) - { - Log::Fatal << "DiscreteDistribution::Probability(): observation has " - << "incorrect dimension " << observation.n_elem << " but should have " - << "dimension " << probabilities.size() << "!" << std::endl; - } - - for (size_t dimension = 0; dimension < observation.n_elem; dimension++) - { - // Adding 0.5 helps ensure that we cast the floating point to a size_t - // correctly. - const size_t obs = size_t(observation(dimension) + 0.5); - - // Ensure that the observation is within the bounds. - if (obs >= probabilities[dimension].n_elem) - { - Log::Fatal << "DiscreteDistribution::Probability(): received " - << "observation " << obs << "; observation must be in [0, " - << probabilities[dimension].n_elem << "] for this distribution." - << std::endl; - } - probability *= probabilities[dimension][obs]; - } - - return probability; - } - - /** - * Return the log probability of the given observation. If the observation is - * greater than the number of possible observations, then a crash will - * probably occur -- bounds checking is not performed. - * - * @param observation Observation to return the log probability of. - * @return Log probability of the given observation. - */ - double LogProbability(const arma::vec& observation) const - { - // TODO: consider storing log probabilities instead? - return log(Probability(observation)); - } - - /** - * Return a randomly generated observation (one-dimensional vector; one - * observation) according to the probability distribution defined by this - * object. - * - * @return Random observation. - */ - arma::vec Random() const; - - /** - * Estimate the probability distribution directly from the given observations. - * If any of the observations is greater than numObservations, a crash is - * likely to occur. - * - * @param observations List of observations. - */ - void Train(const arma::mat& observations); - - /** - * Estimate the probability distribution from the given observations, taking - * into account the probability of each observation actually being from this - * distribution. - * - * @param observations List of observations. - * @param probabilities List of probabilities that each observation is - * actually from this distribution. - */ - void Train(const arma::mat& observations, - const arma::vec& probabilities); - - //! Return the vector of probabilities for the given dimension. - arma::vec& Probabilities(const size_t dim = 0) { return probabilities[dim]; } - //! Modify the vector of probabilities for the given dimension. - const arma::vec& Probabilities(const size_t dim = 0) const - { return probabilities[dim]; } - - /** - * Serialize the distribution. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(probabilities); - } - - private: - //! The probabilities for each dimension; each arma::vec represents the - //! probabilities for the observations in each dimension. - std::vector probabilities; -}; - -} // namespace distribution -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/dists/gamma_distribution.hpp b/src/sdk/mlpack/include/mlpack/core/dists/gamma_distribution.hpp deleted file mode 100644 index b4d7c6e63..000000000 --- a/src/sdk/mlpack/include/mlpack/core/dists/gamma_distribution.hpp +++ /dev/null @@ -1,220 +0,0 @@ -/** - * @file gamma_distribution.hpp - * @author Yannis Mentekidis - * - * Implementation of a Gamma distribution of multidimensional data that fits - * gamma parameters (alpha, beta) to data. - * The fitting is done independently for each dataset dimension (row), based on - * the assumption each dimension is fully indepeendent. - * - * Based on "Estimating a Gamma Distribution" by Thomas P. Minka: - * research.microsoft.com/~minka/papers/minka-gamma.pdf - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef _MLPACK_CORE_DISTRIBUTIONS_GAMMA_DISTRIBUTION_HPP -#define _MLPACK_CORE_DISTRIBUTIONS_GAMMA_DISTRIBUTION_HPP - -#include -#include -#include - -namespace mlpack { -namespace distribution { - -/** - * This class represents the Gamma distribution. It supports training a Gamma - * distribution on a given dataset and accessing the fitted alpha and beta - * parameters. - * - * This class supports multidimensional Gamma distributions; however, it is - * assumed that each dimension is independent; therefore, a multidimensional - * Gamma distribution here may be seen as a set of independent - * single-dimensional Gamma distributions---and the parameters are estimated - * under this assumption. - * - * The estimation algorithm used can be found in the following paper: - * - * @code - * @techreport{minka2002estimating, - * title={Estimating a {G}amma distribution}, - * author={Minka, Thomas P.}, - * institution={Microsoft Research}, - * address={Cambridge, U.K.}, - * year={2002} - * } - * @endcode - */ -class GammaDistribution -{ - public: - /** - * Construct the Gamma distribution with the given number of dimensions - * (default 0); each parameter will be initialized to 0. - * - * @param dimensionality Number of dimensions. - */ - GammaDistribution(const size_t dimensionality = 0); - - /** - * Construct the Gamma distribution, training on the given parameters. - * - * @param data Data to train the distribution on. - * @param tol Convergence tolerance. This is *not* an absolute measure: - * It will stop the approximation once the *change* in the value is - * smaller than tol. - */ - GammaDistribution(const arma::mat& data, const double tol = 1e-8); - - /** - * Construct the Gamma distribution given two vectors alpha and beta. - * - * @param alpha The vector of alphas, one per dimension. - * @param beta The vector of betas, one per dimension. - */ - GammaDistribution(const arma::vec& alpha, const arma::vec& beta); - - /** - * Destructor. - */ - ~GammaDistribution() {} - - /** - * This function trains (fits distribution parameters) to new data or the - * dataset the object owns. - * - * @param rdata Reference data to fit parameters to. - * @param tol Convergence tolerance. This is *not* an absolute measure: - * It will stop the approximation once the *change* in the value is - * smaller than tol. - */ - void Train(const arma::mat& rdata, const double tol = 1e-8); - - /** - * Fits an alpha and beta parameter according to observation probabilities. - * This method is not yet implemented. - * - * @param observations The reference data, one observation per column - * @param probabilities The probability of each observation. One value per - * column of the observations matrix. - * @param tol Convergence tolerance. This is *not* an absolute measure: - * It will stop the approximation once the *change* in the value is - * smaller than tol. - */ - void Train(const arma::mat& observations, - const arma::vec& probabilities, - const double tol = 1e-8); - - /** - * This function trains (fits distribution parameters) to a dataset with - * pre-computed statistics logMeanx, meanLogx, meanx for each dimension. - * - * @param logMeanxVec Is each dimension's logarithm of the mean - * (log(mean(x))). - * @param meanLogxVec Is each dimension's mean of logarithms (mean(log(x))). - * @param meanxVec Is each dimension's mean (mean(x)). - * @param tol Convergence tolerance. This is *not* an absolute measure: - * It will stop the approximation once the *change* in the value is - * smaller than tol. - */ - void Train(const arma::vec& logMeanxVec, - const arma::vec& meanLogxVec, - const arma::vec& meanxVec, - const double tol = 1e-8); - - - /** - * This function returns the probability of a group of observations. - * - * The probability of the value x is - * - * \frac{x^(\alpha - 1)}{\Gamma(\alpha) * \beta^\alpha} * e ^ - * {-\frac{x}{\beta}} - * - * for one dimension. This implementation assumes each dimension is - * independent, so the product rule is used. - * - * @param observations Matrix of observations, one per column. - * @param probabilities column vector of probabilities, one per observation. - */ - void Probability(const arma::mat& observations, - arma::vec& Probabilities) const; - - /* - * This is a shortcut to the Probability(arma::mat&, arma::vec&) function - * for when we want to evaluate only the probability of one dimension of the - * gamma. - * - * @param x The 1-dimensional observation. - * @param dim The dimension for which to calculate the probability - */ - double Probability(double x, size_t dim) const; - - /** - * This function returns the logarithm of the probability of a group of - * observations. - * - * The logarithm of the probability of a value x is - * - * log(\frac{x^(\alpha - 1)}{\Gamma(\alpha) * \beta^\alpha} * e ^ - * {-\frac{x}{\beta}}) - * - * for one dimension. This implementation assumes each dimension is - * independent, so the product rule is used. - * - * @param observations Matrix of observations, one per column. - * @param logProbabilities column vector of log probabilities, one per - * observation. - */ - void LogProbability(const arma::mat& observations, - arma::vec& LogProbabilities) const; - - /** - * This function returns an observation of this distribution - */ - arma::vec Random() const; - - // Access to Gamma distribution parameters. - - //! Get the alpha parameter of the given dimension. - double Alpha(const size_t dim) const { return alpha[dim]; } - //! Modify the alpha parameter of the given dimension. - double& Alpha(const size_t dim) { return alpha[dim]; } - - //! Get the beta parameter of the given dimension. - double Beta(const size_t dim) const { return beta[dim]; } - //! Modify the beta parameter of the given dimension. - double& Beta(const size_t dim) { return beta[dim]; } - - //! Get the dimensionality of the distribution. - size_t Dimensionality() const { return alpha.n_elem; } - - private: - //! Array of fitted alphas. - arma::vec alpha; - //! Array of fitted betas. - arma::vec beta; - - /** - * This is a small function that returns true if the update of alpha is - * smaller than the tolerance ratio. - * - * @param aOld old value of parameter we want to estimate (alpha in our - * case). - * @param aNew new value of parameter (the value after 1 iteration from - * aOld). - * @param tol Convergence tolerance. Relative measure (see documentation of - * GammaDistribution::Train). - */ - inline bool Converged(const double aOld, - const double aNew, - const double tol); -}; - -} // namespace distribution -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/dists/gaussian_distribution.hpp b/src/sdk/mlpack/include/mlpack/core/dists/gaussian_distribution.hpp deleted file mode 100644 index bd3eae94f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/dists/gaussian_distribution.hpp +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @file gaussian_distribution.hpp - * @author Ryan Curtin - * @author Michael Fox - * - * Implementation of the Gaussian distribution. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DISTRIBUTIONS_GAUSSIAN_DISTRIBUTION_HPP -#define MLPACK_CORE_DISTRIBUTIONS_GAUSSIAN_DISTRIBUTION_HPP - -#include - -namespace mlpack { -namespace distribution { - -/** - * A single multivariate Gaussian distribution. - */ -class GaussianDistribution -{ - private: - //! Mean of the distribution. - arma::vec mean; - //! Positive definite covariance of the distribution. - arma::mat covariance; - //! Lower triangular factor of cov (e.g. cov = LL^T). - arma::mat covLower; - //! Cached inverse of covariance. - arma::mat invCov; - //! Cached logdet(cov). - double logDetCov; - - //! log(2pi) - static const constexpr double log2pi = 1.83787706640934533908193770912475883; - - public: - /** - * Default constructor, which creates a Gaussian with zero dimension. - */ - GaussianDistribution() : logDetCov(0.0) { /* nothing to do */ } - - /** - * Create a Gaussian distribution with zero mean and identity covariance with - * the given dimensionality. - */ - GaussianDistribution(const size_t dimension) : - mean(arma::zeros(dimension)), - covariance(arma::eye(dimension, dimension)), - covLower(arma::eye(dimension, dimension)), - invCov(arma::eye(dimension, dimension)), - logDetCov(0) - { /* Nothing to do. */ } - - /** - * Create a Gaussian distribution with the given mean and covariance. - * - * covariance is expected to be positive definite. - */ - GaussianDistribution(const arma::vec& mean, const arma::mat& covariance); - - // TODO(stephentu): do we want a (arma::vec&&, arma::mat&&) ctor? - - //! Return the dimensionality of this distribution. - size_t Dimensionality() const { return mean.n_elem; } - - /** - * Return the probability of the given observation. - */ - double Probability(const arma::vec& observation) const - { - return exp(LogProbability(observation)); - } - - /** - * Return the log probability of the given observation. - */ - double LogProbability(const arma::vec& observation) const; - - /** - * Calculates the multivariate Gaussian probability density function for each - * data point (column) in the given matrix. - * - * @param x List of observations. - * @param probabilities Output probabilities for each input observation. - */ - void Probability(const arma::mat& x, arma::vec& probabilities) const - { - arma::vec logProbabilities; - LogProbability(x, logProbabilities); - probabilities = arma::exp(logProbabilities); - } - - void LogProbability(const arma::mat& x, arma::vec& logProbabilities) const; - - /** - * Return a randomly generated observation according to the probability - * distribution defined by this object. - * - * @return Random observation from this Gaussian distribution. - */ - arma::vec Random() const; - - /** - * Estimate the Gaussian distribution directly from the given observations. - * - * @param observations List of observations. - */ - void Train(const arma::mat& observations); - - /** - * Estimate the Gaussian distribution from the given observations, taking into - * account the probability of each observation actually being from this - * distribution. - */ - void Train(const arma::mat& observations, - const arma::vec& probabilities); - - /** - * Return the mean. - */ - const arma::vec& Mean() const { return mean; } - - /** - * Return a modifiable copy of the mean. - */ - arma::vec& Mean() { return mean; } - - /** - * Return the covariance matrix. - */ - const arma::mat& Covariance() const { return covariance; } - - /** - * Set the covariance. - */ - void Covariance(const arma::mat& covariance); - - void Covariance(arma::mat&& covariance); - - /** - * Serialize the distribution. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - // We just need to serialize each of the members. - ar & BOOST_SERIALIZATION_NVP(mean); - ar & BOOST_SERIALIZATION_NVP(covariance); - ar & BOOST_SERIALIZATION_NVP(covLower); - ar & BOOST_SERIALIZATION_NVP(invCov); - ar & BOOST_SERIALIZATION_NVP(logDetCov); - } - - private: - /** - * This factors the covariance using arma::chol(). The function assumes that - * the given matrix is factorizable via the Cholesky decomposition. If not, a - * std::runtime_error will be thrown. - */ - void FactorCovariance(); -}; - -/** -* Calculates the multivariate Gaussian log probability density function for each -* data point (column) in the given matrix -* -* @param x List of observations. -* @param probabilities Output log probabilities for each input observation. -*/ -inline void GaussianDistribution::LogProbability( - const arma::mat& x, - arma::vec& logProbabilities) const -{ - // Column i of 'diffs' is the difference between x.col(i) and the mean. - arma::mat diffs = x - (mean * arma::ones(x.n_cols)); - - // Now, we only want to calculate the diagonal elements of (diffs' * cov^-1 * - // diffs). We just don't need any of the other elements. We can calculate - // the right hand part of the equation (instead of the left side) so that - // later we are referencing columns, not rows -- that is faster. - const arma::mat rhs = -0.5 * invCov * diffs; - arma::vec logExponents(diffs.n_cols); // We will now fill this. - for (size_t i = 0; i < diffs.n_cols; i++) - logExponents(i) = accu(diffs.unsafe_col(i) % rhs.unsafe_col(i)); - - const size_t k = x.n_rows; - - logProbabilities = -0.5 * k * log2pi - 0.5 * logDetCov + logExponents; -} - - -} // namespace distribution -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/dists/laplace_distribution.hpp b/src/sdk/mlpack/include/mlpack/core/dists/laplace_distribution.hpp deleted file mode 100644 index 046bf3aa7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/dists/laplace_distribution.hpp +++ /dev/null @@ -1,163 +0,0 @@ -/* - * @file laplace.hpp - * @author Zhihao Lou - * - * Laplace (double exponential) distribution used in SA. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_DISTRIBUTIONS_LAPLACE_DISTRIBUTION_HPP -#define MLPACK_CORE_DISTRIBUTIONS_LAPLACE_DISTRIBUTION_HPP - -namespace mlpack { -namespace distribution { - -/** - * The multivariate Laplace distribution centered at 0 has pdf - * - * \f[ - * f(x|\theta) = \frac{1}{2 \theta}\exp\left(-\frac{\|x - \mu\|}{\theta}\right) - * \f] - * - * given scale parameter \f$\theta\f$ and mean \f$\mu\f$. This implementation - * assumes a diagonal covariance, but a rewrite to support arbitrary covariances - * is possible. - * - * See the following paper for more information on the non-diagonal-covariance - * Laplace distribution and estimation techniques: - * - * @code - * @article{eltoft2006multivariate, - * title={{On the Multivariate Laplace Distribution}}, - * author={Eltoft, Torbj\orn and Kim, Taesu and Lee, Te-Won}, - * journal={IEEE Signal Processing Letters}, - * volume={13}, - * number={5}, - * pages={300--304}, - * year={2006} - * } - * @endcode - * - * Note that because of the diagonal covariance restriction, much of the algebra - * in the paper above becomes simplified, and the PDF takes roughly the same - * form as the univariate case. - */ -class LaplaceDistribution -{ - public: - /** - * Default constructor, which creates a Laplace distribution with zero - * dimension and zero scale parameter. - */ - LaplaceDistribution() : scale(0) { } - - /** - * Construct the Laplace distribution with the given scale and dimensionality. - * The mean is initialized to zero. - * - * @param dimensionality Dimensionality of distribution. - * @param scale Scale of distribution. - */ - LaplaceDistribution(const size_t dimensionality, const double scale) : - mean(arma::zeros(dimensionality)), scale(scale) { } - - /** - * Construct the Laplace distribution with the given mean and scale parameter. - * - * @param mean Mean of distribution. - * @param scale Scale of distribution. - */ - LaplaceDistribution(const arma::vec& mean, const double scale) : - mean(mean), scale(scale) { } - - //! Return the dimensionality of this distribution. - size_t Dimensionality() const { return mean.n_elem; } - - /** - * Return the probability of the given observation. - */ - double Probability(const arma::vec& observation) const - { - return exp(LogProbability(observation)); - } - - /** - * Return the log probability of the given observation. - */ - double LogProbability(const arma::vec& observation) const; - - /** - * Return a randomly generated observation according to the probability - * distribution defined by this object. This is inlined for speed. - * - * @return Random observation from this Laplace distribution. - */ - arma::vec Random() const - { - arma::vec result(mean.n_elem); - result.randu(); - - // Convert from uniform distribution to Laplace distribution. - // arma::sign() does not exist in Armadillo < 3.920 so we have to do this - // elementwise. - for (size_t i = 0; i < result.n_elem; ++i) - { - if (result[i] < 0.5) - result[i] = mean[i] + scale * std::log(1 + 2.0 * (result[i] - 0.5)); - else - result[i] = mean[i] - scale * std::log(1 - 2.0 * (result[i] - 0.5)); - } - - return result; - } - - /** - * Estimate the Laplace distribution directly from the given observations. - * - * @param observations List of observations. - */ - void Estimate(const arma::mat& observations); - - /** - * Estimate the Laplace distribution from the given observations, taking into - * account the probability of each observation actually being from this - * distribution. - */ - void Estimate(const arma::mat& observations, - const arma::vec& probabilities); - - //! Return the mean. - const arma::vec& Mean() const { return mean; } - //! Modify the mean. - arma::vec& Mean() { return mean; } - - //! Return the scale parameter. - double Scale() const { return scale; } - //! Modify the scale parameter. - double& Scale() { return scale; } - - /** - * Serialize the distribution. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(mean); - ar & BOOST_SERIALIZATION_NVP(scale); - } - - private: - //! Mean of the distribution. - arma::vec mean; - //! Scale parameter of the distribution. - double scale; -}; - -} // namespace distribution -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/dists/regression_distribution.hpp b/src/sdk/mlpack/include/mlpack/core/dists/regression_distribution.hpp deleted file mode 100644 index 68ad62517..000000000 --- a/src/sdk/mlpack/include/mlpack/core/dists/regression_distribution.hpp +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @file regression_distribution.hpp - * @author Michael Fox - * - * Implementation of conditional Gaussian distribution for HMM regression (HMMR) - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_DISTRIBUTIONS_REGRESSION_DISTRIBUTION_HPP -#define MLPACK_CORE_DISTRIBUTIONS_REGRESSION_DISTRIBUTION_HPP - -#include -#include -#include - -namespace mlpack { -namespace distribution { - -/** - * A class that represents a univariate conditionally Gaussian distribution. - * Can be used as an emission distribution with the hmm class to implement HMM - * regression (HMMR) as described in - * https://www.ima.umn.edu/preprints/January1994/1195.pdf - * The hmm observations should have the dependent variable in the first row, - * with the independent variables in the other rows. - */ -class RegressionDistribution -{ - private: - //! Regression function for representing conditional mean. - regression::LinearRegression rf; - //! Error distribution. - GaussianDistribution err; - - public: - /** - * Default constructor, which creates a Gaussian with zero dimension. - */ - RegressionDistribution() { /* nothing to do */ } - - /** - * Create a Conditional Gaussian distribution with conditional mean function - * obtained by running RegressionFunction on predictors, responses. - * - * @param predictors Matrix of predictors (X). - * @param responses Vector of responses (y). - */ - mlpack_deprecated RegressionDistribution(const arma::mat& predictors, - const arma::vec& responses) : - RegressionDistribution(predictors, arma::rowvec(responses.t())) - {} - - /** - * Create a Conditional Gaussian distribution with conditional mean function - * obtained by running RegressionFunction on predictors, responses. - * - * @param predictors Matrix of predictors (X). - * @param responses Vector of responses (y). - */ - RegressionDistribution(const arma::mat& predictors, - const arma::rowvec& responses) - { - rf.Train(predictors, responses); - err = GaussianDistribution(1); - arma::mat cov(1, 1); - cov(0, 0) = rf.ComputeError(predictors, responses); - err.Covariance(std::move(cov)); - } - - /** - * Serialize the distribution. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(rf); - ar & BOOST_SERIALIZATION_NVP(err); - } - - //! Return regression function. - const regression::LinearRegression& Rf() const { return rf; } - //! Modify regression function. - regression::LinearRegression& Rf() { return rf; } - - //! Return error distribution. - const GaussianDistribution& Err() const { return err; } - //! Modify error distribution. - GaussianDistribution& Err() { return err; } - - /** - * Estimate the Gaussian distribution directly from the given observations. - * - * @param observations List of observations. - */ - void Train(const arma::mat& observations); - - /** - * Estimate parameters using provided observation weights - * - * @param weights probability that given observation is from distribution - */ - mlpack_deprecated void Train(const arma::mat& observations, - const arma::vec& weights); - - /** - * Estimate parameters using provided observation weights - * - * @param weights probability that given observation is from distribution - */ - void Train(const arma::mat& observations, const arma::rowvec& weights); - - /** - * Evaluate probability density function of given observation - * - * @param observation point to evaluate probability at - */ - double Probability(const arma::vec& observation) const; - - /** - * Evaluate log probability density function of given observation - * - * @param observation point to evaluate log probability at - */ - double LogProbability(const arma::vec& observation) const { - return log(Probability(observation)); - } - - /** - * Calculate y_i for each data point in points. - * - * @param points the data points to calculate with. - * @param predictions y, will contain calculated values on completion. - */ - mlpack_deprecated void Predict(const arma::mat& points, - arma::vec& predictions) const; - - /** - * Calculate y_i for each data point in points. - * - * @param points the data points to calculate with. - * @param predictions y, will contain calculated values on completion. - */ - void Predict(const arma::mat& points, arma::rowvec& predictions) const; - - //! Return the parameters (the b vector). - const arma::vec& Parameters() const { return rf.Parameters(); } - - //! Return the dimensionality - size_t Dimensionality() const { return rf.Parameters().n_elem; } -}; - - -} // namespace distribution -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/hpt/cv_function.hpp b/src/sdk/mlpack/include/mlpack/core/hpt/cv_function.hpp deleted file mode 100644 index 0764c1d78..000000000 --- a/src/sdk/mlpack/include/mlpack/core/hpt/cv_function.hpp +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @file cv_function.hpp - * @author Kirill Mishchenko - * - * A cross-validation wrapper for optimizers. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_HPT_CV_FUNCTION_HPP -#define MLPACK_CORE_HPT_CV_FUNCTION_HPP - -#include - -namespace mlpack { -namespace hpt { - -/** - * This wrapper serves for adapting the interface of the cross-validation - * classes to the one that can be utilized by the mlpack optimizers. - * - * This class is not supposed to be used directly by users. To tune - * hyper-parameters see HyperParameterTuner. - * - * @tparam CVType A cross-validation strategy. - * @tparam MLAlgorithm The machine learning algorithm used in cross-validation. - * @tparam TotalArgs The total number of arguments that are supposed to be - * passed to the Evaluate method of a CVType object. - * @tparam BoundArgs Types of arguments (wrapped into the BoundArg struct) that - * should be passed into the Evaluate method of a CVType object but are not - * going to be passed into the Evaluate method of a CVFunction object. - */ -template -class CVFunction -{ - public: - /** - * Initialize a CVFunction object. - * - * @param cv A cross-validation object. - * @param relativeDelta Relative increase of arguments for calculation of - * partial derivatives (by the definition). The exact increase for some - * particular argument is equal to the absolute value of the argument - * multiplied by the relative increase (see also the documentation for the - * minDelta parameter). - * @param minDelta Minimum increase of arguments for calculation of partial - * derivatives (by the definition). This value is going to be used when it - * is greater than the increase calculated with the rules described in the - * documentation for the relativeDelta parameter. - * @param BoundArgs Arguments that should be passed into the Evaluate method - * of the CVType object but are not going to be passed into the Evaluate - * method of this object. - */ - CVFunction(CVType& cv, - const double relativeDelta, - const double minDelta, - const BoundArgs&... args); - - /** - * Run cross-validation with the bound and passed parameters. - * - * @param parameters Arguments (rather than the bound arguments) that should - * be passed into the Evaluate method of the CVType object. - */ - double Evaluate(const arma::mat& parameters); - - /** - * Evaluate numerically the gradient of the CVFunction with the given - * parameters. - * - * @param parameters Arguments (rather than the bound arguments) that should - * be passed into the Evaluate method of the CVType object. - * @param gradient Vector to output the gradient into. - */ - void Gradient(const arma::mat& parameters, arma::mat& gradient); - - //! Access and modify the best model so far. - MLAlgorithm& BestModel() { return bestModel; } - - private: - //! The type of tuples of BoundArgs. - using BoundArgsTupleType = std::tuple; - - //! The amount of bound arguments. - static const size_t BoundArgsAmount = - std::tuple_size::value; - - /** - * A struct that finds out whether the next argument for the Evaluate method - * of a CVType object should be a bound argument at the position BoundArgIndex - * rather than an element of parameters at the position ParamIndex. - */ - template - struct UseBoundArg; - - //! A reference to the cross-validation object. - CVType& cv; - - //! The bound arguments. - BoundArgsTupleType boundArgs; - - //! The best objective so far. - double bestObjective; - - //! The best model so far. - MLAlgorithm bestModel; - - //! Relative increase of arguments for calculation of gradient. - double relativeDelta; - - //! Minimum absolute increase of arguments for calculation of gradient. - double minDelta; - - /** - * Collect all arguments and run cross-validation. - */ - template::type> - inline double Evaluate(const arma::mat& parameters, const Args&... args); - - /** - * Run cross-validation with the collected arguments. - */ - template::type, - typename = void> - inline double Evaluate(const arma::mat& parameters, const Args&... args); - - /** - * Put the bound argument (at the BoundArgIndex position) as the next one. - */ - template::value>::type> - inline double PutNextArg(const arma::mat& parameters, const Args&... args); - - /** - * Put the element (at the ParamIndex position) of the parameters as the next - * one. - */ - template::value>::type, - typename = void> - inline double PutNextArg(const arma::mat& parameters, const Args&... args); -}; - - -} // namespace hpt -} // namespace mlpack - -// Include implementation -#include "cv_function_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/hpt/cv_function_impl.hpp b/src/sdk/mlpack/include/mlpack/core/hpt/cv_function_impl.hpp deleted file mode 100644 index 0642398d4..000000000 --- a/src/sdk/mlpack/include/mlpack/core/hpt/cv_function_impl.hpp +++ /dev/null @@ -1,168 +0,0 @@ -/** - * @file cv_function_impl.hpp - * @author Kirill Mishchenko - * - * The implementation of the class CVFunction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_HPT_CV_FUNCTION_IMPL_HPP -#define MLPACK_CORE_HPT_CV_FUNCTION_IMPL_HPP - -namespace mlpack { -namespace hpt { - -template -template -struct CVFunction::UseBoundArg< - BoundArgIndex, ParamIndex, true> -{ - using BoundArgType = typename - std::tuple_element>::type; - - static const bool value = BoundArgType::index == BoundArgIndex + ParamIndex; -}; - -template -template -struct CVFunction::UseBoundArg< - BoundArgIndex, ParamIndex, false> -{ - static const bool value = false; -}; - -template -CVFunction::CVFunction( - CVType& cv, - const double relativeDelta, - const double minDelta, - const BoundArgs&... args) : - cv(cv), - boundArgs(args...), - bestObjective(std::numeric_limits::max()), - relativeDelta(relativeDelta), - minDelta(minDelta) -{ /* Nothing left to do. */ } - -template -double CVFunction::Evaluate( - const arma::mat& parameters) -{ - return Evaluate<0, 0>(parameters); -} - -template -void CVFunction::Gradient( - const arma::mat& parameters, - arma::mat& gradient) -{ - gradient = arma::mat(arma::size(parameters)); - arma::mat increasedParameters = parameters; - double originalParametersEvaluation = Evaluate(parameters); - for (size_t i = 0; i < parameters.n_rows; ++i) - { - double delta = std::max(std::abs(parameters(i)) * relativeDelta, minDelta); - increasedParameters(i) += delta; - gradient(i) = - (Evaluate(increasedParameters) - originalParametersEvaluation) / delta; - increasedParameters(i) = parameters(i); - } -} - -template -template -double CVFunction::Evaluate( - const arma::mat& parameters, - const Args&... args) -{ - return PutNextArg(parameters, args...); -} - -template -template -double CVFunction::Evaluate( - const arma::mat& /* parameters */, - const Args&... args) -{ - double objective = cv.Evaluate(args...); - - // Change the best model if we have got a better score, or if we probably - // have not assigned any valid (trained) model yet. - if (bestObjective > objective || - bestObjective == std::numeric_limits::max()) - { - bestObjective = objective; - bestModel = std::move(cv.Model()); - } - - return objective; -} - -template -template -double CVFunction::PutNextArg( - const arma::mat& parameters, - const Args&... args) -{ - return Evaluate( - parameters, args..., std::get(boundArgs).value); -} - -template -template -double CVFunction::PutNextArg( - const arma::mat& parameters, - const Args&... args) -{ - return Evaluate( - parameters, args..., parameters(ParamIndex, 0)); -} - -} // namespace hpt -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/hpt/deduce_hp_types.hpp b/src/sdk/mlpack/include/mlpack/core/hpt/deduce_hp_types.hpp deleted file mode 100644 index a1e45a7ad..000000000 --- a/src/sdk/mlpack/include/mlpack/core/hpt/deduce_hp_types.hpp +++ /dev/null @@ -1,132 +0,0 @@ -/** - * @file deduce_hp_types.hpp - * @author Kirill Mishchenko - * - * Tools to deduce types of hyper-parameters from types of arguments in the - * Optimize method in HyperParameterTuner. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_HPT_DEDUCE_HP_TYPES_HPP -#define MLPACK_CORE_HPT_DEDUCE_HP_TYPES_HPP - -#include - -namespace mlpack { -namespace hpt { - -/** - * A type function for deducing types of hyper-parameters from types of - * arguments in the Optimize method in HyperParameterTuner. - * - * We start by putting all types of the arguments into Args, and then process - * each of them one by one and put results into the internal struct - * ResultHolder. By the end Args become empty, while ResultHolder holds the - * tuple type of hyper-parameters. - * - * Here we declare and define DeduceHyperParameterTypes for the end phase when - * Args are empty (all argument types have been processed). - */ -template -struct DeduceHyperParameterTypes -{ - template - struct ResultHolder - { - using TupleType = std::tuple; - }; -}; - -/** - * Defining DeduceHyperParameterTypes for the case when not all argument types - * have been processed, and the next one (T) is a collection type or an - * arithmetic type. - */ -template -struct DeduceHyperParameterTypes -{ - /** - * A type function to deduce the result hyper-parameter type for ArgumentType. - */ - template::value> - struct ResultHPType; - - template - struct ResultHPType - { - using Type = ArithmeticType; - }; - - /** - * A type function to check whether Type is a collection type (for that it - * should define value_type). - */ - template - struct IsCollectionType - { - using Yes = char[1]; - using No = char[2]; - - template - static Yes& Check(typename TypeToCheck::value_type*); - template - static No& Check(...); - - static const bool value = - sizeof(decltype(Check(0))) == sizeof(Yes); - }; - - template - struct ResultHPType - { - static_assert(IsCollectionType::value, - "One of the passed arguments is neither of an arithmetic type, nor of " - "a collection type, nor fixed with the Fixed function."); - - using Type = typename CollectionType::value_type; - }; - - template - struct ResultHolder - { - using TupleType = typename DeduceHyperParameterTypes::template - ResultHolder::Type>::TupleType; - }; - - using TupleType = typename ResultHolder<>::TupleType; -}; - -/** - * Defining DeduceHyperParameterTypes for the case when not all argument types - * have been processed, and the next one is the type of an argument that should - * be fixed. - */ -template -struct DeduceHyperParameterTypes, Args...> -{ - template - struct ResultHolder - { - using TupleType = typename DeduceHyperParameterTypes::template - ResultHolder::TupleType; - }; - - using TupleType = typename ResultHolder<>::TupleType; -}; - -/** - * A short alias for deducing types of hyper-parameters from types of arguments - * in the Optimize method in HyperParameterTuner. - */ -template -using TupleOfHyperParameters = - typename DeduceHyperParameterTypes::TupleType; - -} // namespace hpt -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/hpt/fixed.hpp b/src/sdk/mlpack/include/mlpack/core/hpt/fixed.hpp deleted file mode 100644 index 5d08d3b9f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/hpt/fixed.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file fixed.hpp - * @author Kirill Mishchenko - * - * Facilities for supporting fixed arguments. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_HPT_FIXED_HPP -#define MLPACK_CORE_HPT_FIXED_HPP - -#include - -#include - -namespace mlpack { -namespace hpt { - -template -struct PreFixedArg; - -/** - * Mark the given argument as one that should be fixed. It can be applied to - * arguments that are passed to the Optimize method of HyperParameterTuner. - * - * The implementation avoids data copying. If the passed argument is an l-value - * reference, we store it as a const l-value rerefence inside the returned - * PreFixedArg object. If the passed argument is an r-value reference, - * light-weight copying (by taking possession of the r-value) will be made - * during the initialization of the returned PreFixedArg object. - */ -template -PreFixedArg Fixed(T&& value) -{ - return PreFixedArg{std::forward(value)}; -} - -/** - * A struct for storing information about a fixed argument. Objects of this type - * are supposed to be passed into the CVFunction constructor. - * - * This struct is not meant to be used directly by users. Rather use the - * mlpack::hpt::Fixed function. - * - * @tparam T The type of the fixed argument. - * @tparam I The index of the fixed argument. - */ -template -struct FixedArg -{ - //! The index of the fixed argument. - static const size_t index = I; - - //! The value of the fixed argument. - const T& value; -}; - -/** - * A struct for marking arguments as ones that should be fixed (it can be useful - * for the Optimize method of HyperParameterTuner). Arguments of this type are - * supposed to be converted into structs of the type FixedArg by adding - * information about argument positions. - * - * This struct is not meant to be used directly by users. Rather use the - * mlpack::hpt::Fixed function. - */ -template -struct PreFixedArg -{ - using Type = T; - - const T value; -}; - -/** - * The specialization of the template for references. - * - * This struct is not meant to be used directly by users. Rather use the - * mlpack::hpt::Fixed function. - */ -template -struct PreFixedArg -{ - using Type = T; - - const T& value; -}; - -/** - * A type function for checking whether the given type is PreFixedArg. - */ -template -class IsPreFixedArg -{ - template - struct Implementation : std::false_type {}; - - template - struct Implementation> : std::true_type {}; - - public: - static const bool value = Implementation::type>::value; -}; - -} // namespace hpt -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/hpt/hpt.hpp b/src/sdk/mlpack/include/mlpack/core/hpt/hpt.hpp deleted file mode 100644 index 1499455c6..000000000 --- a/src/sdk/mlpack/include/mlpack/core/hpt/hpt.hpp +++ /dev/null @@ -1,356 +0,0 @@ -/** - * @file hpt.hpp - * @author Kirill Mishchenko - * - * Hyper-parameter tuning. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_HPT_HPT_HPP -#define MLPACK_CORE_HPT_HPT_HPP - -#include -#include -#include - -namespace mlpack { -namespace hpt { - -/** - * The class HyperParameterTuner for the given MLAlgorithm utilizes the provided - * Optimizer to find the values of hyper-parameters that optimize the value of - * the given Metric. The value of the Metric is calculated by performing - * cross-validation with the provided cross-validation strategy. - * - * To construct a HyperParameterTuner object you need to pass the same arguments - * as for construction of an object of the given CV class. For example, we can - * use the following code to try to find a good lambda value for - * LinearRegression. - * - * @code - * // 100-point 5-dimensional random dataset. - * arma::mat data = arma::randu(5, 100); - * // Noisy responses retrieved by a random linear transformation of data. - * arma::rowvec responses = arma::randu(5) * data + - * 0.1 * arma::randn(100); - * - * // Using 80% of data for training and remaining 20% for assessing MSE. - * double validationSize = 0.2; - * HyperParameterTuner hpt(validationSize, - * data, responses); - * - * // Finding the best value for lambda from the values 0.0, 0.001, 0.01, 0.1, - * // and 1.0. - * arma::vec lambdas{0.0, 0.001, 0.01, 0.1, 1.0}; - * double bestLambda; - * std::tie(bestLambda) = hpt.Optimize(lambdas); - * @endcode - * - * When some hyper-parameters should not be optimized, you can specify values - * for them with the Fixed function as in the following example of finding good - * lambda1 and lambda2 values for LARS. - * - * @code - * HyperParameterTuner hpt2(validationSize, data, - * responses); - * - * bool transposeData = true; - * bool useCholesky = false; - * arma::vec lambda1Set{0.0, 0.001, 0.01, 0.1, 1.0}; - * arma::vec lambda2Set{0.0, 0.002, 0.02, 0.2, 2.0}; - * - * double bestLambda1, bestLambda2; - * std::tie(bestLambda1, bestLambda2) = hpt2.Optimize(Fixed(transposeData), - * Fixed(useCholesky), lambda1Set, lambda2Set); - * @endcode - * - * @tparam MLAlgorithm A machine learning algorithm. - * @tparam Metric A metric to assess the quality of a trained model. - * @tparam CV A cross-validation strategy used to assess a set of - * hyper-parameters. - * @tparam OptimizerType An optimization strategy (GridSearch and - * GradientDescent are supported). - * @tparam MatType The type of data. - * @tparam PredictionsType The type of predictions (should be passed when the - * predictions type is a template parameter in Train methods of the given - * MLAlgorithm; arma::Row will be used otherwise). - * @tparam WeightsType The type of weights (should be passed when weighted - * learning is supported, and the weights type is a template parameter in - * Train methods of the given MLAlgorithm; arma::vec will be used - * otherwise). - */ -template class CV, - typename OptimizerType = mlpack::optimization::GridSearch, - typename MatType = arma::mat, - typename PredictionsType = - typename cv::MetaInfoExtractor::PredictionsType, - typename WeightsType = - typename cv::MetaInfoExtractor::WeightsType> -class HyperParameterTuner -{ - public: - /** - * Create a HyperParameterTuner object by passing constructor arguments for - * the given cross-validation strategy (the CV class). - * - * @param args Constructor arguments for the given cross-validation - * strategy (the CV class). - */ - template - HyperParameterTuner(const CVArgs& ...args); - - //! Access and modify the optimizer. - OptimizerType& Optimizer() { return optimizer; } - - /** - * Get relative increase of arguments for calculation of partial - * derivatives (by the definition) in gradient-based optimization. The exact - * increase for some particular argument is equal to the absolute value of the - * argument multiplied by the relative increase (see also the documentation - * for MinDelta()). - * - * The default value is 0.01. - */ - double RelativeDelta() const { return relativeDelta; } - - /** - * Modify relative increase of arguments for calculation of partial - * derivatives (by the definition) in gradient-based optimization. The exact - * increase for some particular argument is equal to the absolute value of the - * argument multiplied by the relative increase (see also the documentation - * for MinDelta()). - * - * The default value is 0.01. - */ - double& RelativeDelta() { return relativeDelta; } - - /** - * Get minimum increase of arguments for calculation of partial derivatives - * (by the definition) in gradient-based optimization. This value is going to - * be used when it is greater than the increase calculated with the rules - * described in the documentation for RelativeDelta(). - * - * The default value is 1e-10. - */ - double MinDelta() const { return minDelta; } - - /** - * Modify minimum increase of arguments for calculation of partial derivatives - * (by the definition) in gradient-based optimization. This value is going to - * be used when it is greater than the increase calculated with the rules - * described in the documentation for RelativeDelta(). - * - * The default value is 1e-10. - */ - double& MinDelta() { return minDelta; } - - /** - * Find the best hyper-parameters by using the given Optimizer. For each - * hyper-parameter one of the following should be passed as an argument. - * 1. A set of values to choose from (when using GridSearch as an optimizer). - * The set of values should be an STL-compatible container (it should - * provide begin() and end() methods returning iterators). - * 2. A starting value (when using any other optimizer than GridSearch). - * 3. A value fixed by using the function mlpack::hpt::Fixed. In this case the - * hyper-parameter will not be optimized. - * - * All arguments should be passed in the same order as if the corresponding - * hyper-parameters would be passed into the Evaluate method of the given CV - * class (in the order as they appear in the constructor(s) of the given - * MLAlgorithm). Also, arguments for all required hyper-parameters (ones that - * don't have default values in the corresponding MLAlgorithm constructor) - * should be provided. - * - * The method returns a tuple of values for hyper-parameters that haven't been - * fixed. - * - * @param args Arguments corresponding to hyper-parameters (see the method - * description for more information). - */ - template - TupleOfHyperParameters Optimize(const Args&... args); - - //! Get the performance measurement of the best model from the last run. - double BestObjective() const { return bestObjective; } - - //! Get the best model from the last run. - const MLAlgorithm& BestModel() const { return bestModel; } - - //! Modify the best model from the last run. - MLAlgorithm& BestModel() { return bestModel; } - - private: - /** - * A decorator that returns negated values of the original metric. - */ - template - struct Negated - { - static double Evaluate(MLAlgorithm& model, - const MatType& xs, - const PredictionsType& ys) - { return -OriginalMetric::Evaluate(model, xs, ys); } - }; - - //! A short alias for the full type of the cross-validation. - using CVType = typename std::conditional, - CV, MatType, PredictionsType, - WeightsType>>::type; - - - //! The cross-validation object for assessing sets of hyper-parameters. - CVType cv; - - //! The optimizer. - OptimizerType optimizer; - - //! The best objective from the last run. - double bestObjective; - - //! The best model from the last run. - MLAlgorithm bestModel; - - /** - * The relative increase of arguments for calculation of gradient in - * CVFunction. - */ - double relativeDelta; - - /** - * The minimum increase of arguments for calculation of gradient in - * CVFunction. - */ - double minDelta; - - /** - * A type function to check whether the element I of the tuple type is a - * PreFixedArg. - */ - template - using IsPreFixed = IsPreFixedArg::type>; - - /** - * A type function to check whether the element I of the tuple type is an - * arithmetic type. - */ - template - using IsArithmetic = std::is_arithmetic::type>::type>; - - /** - * The set of methods to initialize auxiliary objects (a CVFunction object and - * the datasetInfo parameter) and run optimization to find the best - * hyper-parameters. - * - * This template is called when we are ready to run optimization. - */ - template::value>> - inline void InitAndOptimize( - const ArgsTuple& args, - arma::mat& bestParams, - data::DatasetMapper& datasetInfo, - FixedArgs... fixedArgs); - - /** - * The set of methods to initialize auxiliary objects (a CVFunction object and - * the datasetInfo parameter) and run optimization to find the best - * hyper-parameters. - * - * This template is called when the next argument should be fixed (should not - * be optimized). - */ - template::value)>, - typename = std::enable_if_t::value>> - inline void InitAndOptimize( - const ArgsTuple& args, - arma::mat& bestParams, - data::DatasetMapper& datasetInfo, - FixedArgs... fixedArgs); - - /** - * The set of methods to initialize auxiliary objects (a CVFunction object and - * the datasetInfo parameter) and run optimization to find the best - * hyper-parameters. - * - * This template is called when the next argument is of an arithmetic type and - * should be used as an initial value for the hyper-parameter. - */ - template::value)>, - typename = std::enable_if_t::value && - IsArithmetic::value>, - typename = void> - inline void InitAndOptimize( - const ArgsTuple& args, - arma::mat& bestParams, - data::DatasetMapper& datasetInfo, - FixedArgs... fixedArgs); - - /** - * The set of methods to initialize auxiliary objects (a CVFunction object and - * the datasetInfo parameter) and run optimization to find the best - * hyper-parameters. - * - * This template is called when the next argument should be used to specify - * possible values for the hyper-parameter in datasetInfo. - */ - template::value)>, - typename = std::enable_if_t::value && - !IsArithmetic::value>, - typename = void, - typename = void> - inline void InitAndOptimize( - const ArgsTuple& args, - arma::mat& bestParams, - data::DatasetMapper& datasetInfo, - FixedArgs... fixedArgs); - - /** - * Gather all elements of vector in an argument list and use them to create a - * tuple. - */ - template::value)>> - inline TupleType VectorToTuple(const arma::vec& vector, const Args&... args); - - /** - * Create a tuple from args. - */ - template::value>, - typename = void> - inline TupleType VectorToTuple(const arma::vec& vector, const Args&... args); -}; - -} // namespace hpt -} // namespace mlpack - -// Include implementation -#include "hpt_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/hpt/hpt_impl.hpp b/src/sdk/mlpack/include/mlpack/core/hpt/hpt_impl.hpp deleted file mode 100644 index 16f4b9291..000000000 --- a/src/sdk/mlpack/include/mlpack/core/hpt/hpt_impl.hpp +++ /dev/null @@ -1,234 +0,0 @@ -/** - * @file hpt_impl.hpp - * @author Kirill Mishchenko - * - * Implementation of hyper-parameter tuning. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_HPT_HPT_IMPL_HPP -#define MLPACK_CORE_HPT_HPT_IMPL_HPP - -#include - -namespace mlpack { -namespace hpt { - -template class CV, - typename Optimizer, - typename MatType, - typename PredictionsType, - typename WeightsType> -template -HyperParameterTuner::HyperParameterTuner(const CVArgs&... args) : - cv(args...), relativeDelta(0.01), minDelta(1e-10) {} - -template class CV, - typename Optimizer, - typename MatType, - typename PredictionsType, - typename WeightsType> -template -TupleOfHyperParameters HyperParameterTuner::Optimize( - const Args&... args) -{ - static const size_t numberOfParametersToOptimize = - std::tuple_size>::value; - data::IncrementPolicy policy(true); - data::DatasetMapper datasetInfo(policy, - numberOfParametersToOptimize); - - arma::mat bestParameters(numberOfParametersToOptimize, 1); - const auto argsTuple = std::tie(args...); - - InitAndOptimize<0>(argsTuple, bestParameters, datasetInfo); - - return VectorToTuple, 0>(bestParameters); -} - -template class CV, - typename Optimizer, - typename MatType, - typename PredictionsType, - typename WeightsType> -template -void HyperParameterTuner::InitAndOptimize( - const ArgsTuple& /* args */, - arma::mat& bestParams, - data::DatasetMapper& datasetInfo, - FixedArgs... fixedArgs) -{ - static const size_t totalArgs = std::tuple_size::value; - - CVFunction - cvFunction(cv, relativeDelta, minDelta, fixedArgs...); - bestObjective = Metric::NeedsMinimization? - optimizer.Optimize(cvFunction, bestParams, datasetInfo) : - -optimizer.Optimize(cvFunction, bestParams, datasetInfo); - bestModel = std::move(cvFunction.BestModel()); -} - -template class CV, - typename Optimizer, - typename MatType, - typename PredictionsType, - typename WeightsType> -template -void HyperParameterTuner::InitAndOptimize( - const ArgsTuple& args, - arma::mat& bestParams, - data::DatasetMapper& datasetInfo, - FixedArgs... fixedArgs) -{ - using PreFixedArgT = typename std::remove_reference< - typename std::tuple_element::type>::type; - using FixedArgT = FixedArg; - - InitAndOptimize(args, bestParams, datasetInfo, fixedArgs..., - FixedArgT{std::get(args).value}); -} - -template class CV, - typename Optimizer, - typename MatType, - typename PredictionsType, - typename WeightsType> -template -void HyperParameterTuner::InitAndOptimize( - const ArgsTuple& args, - arma::mat& bestParams, - data::DatasetMapper& datasetInfo, - FixedArgs... fixedArgs) -{ - static const size_t dimension = - I - std::tuple_size>::value; - datasetInfo.Type(dimension) = data::Datatype::numeric; - bestParams(dimension) = std::get(args); - - InitAndOptimize(args, bestParams, datasetInfo, fixedArgs...); -} - -template class CV, - typename Optimizer, - typename MatType, - typename PredictionsType, - typename WeightsType> -template -void HyperParameterTuner::InitAndOptimize( - const ArgsTuple& args, - arma::mat& bestParams, - data::DatasetMapper& datasetInfo, - FixedArgs... fixedArgs) -{ - static const size_t dimension = - I - std::tuple_size>::value; - for (auto value : std::get(args)) - datasetInfo.MapString(value, dimension); - - if (datasetInfo.NumMappings(dimension) == 0) - { - std::ostringstream oss; - oss << "HyperParameterTuner::Optimize(): the collection passed as the " - << "argument " << I + 1 << " is empty" << std::endl; - throw std::invalid_argument(oss.str()); - } - - InitAndOptimize(args, bestParams, datasetInfo, fixedArgs...); -} - -template class CV, - typename Optimizer, - typename MatType, - typename PredictionsType, - typename WeightsType> -template -TupleType HyperParameterTuner::VectorToTuple( - const arma::vec& vector, const Args&... args) -{ - return VectorToTuple(vector, args..., vector(I)); -} - -template class CV, - typename Optimizer, - typename MatType, - typename PredictionsType, - typename WeightsType> -template -TupleType HyperParameterTuner::VectorToTuple( - const arma::vec& /* vector */, const Args&... args) -{ - return TupleType(args...); -} - -} // namespace hpt -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/cosine_distance.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/cosine_distance.hpp deleted file mode 100644 index 1f19d8a31..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/cosine_distance.hpp +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @file cosine_distance.hpp - * @author Ryan Curtin - * - * This implements the cosine distance (or cosine similarity) between two - * vectors, which is a measure of the angle between the two vectors. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_COSINE_DISTANCE_HPP -#define MLPACK_CORE_KERNELS_COSINE_DISTANCE_HPP - -#include -#include - -namespace mlpack { -namespace kernel { - -/** - * The cosine distance (or cosine similarity). It is defined by - * - * @f[ - * d(a, b) = \frac{a^T b}{|| a || || b ||} - * @f] - * - * and this class assumes the standard L2 inner product. - */ -class CosineDistance -{ - public: - /** - * Computes the cosine distance between two points. - * - * @param a First vector. - * @param b Second vector. - * @return d(a, b). - */ - template - static double Evaluate(const VecTypeA& a, const VecTypeB& b); - - //! Serialize the class (there's nothing to save). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -//! Kernel traits for the cosine distance. -template<> -class KernelTraits -{ - public: - //! The cosine kernel is normalized: K(x, x) = 1 for all x. - static const bool IsNormalized = true; - - //! The cosine kernel doesn't include a squared distance. - static const bool UsesSquaredDistance = false; -}; - -} // namespace kernel -} // namespace mlpack - -// Include implementation. -#include "cosine_distance_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/cosine_distance_impl.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/cosine_distance_impl.hpp deleted file mode 100644 index 2cb10ff23..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/cosine_distance_impl.hpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @file cosine_distance_impl.hpp - * @author Ryan Curtin - * - * This implements the cosine distance. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_COSINE_DISTANCE_IMPL_HPP -#define MLPACK_CORE_KERNELS_COSINE_DISTANCE_IMPL_HPP - -#include "cosine_distance.hpp" - -namespace mlpack { -namespace kernel { - -template -double CosineDistance::Evaluate(const VecTypeA& a, const VecTypeB& b) -{ - // Since we are using the L2 inner product, this is easy. But we have to make - // sure we aren't dividing by zero (if we are, then the cosine similarity is - // 0: we reason this value because the cosine distance is just a normalized - // dot product; take away the normalization, and if ||a|| or ||b|| is equal to - // 0, then a^T b is zero too). - const double denominator = norm(a, 2) * norm(b, 2); - if (denominator == 0.0) - return 0; - else - return dot(a, b) / denominator; -} - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/epanechnikov_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/epanechnikov_kernel.hpp deleted file mode 100644 index e2b69ec27..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/epanechnikov_kernel.hpp +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @file epanechnikov_kernel.hpp - * @author Neil Slagle - * - * Definition of the Epanechnikov kernel. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_EPANECHNIKOV_KERNEL_HPP -#define MLPACK_CORE_KERNELS_EPANECHNIKOV_KERNEL_HPP - -#include -#include - -namespace mlpack { -namespace kernel { - -/** - * The Epanechnikov kernel, defined as - * - * @f[ - * K(x, y) = \max \{0, 1 - || x - y ||^2_2 / b^2 \} - * @f] - * - * where @f$ b @f$ is the bandwidth the of the kernel (defaults to 1.0). - */ -class EpanechnikovKernel -{ - public: - /** - * Instantiate the Epanechnikov kernel with the given bandwidth (default 1.0). - * - * @param bandwidth Bandwidth of the kernel. - */ - EpanechnikovKernel(const double bandwidth = 1.0) : - bandwidth(bandwidth), - inverseBandwidthSquared(1.0 / (bandwidth * bandwidth)) - { } - - /** - * Evaluate the Epanechnikov kernel on the given two inputs. - * - * @tparam VecTypeA Type of first vector. - * @tparam VecTypeB Type of second vector. - * @param a One input vector. - * @param b The other input vector. - */ - template - double Evaluate(const VecTypeA& a, const VecTypeB& b) const; - - /** - * Evaluate the Epanechnikov kernel given that the distance between the two - * input points is known. - */ - double Evaluate(const double distance) const; - - /** - * Evaluate the Gradient of Epanechnikov kernel - * given that the distance between the two - * input points is known. - */ - double Gradient(const double distance) const; - - /** - * Evaluate the Gradient of Epanechnikov kernel - * given that the squared distance between the two - * input points is known. - */ - double GradientForSquaredDistance(const double distanceSquared) const; - /** - * Obtains the convolution integral [integral of K(||x-a||) K(||b-x||) dx] - * for the two vectors. - * - * @tparam VecType Type of vector (arma::vec, arma::spvec should be expected). - * @param a First vector. - * @param b Second vector. - * @return the convolution integral value. - */ - template - double ConvolutionIntegral(const VecTypeA& a, const VecTypeB& b); - - /** - * Compute the normalizer of this Epanechnikov kernel for the given dimension. - * - * @param dimension Dimension to calculate the normalizer for. - */ - double Normalizer(const size_t dimension); - - /** - * Serialize the kernel. - */ - template - void serialize(Archive& ar, const unsigned int version); - - private: - //! Bandwidth of the kernel. - double bandwidth; - //! Cached value of the inverse bandwidth squared (to speed up computation). - double inverseBandwidthSquared; -}; - -//! Kernel traits for the Epanechnikov kernel. -template<> -class KernelTraits -{ - public: - //! The Epanechnikov kernel is normalized: K(x, x) = 1 for all x. - static const bool IsNormalized = true; - //! The Epanechnikov kernel includes a squared distance. - static const bool UsesSquaredDistance = true; -}; - -} // namespace kernel -} // namespace mlpack - -// Include implementation. -#include "epanechnikov_kernel_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/epanechnikov_kernel_impl.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/epanechnikov_kernel_impl.hpp deleted file mode 100644 index 2973aa420..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/epanechnikov_kernel_impl.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file epanechnikov_kernel_impl.hpp - * @author Neil Slagle - * - * Implementation of template-based Epanechnikov kernel functions. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_EPANECHNIKOV_KERNEL_IMPL_HPP -#define MLPACK_CORE_KERNELS_EPANECHNIKOV_KERNEL_IMPL_HPP - -// In case it hasn't already been included. -#include "epanechnikov_kernel.hpp" -#include - -#include - -namespace mlpack { -namespace kernel { - -template -inline double EpanechnikovKernel::Evaluate(const VecTypeA& a, const VecTypeB& b) - const -{ - return std::max(0.0, 1.0 - metric::SquaredEuclideanDistance::Evaluate(a, b) - * inverseBandwidthSquared); -} - -/** - * Obtains the convolution integral [integral of K(||x-a||) K(||b-x||) dx] - * for the two vectors. - * - * @tparam VecTypeA Type of first vector (arma::vec, arma::sp_vec should be - * expected). - * @tparam VecTypeB Type of second vector (arma::vec, arma::sp_vec). - * @param a First vector. - * @param b Second vector. - * @return the convolution integral value. - */ -template -double EpanechnikovKernel::ConvolutionIntegral(const VecTypeA& a, - const VecTypeB& b) -{ - double distance = sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b)); - if (distance >= 2.0 * bandwidth) - return 0.0; - - double volumeSquared = std::pow(Normalizer(a.n_rows), 2.0); - - switch (a.n_rows) - { - case 1: - return 1.0 / volumeSquared * - (16.0 / 15.0 * bandwidth - 4.0 * distance * distance / - (3.0 * bandwidth) + 2.0 * distance * distance * distance / - (3.0 * bandwidth * bandwidth) - - std::pow(distance, 5.0) / (30.0 * std::pow(bandwidth, 4.0))); - break; - case 2: - return 1.0 / volumeSquared * - ((2.0 / 3.0 * bandwidth * bandwidth - distance * distance) * - asin(sqrt(1.0 - std::pow(distance / (2.0 * bandwidth), 2.0))) + - sqrt(4.0 * bandwidth * bandwidth - distance * distance) * - (distance / 6.0 + 2.0 / 9.0 * distance * - std::pow(distance / bandwidth, 2.0) - distance / 72.0 * - std::pow(distance / bandwidth, 4.0))); - break; - default: - Log::Fatal << "EpanechnikovKernel::ConvolutionIntegral(): dimension " - << a.n_rows << " not supported."; - return -1.0; // This line will not execute. - break; - } -} - -//! Serialize the kernel. -template -void EpanechnikovKernel::serialize(Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(bandwidth); - ar & BOOST_SERIALIZATION_NVP(inverseBandwidthSquared); -} - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/example_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/example_kernel.hpp deleted file mode 100644 index d86456a18..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/example_kernel.hpp +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @file example_kernel.hpp - * @author Ryan Curtin - * - * This is an example kernel. If you are making your own kernel, follow the - * outline specified in this file. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_EXAMPLE_KERNEL_HPP -#define MLPACK_CORE_KERNELS_EXAMPLE_KERNEL_HPP - -#include - -namespace mlpack { - -/** - * @brief Kernel functions. - * - * This namespace contains kernel functions, which evaluate some kernel function - * @f$ K(x, y) @f$ for some arbitrary vectors @f$ x @f$ and @f$ y @f$ of the - * same dimension. The single restriction on the function @f$ K(x, y) @f$ is - * that it must satisfy Mercer's condition: - * - * @f[ - * \int \int K(x, y) g(x) g(y) dx dy \ge 0 - * @f] - * - * for all square integrable functions @f$ g(x) @f$. - * - * The kernels in this namespace all implement the KernelType policy. For more - * information, see \ref kernels "The KernelType policy documentation". - */ -namespace kernel { - -/** - * An example kernel function. This is not a useful kernel, but it implements - * the two functions necessary to satisfy the Kernel policy (so that a class can - * be used whenever an mlpack method calls for a `typename Kernel` template - * parameter. - * - * All that is necessary is a constructor and an `Evaluate()` function. More - * methods could be added; for instance, one useful idea is a constructor which - * takes parameters for a kernel (for instance, the width of the Gaussian for a - * Gaussian kernel). However, mlpack methods cannot count on these various - * constructors existing, which is why most methods allow passing an - * already-instantiated kernel object (and by default the method will construct - * the kernel with the default constructor). So, for instance, - * - * @code - * GaussianKernel k(5.0); - * KernelPCA kpca(dataset, k); - * @endcode - * - * will set up kernel PCA using a Gaussian kernel with a width of 5.0, but - * - * @code - * KernelPCA kpca(dataset); - * @endcode - * - * will create the kernel with the default constructor. It is important (but - * not strictly mandatory) that your default constructor still gives a working - * kernel. - * - * @note - * Not all kernels require state. For instance, the regular dot product needs - * no parameters. In that case, no local variables are necessary and - * `Evaluate()` can (and should) be declared static. However, for greater - * generalization, mlpack methods expect all kernels to require state and hence - * must store instantiated kernel functions; this is why a default constructor - * is necessary. - * @endnote - */ -class ExampleKernel -{ - public: - /** - * The default constructor, which takes no parameters. Because our simple - * example kernel has no internal parameters that need to be stored, the - * constructor does not need to do anything. For a more complex example, see - * the GaussianKernel, which stores an internal parameter. - */ - ExampleKernel() { } - - /** - * Evaluates the kernel function for two given vectors. In this case, because - * our simple example kernel has no internal parameters, we can declare the - * function static. For a more complex example which cannot be declared - * static, see the GaussianKernel, which stores an internal parameter. - * - * @tparam VecTypeA Type of first vector (arma::vec, arma::sp_vec should be - * expected). - * @tparam VecTypeB Type of second vector (arma::vec, arma::sp_vec). - * @param a First vector. - * @param b Second vector. - * @return K(a, b). - */ - template - static double Evaluate(const VecTypeA& /* a */, const VecTypeB& /* b */) - { return 0; } - - /** - * Serializes the kernel. In this case, the kernel has no members, so we do - * not need to do anything at all. - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } - - /** - * Obtains the convolution integral [integral K(||x-a||)K(||b-x||)dx] - * for the two vectors. In this case, because - * our simple example kernel has no internal parameters, we can declare the - * function static. For a more complex example which cannot be declared - * static, see the GaussianKernel, which stores an internal parameter. - * - * @tparam VecTypeA Type of first vector (arma::vec, arma::sp_vec should be - * expected). - * @tparam VecTypeB Type of second vector (arma::vec, arma::sp_vec). - * @param a First vector. - * @param b Second vector. - * @return the convolution integral value. - */ - template - static double ConvolutionIntegral(const VecTypeA& /* a */, - const VecTypeB& /* b */) { return 0; } - - /** - * Obtains the normalizing volume for the kernel with dimension $dimension$. - * In this case, because our simple example kernel has no internal parameters, - * we can declare the function static. For a more complex example which - * cannot be declared static, see the GaussianKernel, which stores an internal - * parameter. - * - * @param dimension the dimension of the space. - * @return the normalization constant. - */ - static double Normalizer() { return 0; } - - // Modified to remove unused variable "dimension" - // static double Normalizer(size_t dimension=1) { return 0; } -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/gaussian_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/gaussian_kernel.hpp deleted file mode 100644 index c748311f2..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/gaussian_kernel.hpp +++ /dev/null @@ -1,179 +0,0 @@ -/** - * @file gaussian_kernel.hpp - * @author Wei Guan - * @author James Cline - * @author Ryan Curtin - * - * Implementation of the Gaussian kernel (GaussianKernel). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP -#define MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP - -#include -#include -#include - -namespace mlpack { -namespace kernel { - -/** - * The standard Gaussian kernel. Given two vectors @f$ x @f$, @f$ y @f$, and a - * bandwidth @f$ \mu @f$ (set in the constructor), - * - * @f[ - * K(x, y) = \exp(-\frac{|| x - y ||^2}{2 \mu^2}). - * @f] - * - * The implementation is all in the header file because it is so simple. - */ -class GaussianKernel -{ - public: - /** - * Default constructor; sets bandwidth to 1.0. - */ - GaussianKernel() : bandwidth(1.0), gamma(-0.5) - { } - - /** - * Construct the Gaussian kernel with a custom bandwidth. - * - * @param bandwidth The bandwidth of the kernel (@f$\mu@f$). - */ - GaussianKernel(const double bandwidth) : - bandwidth(bandwidth), - gamma(-0.5 * pow(bandwidth, -2.0)) - { } - - /** - * Evaluation of the Gaussian kernel. This could be generalized to use any - * distance metric, not the Euclidean distance, but for now, the Euclidean - * distance is used. - * - * @tparam VecType Type of vector (likely arma::vec or arma::spvec). - * @param a First vector. - * @param b Second vector. - * @return K(a, b) using the bandwidth (@f$\mu@f$) specified in the - * constructor. - */ - template - double Evaluate(const VecTypeA& a, const VecTypeB& b) const - { - // The precalculation of gamma saves us a little computation time. - return exp(gamma * metric::SquaredEuclideanDistance::Evaluate(a, b)); - } - - /** - * Evaluation of the Gaussian kernel given the distance between two points. - * - * @param t The distance between the two points the kernel is evaluated on. - * @return K(t) using the bandwidth (@f$\mu@f$) specified in the - * constructor. - */ - double Evaluate(const double t) const - { - // The precalculation of gamma saves us a little computation time. - return exp(gamma * std::pow(t, 2.0)); - } - - /** - * Evaluation of the gradient of Gaussian kernel - * given the distance between two points. - * - * @param t The distance between the two points the kernel is evaluated on. - * @return K(t) using the bandwidth (@f$\mu@f$) specified in the - * constructor. - */ - double Gradient(const double t) const { - return 2 * t * gamma * exp(gamma * std::pow(t, 2.0)); - } - - /** - * Evaluation of the gradient of Gaussian kernel - * given the squared distance between two points. - * - * @param t The squared distance between the two points - * @return K(t) using the bandwidth (@f$\mu@f$) specified in the - * constructor. - */ - double GradientForSquaredDistance(const double t) const { - return gamma * exp(gamma * t); - } - - /** - * Obtain the normalization constant of the Gaussian kernel. - * - * @param dimension - * @return the normalization constant - */ - double Normalizer(const size_t dimension) - { - return pow(sqrt(2.0 * M_PI) * bandwidth, (double) dimension); - } - - /** - * Obtain a convolution integral of the Gaussian kernel. - * - * @param a First vector. - * @param b Second vector. - * @return The convolution integral. - */ - template - double ConvolutionIntegral(const VecTypeA& a, const VecTypeB& b) - { - return Evaluate(sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b) / - 2.0)) / (Normalizer(a.n_rows) * pow(2.0, (double) a.n_rows / 2.0)); - } - - - //! Get the bandwidth. - double Bandwidth() const { return bandwidth; } - - //! Modify the bandwidth. This takes an argument because we must update the - //! precalculated constant (gamma). - void Bandwidth(const double bandwidth) - { - this->bandwidth = bandwidth; - this->gamma = -0.5 * pow(bandwidth, -2.0); - } - - //! Get the precalculated constant. - double Gamma() const { return gamma; } - - //! Serialize the kernel. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(bandwidth); - ar & BOOST_SERIALIZATION_NVP(gamma); - } - - private: - //! Kernel bandwidth. - double bandwidth; - - //! Precalculated constant depending on the bandwidth; - //! @f$ \gamma = -\frac{1}{2 \mu^2} @f$. - double gamma; -}; - -//! Kernel traits for the Gaussian kernel. -template<> -class KernelTraits -{ - public: - //! The Gaussian kernel is normalized: K(x, x) = 1 for all x. - static const bool IsNormalized = true; - //! The Gaussian kernel includes a squared distance. - static const bool UsesSquaredDistance = true; -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/hyperbolic_tangent_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/hyperbolic_tangent_kernel.hpp deleted file mode 100644 index 6fdd4f3d8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/hyperbolic_tangent_kernel.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file hyperbolic_tangent_kernel.hpp - * @author Ajinkya Kale - * - * Implementation of the hyperbolic tangent kernel. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_HYPERBOLIC_TANGENT_KERNEL_HPP -#define MLPACK_CORE_KERNELS_HYPERBOLIC_TANGENT_KERNEL_HPP - -#include - -namespace mlpack { -namespace kernel { - -/** - * Hyperbolic tangent kernel. For any two vectors @f$ x @f$, @f$ y @f$ and a - * given scale @f$ s @f$ and offset @f$ t @f$ - * - * @f[ - * K(x, y) = \tanh(s + t) - * @f] - */ -class HyperbolicTangentKernel -{ - public: - /** - * This constructor sets the default scale to 1.0 and offset to 0.0. - */ - HyperbolicTangentKernel() : scale(1.0), offset(0.0) - { } - - /** - * Construct the hyperbolic tangent kernel with custom scale factor and - * offset. - * - * @param scale Scaling factor for . - * @param offset Kernel offset. - */ - HyperbolicTangentKernel(double scale, double offset) : - scale(scale), offset(offset) - { } - - /** - * Evaluate the hyperbolic tangent kernel. This evaluation uses Armadillo's - * dot() function. - * - * @tparam VecTypeA Type of first vector (should be arma::vec or - * arma::sp_vec). - * @tparam VecTypeB Type of second vector (arma::vec / arma::sp_vec). - * @param a First vector. - * @param b Second vector. - * @return K(a, b). - */ - template - double Evaluate(const VecTypeA& a, const VecTypeB& b) - { - return tanh(scale * arma::dot(a, b) + offset); - } - - //! Get scale factor. - double Scale() const { return scale; } - //! Modify scale factor. - double& Scale() { return scale; } - - //! Get offset for the kernel. - double Offset() const { return offset; } - //! Modify offset for the kernel. - double& Offset() { return offset; } - - //! Serialize the kernel. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(scale); - ar & BOOST_SERIALIZATION_NVP(offset); - } - - private: - double scale; - double offset; -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/kernel_traits.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/kernel_traits.hpp deleted file mode 100644 index 2636f690c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/kernel_traits.hpp +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @file kernel_traits.hpp - * @author Ryan Curtin - * - * This provides the KernelTraits class, a template class to get information - * about various kernels. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_KERNEL_TRAITS_HPP -#define MLPACK_CORE_KERNELS_KERNEL_TRAITS_HPP - -namespace mlpack { -namespace kernel { - -/** - * This is a template class that can provide information about various kernels. - * By default, this class will provide the weakest possible assumptions on - * kernels, and each kernel should override values as necessary. If a kernel - * doesn't need to override a value, then there's no need to write a - * KernelTraits specialization for that class. - */ -template -class KernelTraits -{ - public: - /** - * If true, then the kernel is normalized: K(x, x) = K(y, y) = 1 for all x. - */ - static const bool IsNormalized = false; - - /** - * If true, then the kernel include a squared distance, ||x - y||^2 . - */ - static const bool UsesSquaredDistance = false; -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/laplacian_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/laplacian_kernel.hpp deleted file mode 100644 index b8377fdf0..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/laplacian_kernel.hpp +++ /dev/null @@ -1,125 +0,0 @@ -/** - * @file laplacian_kernel.hpp - * @author Ajinkya Kale - * - * Implementation of the Laplacian kernel (LaplacianKernel). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_LAPLACIAN_KERNEL_HPP -#define MLPACK_CORE_KERNELS_LAPLACIAN_KERNEL_HPP - -#include - -namespace mlpack { -namespace kernel { - -/** - * The standard Laplacian kernel. Given two vectors @f$ x @f$, @f$ y @f$, and a - * bandwidth @f$ \mu @f$ (set in the constructor), - * - * @f[ - * K(x, y) = \exp(-\frac{|| x - y ||}{\mu}). - * @f] - * - * The implementation is all in the header file because it is so simple. - */ -class LaplacianKernel -{ - public: - /** - * Default constructor; sets bandwidth to 1.0. - */ - LaplacianKernel() : bandwidth(1.0) - { } - - /** - * Construct the Laplacian kernel with a custom bandwidth. - * - * @param bandwidth The bandwidth of the kernel (@f$\mu@f$). - */ - LaplacianKernel(double bandwidth) : - bandwidth(bandwidth) - { } - - /** - * Evaluation of the Laplacian kernel. This could be generalized to use any - * distance metric, not the Euclidean distance, but for now, the Euclidean - * distance is used. - * - * @tparam VecTypeA Type of first vector (likely arma::vec or arma::sp_vec). - * @tparam VecTypeB Type of second vector (arma::vec / arma::sp_vec). - * @param a First vector. - * @param b Second vector. - * @return K(a, b) using the bandwidth (@f$\mu@f$) specified in the - * constructor. - */ - template - double Evaluate(const VecTypeA& a, const VecTypeB& b) const - { - // The precalculation of gamma saves us a little computation time. - return exp(-metric::EuclideanDistance::Evaluate(a, b) / bandwidth); - } - - /** - * Evaluation of the Laplacian kernel given the distance between two points. - * - * @param t The distance between the two points the kernel should be evaluated - * on. - * @return K(t) using the bandwidth (@f$\mu@f$) specified in the - * constructor. - */ - double Evaluate(const double t) const - { - // The precalculation of gamma saves us a little computation time. - return exp(-t / bandwidth); - } - - /** - * Evaluation of the gradient of the Laplacian kernel - * given the distance between two points. - * - * @param t The distance between the two points the kernel should be evaluated - * on. - * @return K(t) using the bandwidth (@f$\mu@f$) specified in the - * constructor. - */ - double Gradient(const double t) const { - return exp(-t / bandwidth) / -bandwidth; - } - - //! Get the bandwidth. - double Bandwidth() const { return bandwidth; } - //! Modify the bandwidth. - double& Bandwidth() { return bandwidth; } - - //! Serialize the kernel. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(bandwidth); - } - - private: - //! Kernel bandwidth. - double bandwidth; -}; - -//! Kernel traits of the Laplacian kernel. -template<> -class KernelTraits -{ - public: - //! The Laplacian kernel is normalized: K(x, x) = 1 for all x. - static const bool IsNormalized = true; - //! The Laplacian kernel doesn't include a squared distance. - static const bool UsesSquaredDistance = false; -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/linear_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/linear_kernel.hpp deleted file mode 100644 index 0bfeb0516..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/linear_kernel.hpp +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @file linear_kernel.hpp - * @author Wei Guan - * @author James Cline - * @author Ryan Curtin - * - * Implementation of the linear kernel (just the standard dot product). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_LINEAR_KERNEL_HPP -#define MLPACK_CORE_KERNELS_LINEAR_KERNEL_HPP - -#include - -namespace mlpack { -namespace kernel { - -/** - * The simple linear kernel (dot product). For any two vectors @f$ x @f$ and - * @f$ y @f$, - * - * @f[ - * K(x, y) = x^T y - * @f] - * - * This kernel has no parameters and therefore the evaluation can be static. - */ -class LinearKernel -{ - public: - /** - * This constructor does nothing; the linear kernel has no parameters to - * store. - */ - LinearKernel() { } - - /** - * Simple evaluation of the dot product. This evaluation uses Armadillo's - * dot() function. - * - * @tparam VecTypeA Type of first vector (should be arma::vec or - * arma::sp_vec). - * @tparam VecTypeB Type of second vector (arma::vec / arma::sp_vec). - * @param a First vector. - * @param b Second vector. - * @return K(a, b). - */ - template - static double Evaluate(const VecTypeA& a, const VecTypeB& b) - { - return arma::dot(a, b); - } - - //! Serialize the kernel (it has no members... do nothing). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/polynomial_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/polynomial_kernel.hpp deleted file mode 100644 index c06794af3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/polynomial_kernel.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file polynomial_kernel.hpp - * @author Ajinkya Kale - * - * Implementation of the polynomial kernel (just the standard dot product). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_POLYNOMIAL_KERNEL_HPP -#define MLPACK_CORE_KERNELS_POLYNOMIAL_KERNEL_HPP - -#include - -namespace mlpack { -namespace kernel { - -/** - * The simple polynomial kernel. For any two vectors @f$ x @f$, @f$ y @f$, - * @f$ degree @f$ and @f$ offset @f$, - * - * @f[ - * K(x, y) = (x^T * y + offset) ^ {degree}. - * @f] - */ -class PolynomialKernel -{ - public: - /** - * Construct the Polynomial Kernel with the given offset and degree. If the - * arguments are omitted, the default degree is 2 and the default offset is 0. - * - * @param offset Offset of the dot product of the arguments. - * @param degree Degree of the polynomial. - */ - PolynomialKernel(const double degree = 2.0, const double offset = 0.0) : - degree(degree), - offset(offset) - { } - - /** - * Simple evaluation of the dot product. This evaluation uses Armadillo's - * dot() function. - * - * @tparam VecTypeA Type of first vector (should be arma::vec or - * arma::sp_vec). - * @tparam VecTypeB Type of second vector (arma::vec / arma::sp_vec). - * @param a First vector. - * @param b Second vector. - * @return K(a, b). - */ - template - double Evaluate(const VecTypeA& a, const VecTypeB& b) const - { - return pow((arma::dot(a, b) + offset), degree); - } - - //! Get the degree of the polynomial. - const double& Degree() const { return degree; } - //! Modify the degree of the polynomial. - double& Degree() { return degree; } - - //! Get the offset of the dot product of the arguments. - const double& Offset() const { return offset; } - //! Modify the offset of the dot product of the arguments. - double& Offset() { return offset; } - - //! Serialize the kernel. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(degree); - ar & BOOST_SERIALIZATION_NVP(offset); - } - - private: - //! The degree of the polynomial. - double degree; - //! The offset of the dot product of the arguments. - double offset; -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/pspectrum_string_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/pspectrum_string_kernel.hpp deleted file mode 100644 index 9b5bb92b9..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/pspectrum_string_kernel.hpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @file pspectrum_string_kernel.hpp - * @author Ryan Curtin - * - * Implementation of the p-spectrum string kernel, created for use with FastMKS. - * Instead of passing a data matrix to FastMKS which stores the kernels, pass a - * one-dimensional data matrix (data vector) to FastMKS which stores indices of - * strings; then, the actual strings are given to the PSpectrumStringKernel at - * construction time, and the kernel knows to map the indices to actual strings. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_PSPECTRUM_STRING_KERNEL_HPP -#define MLPACK_CORE_KERNELS_PSPECTRUM_STRING_KERNEL_HPP - -#include -#include -#include - -#include -#include - -namespace mlpack { -namespace kernel { - -/** - * The p-spectrum string kernel. Given a length p, the p-spectrum kernel finds - * the contiguous subsequence match count between two strings. The kernel will - * take every possible substring of length p of one string and count how many - * times it appears in the other string. - * - * The string kernel, when created, must be passed a reference to a series of - * string datasets (std::vector >&). This is because - * mlpack only supports datasets which are Armadillo matrices -- and a dataset - * of variable-length strings cannot be easily cast into an Armadillo matrix. - * - * Therefore, once the PSpectrumStringKernel is created with a reference to the - * string datasets, a "fake" Armadillo data matrix must be created, which simply - * holds indices to the strings they represent. This "fake" matrix has two rows - * and n columns (where n is the number of strings in the dataset). The first - * row holds the index of the dataset (remember, the kernel can have multiple - * datasets), and the second row holds the index of the string. A fake matrix - * containing only strings from dataset 0 might look like this: - * - * [[0 0 0 0 0 0 0 0 0] - * [0 1 2 3 4 5 6 7 8]] - * - * This fake matrix is then given to the machine learning method, which will - * eventually call PSpectrumStringKernel::Evaluate(a, b), where a and b are two - * columns of the fake matrix. The string kernel will then map these fake - * columns back to the strings they represent, and then correctly evaluate the - * kernel. - * - * Unfortunately, not every machine learning method will work with this kernel. - * Only machine learning methods which do not ever operate on the explicit - * representation of points can use this kernel. So, for instance, one cannot - * build a kd-tree on strings, because the BinarySpaceTree<> class will split - * the data according to the fake data matrix -- resulting in a meaningless - * tree. This kernel was originally written for the FastMKS method; so, at the - * very least, it will work with that. - */ -class PSpectrumStringKernel -{ - public: - /** - * Initialize the PSpectrumStringKernel with the given string datasets. For - * more information on this, see the general class documentation. - * - * @param datasets Sets of string data. - * @param p The length of substrings to search. - */ - PSpectrumStringKernel(const std::vector >& datasets, - const size_t p); - - /** - * Evaluate the kernel for the string indices given. As mentioned in the - * class documentation, a and b should be 2-element vectors, where the first - * element contains the index of the dataset and the second element contains - * the index of the string. Therefore, if [2 3] is passed for a, the string - * used will be datasets[2][3] (datasets is of type - * std::vector >&). - * - * @param a Index of string and dataset for first string. - * @param b Index of string and dataset for second string. - */ - template - double Evaluate(const VecType& a, const VecType& b) const; - - //! Access the lists of substrings. - const std::vector > >& Counts() const - { return counts; } - //! Modify the lists of substrings. - std::vector > >& Counts() - { return counts; } - - //! Access the value of p. - size_t P() const { return p; } - //! Modify the value of p. - size_t& P() { return p; } - - private: - //! Mappings of the datasets to counts of substrings. Such a huge structure - //! is not wonderful... - std::vector > > counts; - - //! The value of p to use in calculation. - size_t p; -}; - -} // namespace kernel -} // namespace mlpack - -// Include implementation of templated Evaluate(). -#include "pspectrum_string_kernel_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/pspectrum_string_kernel_impl.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/pspectrum_string_kernel_impl.hpp deleted file mode 100644 index 6ae2cab1b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/pspectrum_string_kernel_impl.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file pspectrum_string_kernel_impl.hpp - * @author Ryan Curtin - * - * Implementation of the p-spectrum string kernel, created for use with FastMKS. - * Instead of passing a data matrix to FastMKS which stores the kernels, pass a - * one-dimensional data matrix (data vector) to FastMKS which stores indices of - * strings; then, the actual strings are given to the PSpectrumStringKernel at - * construction time, and the kernel knows to map the indices to actual strings. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_PSPECTRUM_STRING_KERNEL_IMPL_HPP -#define MLPACK_CORE_KERNELS_PSPECTRUM_STRING_KERNEL_IMPL_HPP - -// In case it has not been included yet. -#include "pspectrum_string_kernel.hpp" - -namespace mlpack { -namespace kernel { - -/** - * Evaluate the kernel for the string indices given. As mentioned in the class - * documentation, a and b should be 2-element vectors, where the first element - * contains the index of the dataset and the second element contains the index - * of the string. Therefore, if [2 3] is passed for a, the string used will be - * datasets[2][3] (datasets is of type std::vector >&). - * - * @param a Index of string and dataset for first string. - * @param b Index of string and dataset for second string. - */ -template -double PSpectrumStringKernel::Evaluate(const VecType& a, - const VecType& b) const -{ - // Get the map of substrings for the two strings we are interested in. - const std::map& aMap = counts[a[0]][a[1]]; - const std::map& bMap = counts[b[0]][b[1]]; - - double eval = 0; - - // Loop through the two maps (which, when iterated through, are sorted - // alphabetically). - std::map::const_iterator aIt = aMap.begin(); - std::map::const_iterator bIt = bMap.begin(); - - while ((aIt != aMap.end()) && (bIt != bMap.end())) - { - // Compare alphabetically (this is how std::map is ordered). - int result = (*aIt).first.compare((*bIt).first); - - if (result == 0) // The same substring. - { - eval += ((*aIt).second * (*bIt).second); - - // Now increment both. - ++aIt; - ++bIt; - } - else if (result > 0) - { - // aIt is "ahead" of bIt (alphabetically); so increment bIt to "catch up". - ++bIt; - } - else - { - // bIt is "ahead" of aIt (alphabetically); so increment aIt to "catch up". - ++aIt; - } - } - - return eval; -} -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/spherical_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/spherical_kernel.hpp deleted file mode 100644 index 44a7ba055..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/spherical_kernel.hpp +++ /dev/null @@ -1,135 +0,0 @@ -/** - * @file spherical_kernel.hpp - * @author Neil Slagle - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_SPHERICAL_KERNEL_HPP -#define MLPACK_CORE_KERNELS_SPHERICAL_KERNEL_HPP - -#include -#include - -namespace mlpack { -namespace kernel { - -/** - * The spherical kernel, which is 1 when the distance between the two argument - * points is less than or equal to the bandwidth, or 0 otherwise. - */ -class SphericalKernel -{ - public: - /** - * Construct the SphericalKernel with the given bandwidth. - */ - SphericalKernel(const double bandwidth = 1.0) : - bandwidth(bandwidth), - bandwidthSquared(std::pow(bandwidth, 2.0)) - { /* Nothing to do. */ } - - /** - * Evaluate the spherical kernel with the given two vectors. - * - * @tparam VecTypeA Type of first vector. - * @tparam VecTypeB Type of second vector. - * @param a First vector. - * @param b Second vector. - * @return The kernel evaluation between the two vectors. - */ - template - double Evaluate(const VecTypeA& a, const VecTypeB& b) const - { - return - (metric::SquaredEuclideanDistance::Evaluate(a, b) <= bandwidthSquared) ? - 1.0 : 0.0; - } - /** - * Obtains the convolution integral [integral K(||x-a||)K(||b-x||)dx] - * for the two vectors. - * - * @tparam VecTypeA Type of first vector (arma::vec, arma::sp_vec should be - * expected). - * @tparam VecTypeB Type of second vector. - * @param a First vector. - * @param b Second vector. - * @return the convolution integral value. - */ - template - double ConvolutionIntegral(const VecTypeA& a, const VecTypeB& b) const - { - double distance = sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b)); - if (distance >= 2.0 * bandwidth) - { - return 0.0; - } - double volumeSquared = pow(Normalizer(a.n_rows), 2.0); - - switch (a.n_rows) - { - case 1: - return 1.0 / volumeSquared * (2.0 * bandwidth - distance); - break; - case 2: - return 1.0 / volumeSquared * - (2.0 * bandwidth * bandwidth * acos(distance/(2.0 * bandwidth)) - - distance / 4.0 * sqrt(4.0*bandwidth*bandwidth-distance*distance)); - break; - default: - Log::Fatal << "The spherical kernel does not support convolution\ - integrals above dimension two, yet..." << std::endl; - return -1.0; - break; - } - } - double Normalizer(size_t dimension) const - { - return pow(bandwidth, (double) dimension) * pow(M_PI, dimension / 2.0) / - std::tgamma(dimension / 2.0 + 1.0); - } - - /** - * Evaluate the kernel when only a distance is given, not two points. - * - * @param t Argument to kernel. - */ - double Evaluate(const double t) const - { - return (t <= bandwidth) ? 1.0 : 0.0; - } - double Gradient(double t) - { - return t == bandwidth ? arma::datum::nan : 0.0; - } - - //! Serialize the object. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(bandwidth); - ar & BOOST_SERIALIZATION_NVP(bandwidthSquared); - } - - private: - double bandwidth; - double bandwidthSquared; -}; - -//! Kernel traits for the spherical kernel. -template<> -class KernelTraits -{ - public: - //! The spherical kernel is normalized: K(x, x) = 1 for all x. - static const bool IsNormalized = true; - //! The spherical kernel doesn't include a squared distance. - static const bool UsesSquaredDistance = false; -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/kernels/triangular_kernel.hpp b/src/sdk/mlpack/include/mlpack/core/kernels/triangular_kernel.hpp deleted file mode 100644 index 96a24f6e1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/kernels/triangular_kernel.hpp +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @file triangular_kernel.hpp - * @author Ryan Curtin - * - * Definition and implementation of the trivially simple triangular kernel. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_KERNELS_TRIANGULAR_KERNEL_HPP -#define MLPACK_CORE_KERNELS_TRIANGULAR_KERNEL_HPP - -#include -#include - -namespace mlpack { -namespace kernel { - -/** - * The trivially simple triangular kernel, defined by - * - * @f[ - * K(x, y) = \max \{ 0, 1 - \frac{|| x - y ||_2}{b} \} - * @f] - * - * where \f$ b \f$ is the bandwidth of the kernel. - */ -class TriangularKernel -{ - public: - /** - * Initialize the triangular kernel with the given bandwidth (default 1.0). - * - * @param bandwidth Bandwidth of the triangular kernel. - */ - TriangularKernel(const double bandwidth = 1.0) : bandwidth(bandwidth) { } - - /** - * Evaluate the triangular kernel for the two given vectors. - * - * @tparam VecTypeA Type of first vector. - * @tparam VecTypeB Type of second vector. - * @param a First vector. - * @param b Second vector. - */ - template - double Evaluate(const VecTypeA& a, const VecTypeB& b) const - { - return std::max(0.0, (1 - metric::EuclideanDistance::Evaluate(a, b) / - bandwidth)); - } - - /** - * Evaluate the triangular kernel given that the distance between the two - * points is known. - * - * @param distance The distance between the two points. - */ - double Evaluate(const double distance) const - { - return std::max(0.0, (1 - distance) / bandwidth); - } - - /** - * Evaluate the gradient of triangular kernel - * given that the distance between the two - * points is known. - * - * @param distance The distance between the two points. - */ - double Gradient(const double distance) const - { - if (distance < 1) - { - return -1.0 / bandwidth; - } - else if (distance > 1) - { - return 0; - } - else - { - return arma::datum::nan; - } - } - - //! Get the bandwidth of the kernel. - double Bandwidth() const { return bandwidth; } - //! Modify the bandwidth of the kernel. - double& Bandwidth() { return bandwidth; } - - //! Serialize the kernel. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(bandwidth); - } - - private: - //! The bandwidth of the kernel. - double bandwidth; -}; - -//! Kernel traits for the triangular kernel. -template<> -class KernelTraits -{ - public: - //! The triangular kernel is normalized: K(x, x) = 1 for all x. - static const bool IsNormalized = true; - //! The triangular kernel doesn't include a squared distance. - static const bool UsesSquaredDistance = false; -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/math/clamp.hpp b/src/sdk/mlpack/include/mlpack/core/math/clamp.hpp deleted file mode 100644 index bc87362c3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/clamp.hpp +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @file clamp.hpp - * - * Miscellaneous math clamping routines. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_CLAMP_HPP -#define MLPACK_CORE_MATH_CLAMP_HPP - -#include -#include -#include - -namespace mlpack { -namespace math /** Miscellaneous math routines. */ { - -/** - * Forces a number to be non-negative, turning negative numbers into zero. - * Avoids branching costs (this is a measurable improvement). - * - * @param d Double to clamp. - * @return 0 if d < 0, d otherwise. - */ -inline double ClampNonNegative(const double d) -{ - return (d + fabs(d)) / 2; -} - -/** - * Forces a number to be non-positive, turning positive numbers into zero. - * Avoids branching costs (this is a measurable improvement). - * - * @param d Double to clamp. - * @param 0 if d > 0, d otherwise. - */ -inline double ClampNonPositive(const double d) -{ - return (d - fabs(d)) / 2; -} - -/** - * Clamp a number between a particular range. - * - * @param value The number to clamp. - * @param rangeMin The first of the range. - * @param rangeMax The last of the range. - * @return max(rangeMin, min(rangeMax, d)). - */ -inline double ClampRange(double value, - const double rangeMin, - const double rangeMax) -{ - value -= rangeMax; - value = ClampNonPositive(value) + rangeMax; - value -= rangeMin; - value = ClampNonNegative(value) + rangeMin; - return value; -} - -} // namespace math -} // namespace mlpack - -#endif // MLPACK_CORE_MATH_CLAMP_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/math/columns_to_blocks.hpp b/src/sdk/mlpack/include/mlpack/core/math/columns_to_blocks.hpp deleted file mode 100644 index e9f12de1f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/columns_to_blocks.hpp +++ /dev/null @@ -1,227 +0,0 @@ -/** - * @file columns_to_blocks.hpp - * @author Tham Ngap Wei - * - * A helper class that could be useful for visualizing the output of - * MaximalInputs() and possibly other things. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NN_COLUMNS_TO_BLOCKS_HPP -#define MLPACK_METHODS_NN_COLUMNS_TO_BLOCKS_HPP - -#include - -namespace mlpack { -namespace math { - -/** - * Transform the columns of the given matrix into a block format. This could be - * useful with the mlpack::nn::MaximalInputs() function, if your training - * samples are images. Roughly speaking, given a matrix - * - * [[A] - * [B] - * [C] - * [D]] - * - * then the ColumnsToBlocks class can transform this to something like - * - * [[m m m m m] - * [m A m B m] - * [m m m m m] - * [m C m D m] - * [m m m m m]] - * - * where A through D are vectors and may themselves be reshaped by - * ColumnsToBlocks. - * - * An example usage of the ColumnsToBlocks class with the output of - * MaximalInputs() is given below; this assumes that the images are square, and - * will return a matrix with a one-element margin, with each maximal input (that - * is, each column of the maximalInput matrix) as a square block in the output - * matrix. 5 rows and columns of blocks will be in the output matrix. - * - * @code - * // We assume we have a sparse autoencoder 'encoder'. - * arma::mat maximalInput; // Store the features learned by sparse autoencoder - * mlpack::nn::MaximalInputs(encoder.Parameters(), maximalInput); - * - * arma::mat outputs; - * const bool scale = true; - * - * ColumnsToBlocks ctb(5, 5); - * arma::mat output; - * ctb.Transform(maximalInput, output); - * // You can save the output as a pgm, this may help you visualize the training - * // results. - * output.save(fileName, arma::pgm_binary); - * @endcode - * - * Another example of usage is given below, on a sample matrix. - * - * @code - * // This matrix has two columns. - * arma::mat input; - * input << -1.0000 << 0.1429 << arma::endr - * << -0.7143 << 0.4286 << arma::endr - * << -0.4286 << 0.7143 << arma::endr - * << -0.1429 << 1.0000 << arma::endr; - * - * arma::mat output; - * ColumnsToBlocks ctb(1, 2); - * ctb.Transform(input, output); - * - * // The columns of the input will be reshaped as a square which is - * // surrounded by padding value -1 (this value could be changed with the - * // BufValue() method): - * // -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 - * // -1.0000 -1.0000 -0.4286 -1.0000 0.1429 0.7143 -1.0000 - * // -1.0000 -0.7143 -0.1429 -1.0000 0.4286 1.0000 -1.0000 - * // -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 - * - * // Now, let's change some parameters; let's have each input column output not - * // as a square, but as a 4x1 vector. - * ctb.BlockWidth(1); - * ctb.BlockHeight(4); - * ctb.Transform(input, output); - * - * // The output here will be similar, but each maximal input is 4x1: - * // -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 - * // -1.0000 -1.0000 -1.0000 0.1429 -1.0000 - * // -1.0000 -0.7143 -1.0000 0.4286 -1.0000 - * // -1.0000 -0.4286 -1.0000 0.7143 -1.0000 - * // -1.0000 -0.1429 -1.0000 1.0000 -1.0000 - * // -1.0000 -1.0000 -1.0000 -1.0000 -1.0000 - * @endcode - * - * The ColumnsToBlocks class can also, depending on the parameters, scale the - * input to a given range (useful for exporting to PGM, for instance), and also - * set the buffer size and value. See the Scale(), MinRange(), MaxRange(), - * BufSize(), and BufValue() methods for more details. - */ -class ColumnsToBlocks -{ - public: - /** - * Constructor a ColumnsToBlocks object with the given parameters. The rows - * and cols parameters control the number of blocks per row and column of the - * output matrix, respectively, and the blockHeight and blockWidth parameters - * control the size of the individual blocks. If blockHeight and blockWidth - * are specified, then (blockHeight * blockWidth) must be equal to the number - * of rows in the input matrix when Transform() is called. If blockHeight and - * blockWidth are not specified, then the square root of the number of rows of - * the input matrix will be taken when Transform() is called and that will be - * used as the block width and height. - * - * Note that the ColumnsToBlocks object can also scale the inputs to a given - * range; see Scale(), MinRange(), and MaxRange(), and the buffer (margin) - * size can also be set with BufSize(), and the value used for the buffer can - * be set with BufValue(). - * - * @param rows Number of blocks in each column of the output matrix. - * @param cols Number of blocks in each row of the output matrix. - * @param blockHeight Height of each block. - * @param blockWidth Width of each block. - * - * @warning blockHeight * blockWidth must be equal to maximalInputs.n_rows. - */ - ColumnsToBlocks(size_t rows, - size_t cols, - size_t blockHeight = 0, - size_t blockWidth = 0); - - /** - * Transform the columns of the input matrix into blocks. If blockHeight and - * blockWidth were not specified in the constructor (and BlockHeight() and - * BlockWidth() were not called), then the number of rows in the input matrix - * must be a perfect square. - * - * @param input Input matrix to transform. - * @param output Matrix to store transformed output in. - */ - void Transform(const arma::mat& maximalInputs, arma::mat& output); - - //! Set the height of each block; see the constructor for more details. - void BlockHeight(const size_t value) { blockHeight = value; } - //! Get the block height. - size_t BlockHeight() const { return blockHeight; } - - //! Set the width of each block; see the constructor for more details. - void BlockWidth(size_t value) { blockWidth = value; } - //! Get the block width. - size_t BlockWidth() const { return blockWidth; } - - //! Modify the buffer size (the size of the margin around each column of the - //! input). The default value is 1. - void BufSize(const size_t value) { bufSize = value; } - //! Get the buffer size. - size_t BufSize() const { return bufSize; } - - //! Modify the value used for buffer cells; the default is -1. - void BufValue(const double value) { bufValue = value; } - //! Get the value used for buffer cells. - double BufValue() const { return bufValue; } - - //! Set the maximum of the range the input will be scaled to, if scaling is - //! enabled (see Scale()). - void MaxRange(const double value) { maxRange = value; } - //! Get the maximum of the range the input will be scaled to, if scaling is - //! enabled (see Scale()). - double MaxRange() const { return maxRange; } - - //! Set the minimum of the range the input will be scaled to, if scaling is - //! enabled (see Scale()). - void MinRange(const double value) { minRange = value; } - //! Get the minimum of the range the input will be scaled to, if scaling is - //! enabled (see Scale()). - double MinRange() const { return minRange; } - - //! Set whether or not scaling is enabled (see also MaxRange() and - //! MinRange()). - void Scale(const bool value) { scale = value; } - //! Get whether or not scaling is enabled (see also MaxRange() and - //! MinRange()). - bool Scale() const { return scale; } - - //! Set the number of blocks per row. - void Rows(const size_t value) { rows = value; } - //! Modify the number of blocks per row. - size_t Rows() const { return rows; } - - //! Set the number of blocks per column. - void Cols(const size_t value) { cols = value; } - //! Return the number of blocks per column. - size_t Cols() const { return cols; } - - private: - //! Determine whether or not the number is a perfect square. - bool IsPerfectSquare(size_t value) const; - - //! The height of each block. - size_t blockHeight; - //! The width of each block. - size_t blockWidth; - //! The size of the buffer around each block. - size_t bufSize; - //! The value of the buffer around each block. - double bufValue; - //! The minimum of the range to be scaled to (if scaling is enabled). - double minRange; - //! The maximum of the range to be scaled to (if scaling is enabled). - double maxRange; - //! Whether or not scaling is enabled. - bool scale; - //! The number of blocks in each row. - size_t rows; - //! The number of blocks in each column. - size_t cols; -}; - -} // namespace math -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/math/lin_alg.hpp b/src/sdk/mlpack/include/mlpack/core/math/lin_alg.hpp deleted file mode 100644 index 07b9bf720..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/lin_alg.hpp +++ /dev/null @@ -1,146 +0,0 @@ -/** - * @file lin_alg.hpp - * @author Nishant Mehta - * - * Linear algebra utilities. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_LIN_ALG_HPP -#define MLPACK_CORE_MATH_LIN_ALG_HPP - -#include - -/** - * Linear algebra utility functions, generally performed on matrices or vectors. - */ -namespace mlpack { -namespace math { - -/** - * Auxiliary function to raise vector elements to a specific power. The sign - * is ignored in the power operation and then re-added. Useful for - * eigenvalues. - */ -void VectorPower(arma::vec& vec, const double power); - -/** - * Creates a centered matrix, where centering is done by subtracting - * the sum over the columns (a column vector) from each column of the matrix. - * - * @param x Input matrix - * @param xCentered Matrix to write centered output into - */ -void Center(const arma::mat& x, arma::mat& xCentered); - -/** - * Whitens a matrix using the singular value decomposition of the covariance - * matrix. Whitening means the covariance matrix of the result is the identity - * matrix. - */ -void WhitenUsingSVD(const arma::mat& x, - arma::mat& xWhitened, - arma::mat& whiteningMatrix); - -/** - * Whitens a matrix using the eigendecomposition of the covariance matrix. - * Whitening means the covariance matrix of the result is the identity matrix. - */ -void WhitenUsingEig(const arma::mat& x, - arma::mat& xWhitened, - arma::mat& whiteningMatrix); - -/** - * Overwrites a dimension-N vector to a random vector on the unit sphere in R^N. - */ -void RandVector(arma::vec& v); - -/** - * Orthogonalize x and return the result in W, using eigendecomposition. - * We will be using the formula \f$ W = x (x^T x)^{-0.5} \f$. - */ -void Orthogonalize(const arma::mat& x, arma::mat& W); - -/** - * Orthogonalize x in-place. This could be sped up by a custom - * implementation. - */ -void Orthogonalize(arma::mat& x); - -/** - * Remove a certain set of rows in a matrix while copying to a second matrix. - * - * @param input Input matrix to copy. - * @param rowsToRemove Vector containing indices of rows to be removed. - * @param output Matrix to copy non-removed rows into. - */ -void RemoveRows(const arma::mat& input, - const std::vector& rowsToRemove, - arma::mat& output); - -/** - * Upper triangular representation of a symmetric matrix, scaled such that, - * dot(Svec(A), Svec(B)) == dot(A, B) for symmetric A, B. Specifically, - * - * Svec(K) = [ K_11, sqrt(2) K_12, ..., sqrt(2) K_1n, K_22, ..., sqrt(2) K_2n, ..., K_nn ]^T - * - * @param input A symmetric matrix - * @param output - */ -void Svec(const arma::mat& input, arma::vec& output); - -void Svec(const arma::sp_mat& input, arma::sp_vec& output); - -/** - * The inverse of Svec. That is, Smat(Svec(A)) == A. - * - * @param input - * @param output A symmetric matrix - */ -void Smat(const arma::vec& input, arma::mat& output); - -/** - * Return the index such that A[i,j] == factr(i, j) * svec(A)[pos(i, j)], - * where factr(i, j) = sqrt(2) if i != j and 1 otherwise. - * - * @param i - * @param j - * @param n - */ -inline size_t SvecIndex(size_t i, size_t j, size_t n); - -/** - * If A is a symmetric matrix, then SymKronId returns an operator Op such that - * - * Op * svec(X) == svec(0.5 * (AX + XA)) - * - * for every symmetric matrix X - * - * @param A - * @param op - */ -void SymKronId(const arma::mat& A, arma::mat& op); - -/** - * Signum function. - * Return 1 if x>0; return 0 if x=0; return -1 if x<0. - * Return type are the same as input type. - * - * @param x Number of any type. - */ -template -T Sign(const T x) -{ - return (T(0) < x) - (x < T(0)); -} - -} // namespace math -} // namespace mlpack - -// Partially include implementation -#include "lin_alg_impl.hpp" - -#endif // MLPACK_CORE_MATH_LIN_ALG_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/math/lin_alg_impl.hpp b/src/sdk/mlpack/include/mlpack/core/math/lin_alg_impl.hpp deleted file mode 100644 index c22684fe0..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/lin_alg_impl.hpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @file lin_alg_impl.hpp - * @author Stephen Tu - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_LIN_ALG_IMPL_HPP -#define MLPACK_CORE_MATH_LIN_ALG_IMPL_HPP - -#include "lin_alg.hpp" - -namespace mlpack { -namespace math { - -inline size_t SvecIndex(size_t i, size_t j, size_t n) -{ - if (i > j) - std::swap(i, j); - return (j-i) + (n*(n+1) - (n-i)*(n-i+1))/2; -} - -} // namespace math -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/math/make_alias.hpp b/src/sdk/mlpack/include/mlpack/core/math/make_alias.hpp deleted file mode 100644 index 7ed068714..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/make_alias.hpp +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file make_alias.hpp - * @author Ryan Curtin - * - * Make an alias of a matrix. For sparse matrices, unfortunately no alias can - * be made and a copy must be incurred. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_MAKE_ALIAS_HPP -#define MLPACK_CORE_MATH_MAKE_ALIAS_HPP - -namespace mlpack { -namespace math { - -/** - * Make an alias of a dense matrix. If strict is true, then the alias cannot be - * resized or pointed at new memory. - */ -template -arma::Mat MakeAlias(arma::Mat& input, - const bool strict = true) -{ - // Use the advanced constructor. - return arma::Mat(input.memptr(), input.n_rows, input.n_cols, false, - strict); -} - -/** - * Make an alias of a dense row. If strict is true, then the alias cannot be - * resized or pointed at new memory. - */ -template -arma::Row MakeAlias(arma::Row& input, - const bool strict = true) -{ - // Use the advanced constructor. - return arma::Row(input.memptr(), input.n_elem, false, strict); -} - -/** - * Make an alias of a dense column. If strict is true, then the alias cannot be - * resized or pointed at new memory. - */ -template -arma::Col MakeAlias(arma::Col& input, - const bool strict = true) -{ - // Use the advanced constructor. - return arma::Col(input.memptr(), input.n_elem, false, strict); -} - -/** - * Make a copy of a sparse matrix (an alias is not possible). The strict - * parameter is ignored. - */ -template -arma::SpMat MakeAlias(const arma::SpMat& input, - const bool /* strict */ = true) -{ - // Make a copy... - return arma::SpMat(input); -} - -/** - * Make a copy of a sparse row (an alias is not possible). The strict - * parameter is ignored. - */ -template -arma::SpRow MakeAlias(const arma::SpRow& input, - const bool /* strict */ = true) -{ - // Make a copy... - return arma::SpRow(input); -} - -/** - * Make a copy of a sparse column (an alias is not possible). The strict - * parameter is ignored. - */ -template -arma::SpCol MakeAlias(const arma::SpCol& input, - const bool /* strict */ = true) -{ - // Make a copy... - return arma::SpCol(input); -} - -/** - * Clear an alias so that no data is overwritten. This resets the matrix if it - * is an alias (and does nothing otherwise). - */ -template -void ClearAlias(arma::Mat& mat) -{ - if (mat.mem_state >= 1) - mat.reset(); -} - -/** - * Clear an alias for a sparse matrix. This does nothing because no sparse - * matrices can have aliases. - */ -template -void ClearAlias(arma::SpMat& /* mat */) -{ - // Nothing to do. -} - - -} // namespace math -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/math/random.hpp b/src/sdk/mlpack/include/mlpack/core/math/random.hpp deleted file mode 100644 index 5df2b3249..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/random.hpp +++ /dev/null @@ -1,162 +0,0 @@ -/** - * @file random.hpp - * - * Miscellaneous math random-related routines. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_RANDOM_HPP -#define MLPACK_CORE_MATH_RANDOM_HPP - -#include -#include -#include - -namespace mlpack { -namespace math /** Miscellaneous math routines. */ { - -/** - * MLPACK_EXPORT is required for global variables; it exports the symbols - * correctly on Windows. - */ - -// Global random object. -extern MLPACK_EXPORT std::mt19937 randGen; -// Global uniform distribution. -extern MLPACK_EXPORT std::uniform_real_distribution<> randUniformDist; -// Global normal distribution. -extern MLPACK_EXPORT std::normal_distribution<> randNormalDist; - -/** - * Set the random seed used by the random functions (Random() and RandInt()). - * The seed is casted to a 32-bit integer before being given to the random - * number generator, but a size_t is taken as a parameter for API consistency. - * - * @param seed Seed for the random number generator. - */ -inline void RandomSeed(const size_t seed) -{ - #if (!defined(BINDING_TYPE) || BINDING_TYPE != BINDING_TYPE_TEST) - randGen.seed((uint32_t) seed); - srand((unsigned int) seed); - arma::arma_rng::set_seed(seed); - #else - (void) seed; - #endif -} - -/** - * Set the random seed to a fixed number. - * This function is used in binding tests to set a fixed random seed before - * calling mlpack(). In this way we can test whether a certain parameter makes - * a difference to execution of CLI binding. - * Refer to pull request #1306 for discussion on this function. - */ -#if (BINDING_TYPE == BINDING_TYPE_TEST) -inline void FixedRandomSeed() -{ - const static size_t seed = rand(); - randGen.seed((uint32_t) seed); - srand((unsigned int) seed); - arma::arma_rng::set_seed(seed); -} -#endif - -/** - * Generates a uniform random number between 0 and 1. - */ -inline double Random() -{ - return randUniformDist(randGen); -} - -/** - * Generates a uniform random number in the specified range. - */ -inline double Random(const double lo, const double hi) -{ - return lo + (hi - lo) * randUniformDist(randGen); -} - -/** - * Generates a uniform random integer. - */ -inline int RandInt(const int hiExclusive) -{ - return (int) std::floor((double) hiExclusive * randUniformDist(randGen)); -} - -/** - * Generates a uniform random integer. - */ -inline int RandInt(const int lo, const int hiExclusive) -{ - return lo + (int) std::floor((double) (hiExclusive - lo) - * randUniformDist(randGen)); -} - -/** - * Generates a normally distributed random number with mean 0 and variance 1. - */ -inline double RandNormal() -{ - return randNormalDist(randGen); -} - -/** - * Generates a normally distributed random number with specified mean and - * variance. - * - * @param mean Mean of distribution. - * @param variance Variance of distribution. - */ -inline double RandNormal(const double mean, const double variance) -{ - return variance * randNormalDist(randGen) + mean; -} - -/** - * Obtains no more than maxNumSamples distinct samples. Each sample belongs to - * [loInclusive, hiExclusive). - * - * @param loInclusive The lower bound (inclusive). - * @param hiExclusive The high bound (exclusive). - * @param maxNumSamples The maximum number of samples to obtain. - * @param distinctSamples The samples that will be obtained. - */ -inline void ObtainDistinctSamples(const size_t loInclusive, - const size_t hiExclusive, - const size_t maxNumSamples, - arma::uvec& distinctSamples) -{ - const size_t samplesRangeSize = hiExclusive - loInclusive; - - if (samplesRangeSize > maxNumSamples) - { - arma::Col samples; - - samples.zeros(samplesRangeSize); - - for (size_t i = 0; i < maxNumSamples; i++) - samples [ (size_t) math::RandInt(samplesRangeSize) ]++; - - distinctSamples = arma::find(samples > 0); - - if (loInclusive > 0) - distinctSamples += loInclusive; - } - else - { - distinctSamples.set_size(samplesRangeSize); - for (size_t i = 0; i < samplesRangeSize; i++) - distinctSamples[i] = loInclusive + i; - } -} - -} // namespace math -} // namespace mlpack - -#endif // MLPACK_CORE_MATH_MATH_LIB_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/math/random_basis.hpp b/src/sdk/mlpack/include/mlpack/core/math/random_basis.hpp deleted file mode 100644 index a0b21dcf5..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/random_basis.hpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @file random_basis.hpp - * @author Ryan Curtin - * - * Generate a random d-dimensional basis. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_RANDOM_BASIS_HPP -#define MLPACK_CORE_MATH_RANDOM_BASIS_HPP - -#include - -namespace mlpack { -namespace math { - -/** - * Create a random d-dimensional orthogonal basis, storing it in the given - * matrix. - * - * @param basis Matrix to store basis in. - * @param d Desired number of dimensions in the basis. - */ -void RandomBasis(arma::mat& basis, const size_t d); - -} // namespace math -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/math/range.hpp b/src/sdk/mlpack/include/mlpack/core/math/range.hpp deleted file mode 100644 index f3fc33615..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/range.hpp +++ /dev/null @@ -1,191 +0,0 @@ -/** - * @file range.hpp - * - * Definition of the Range class, which represents a simple range with a lower - * and upper bound. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_RANGE_HPP -#define MLPACK_CORE_MATH_RANGE_HPP - -namespace mlpack { -namespace math { - -template -class RangeType; - -//! 3.0.0 TODO: break reverse-compatibility by changing RangeType to Range. -typedef RangeType Range; - -/** - * Simple real-valued range. It contains an upper and lower bound. - * - * Note that until mlpack 3.0.0, this class is named RangeType<> and for the - * specification where T is double, you can use math::Range. As of mlpack - * 3.0.0, this class will be renamed math::Range<>. - * - * @tparam T type of element held by this range. - */ -template -class RangeType -{ - private: - T lo; /// The lower bound. - T hi; /// The upper bound. - - public: - /** Initialize to an empty set (where lo > hi). */ - inline RangeType(); - - /*** - * Initialize a range to enclose only the given point (lo = point, hi = - * point). - * - * @param point Point that this range will enclose. - */ - inline RangeType(const T point); - - /** - * Initializes to specified range. - * - * @param lo Lower bound of the range. - * @param hi Upper bound of the range. - */ - inline RangeType(const T lo, const T hi); - - //! Get the lower bound. - inline T Lo() const { return lo; } - //! Modify the lower bound. - inline T& Lo() { return lo; } - - //! Get the upper bound. - inline T Hi() const { return hi; } - //! Modify the upper bound. - inline T& Hi() { return hi; } - - /** - * Gets the span of the range (hi - lo). - */ - inline T Width() const; - - /** - * Gets the midpoint of this range. - */ - inline T Mid() const; - - /** - * Expands this range to include another range. - * - * @param rhs Range to include. - */ - inline RangeType& operator|=(const RangeType& rhs); - - /** - * Expands this range to include another range. - * - * @param rhs Range to include. - */ - inline RangeType operator|(const RangeType& rhs) const; - - /** - * Shrinks this range to be the overlap with another range; this makes an - * empty set if there is no overlap. - * - * @param rhs Other range. - */ - inline RangeType& operator&=(const RangeType& rhs); - - /** - * Shrinks this range to be the overlap with another range; this makes an - * empty set if there is no overlap. - * - * @param rhs Other range. - */ - inline RangeType operator&(const RangeType& rhs) const; - - /** - * Scale the bounds by the given double. - * - * @param d Scaling factor. - */ - inline RangeType& operator*=(const T d); - - /** - * Scale the bounds by the given double. - * - * @param d Scaling factor. - */ - inline RangeType operator*(const T d) const; - - /** - * Scale the bounds by the given double. - * - * @param d Scaling factor. - */ - template - friend inline RangeType operator*(const TT d, const RangeType& r); - - /** - * Compare with another range for strict equality. - * - * @param rhs Other range. - */ - inline bool operator==(const RangeType& rhs) const; - - /** - * Compare with another range for strict equality. - * - * @param rhs Other range. - */ - inline bool operator!=(const RangeType& rhs) const; - - /** - * Compare with another range. For Range objects x and y, x < y means that x - * is strictly less than y and does not overlap at all. - * - * @param rhs Other range. - */ - inline bool operator<(const RangeType& rhs) const; - - /** - * Compare with another range. For Range objects x and y, x < y means that x - * is strictly less than y and does not overlap at all. - * - * @param rhs Other range. - */ - inline bool operator>(const RangeType& rhs) const; - - /** - * Determines if a point is contained within the range. - * - * @param d Point to check. - */ - inline bool Contains(const T d) const; - - /** - * Determines if another range overlaps with this one. - * - * @param r Other range. - * - * @return true if ranges overlap at all. - */ - inline bool Contains(const RangeType& r) const; - - /** - * Serialize the range object. - */ - template - void serialize(Archive& ar, const unsigned int version); -}; - -} // namespace math -} // namespace mlpack - -// Include inlined implementation. -#include "range_impl.hpp" - -#endif // MLPACK_CORE_MATH_RANGE_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/math/range_impl.hpp b/src/sdk/mlpack/include/mlpack/core/math/range_impl.hpp deleted file mode 100644 index 115a925a7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/range_impl.hpp +++ /dev/null @@ -1,213 +0,0 @@ -/** - * @file range_impl.hpp - * - * Implementation of the (inlined) Range class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_RANGE_IMPL_HPP -#define MLPACK_CORE_MATH_RANGE_IMPL_HPP - -#include "range.hpp" -#include -#include - -namespace mlpack { -namespace math { - -/** - * Initialize the range to 0. - */ -template -inline RangeType::RangeType() : - lo(std::numeric_limits::max()), - hi(-std::numeric_limits::max()) { /* nothing else to do */ } - -/** - * Initialize a range to enclose only the given point. - */ -template -inline RangeType::RangeType(const T point) : - lo(point), hi(point) { /* nothing else to do */ } - -/** - * Initializes the range to the specified values. - */ -template -inline RangeType::RangeType(const T lo, const T hi) : - lo(lo), hi(hi) { /* nothing else to do */ } - -/** - * Gets the span of the range, hi - lo. Returns 0 if the range is negative. - */ -template -inline T RangeType::Width() const -{ - if (lo < hi) - return (hi - lo); - else - return 0.0; -} - -/** - * Gets the midpoint of this range. - */ -template -inline T RangeType::Mid() const -{ - return (hi + lo) / 2; -} - -/** - * Expands range to include the other range. - */ -template -inline RangeType& RangeType::operator|=(const RangeType& rhs) -{ - if (rhs.lo < lo) - lo = rhs.lo; - if (rhs.hi > hi) - hi = rhs.hi; - - return *this; -} - -template -inline RangeType RangeType::operator|(const RangeType& rhs) const -{ - return RangeType((rhs.lo < lo) ? rhs.lo : lo, - (rhs.hi > hi) ? rhs.hi : hi); -} - -/** - * Shrinks range to be the overlap with another range, becoming an empty - * set if there is no overlap. - */ -template -inline RangeType& RangeType::operator&=(const RangeType& rhs) -{ - if (rhs.lo > lo) - lo = rhs.lo; - if (rhs.hi < hi) - hi = rhs.hi; - - return *this; -} - -template -inline RangeType RangeType::operator&(const RangeType& rhs) const -{ - return RangeType((rhs.lo > lo) ? rhs.lo : lo, - (rhs.hi < hi) ? rhs.hi : hi); -} - -/** - * Scale the bounds by the given double. - */ -template -inline RangeType& RangeType::operator*=(const T d) -{ - lo *= d; - hi *= d; - - // Now if we've negated, we need to flip things around so the bound is valid. - if (lo > hi) - { - double tmp = hi; - hi = lo; - lo = tmp; - } - - return *this; -} - -template -inline RangeType RangeType::operator*(const T d) const -{ - double nlo = lo * d; - double nhi = hi * d; - - if (nlo <= nhi) - return RangeType(nlo, nhi); - else - return RangeType(nhi, nlo); -} - -// Symmetric case. -template -inline RangeType operator*(const T d, const RangeType& r) -{ - double nlo = r.lo * d; - double nhi = r.hi * d; - - if (nlo <= nhi) - return RangeType(nlo, nhi); - else - return RangeType(nhi, nlo); -} - -/** - * Compare with another range for strict equality. - */ -template -inline bool RangeType::operator==(const RangeType& rhs) const -{ - return (lo == rhs.lo) && (hi == rhs.hi); -} - -template -inline bool RangeType::operator!=(const RangeType& rhs) const -{ - return (lo != rhs.lo) || (hi != rhs.hi); -} - -/** - * Compare with another range. For Range objects x and y, x < y means that x is - * strictly less than y and does not overlap at all. - */ -template -inline bool RangeType::operator<(const RangeType& rhs) const -{ - return hi < rhs.lo; -} - -template -inline bool RangeType::operator>(const RangeType& rhs) const -{ - return lo > rhs.hi; -} - -/** - * Determines if a point is contained within the range. - */ -template -inline bool RangeType::Contains(const T d) const -{ - return d >= lo && d <= hi; -} - -/** - * Determines if this range overlaps with another range. - */ -template -inline bool RangeType::Contains(const RangeType& r) const -{ - return lo <= r.hi && hi >= r.lo; -} - -//! Serialize the range. -template -template -void RangeType::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(hi); - ar & BOOST_SERIALIZATION_NVP(lo); -} - -} // namespace math -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/math/round.hpp b/src/sdk/mlpack/include/mlpack/core/math/round.hpp deleted file mode 100644 index 4a8d97bba..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/round.hpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @file round.hpp - * @author Ryan Curtin - * - * Implementation of round() for use on Visual Studio, where C99 isn't - * implemented. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_ROUND_HPP -#define MLPACK_CORE_MATH_ROUND_HPP - -// _MSC_VER should only be defined for Visual Studio, which doesn't implement -// C99. -#ifdef _MSC_VER - -// This function ends up going into the global namespace, so it can be used in -// place of C99's round(). - -//! Round a number to the nearest integer. -inline double round(double a) -{ - return floor(a + 0.5); -} - -#endif - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/math/shuffle_data.hpp b/src/sdk/mlpack/include/mlpack/core/math/shuffle_data.hpp deleted file mode 100644 index 1980dc6a5..000000000 --- a/src/sdk/mlpack/include/mlpack/core/math/shuffle_data.hpp +++ /dev/null @@ -1,243 +0,0 @@ -/** - * @file shuffle_data.hpp - * @author Ryan Curtin - * - * Given data points and labels, shuffle their ordering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_MATH_SHUFFLE_DATA_HPP -#define MLPACK_CORE_MATH_SHUFFLE_DATA_HPP - -#include - -namespace mlpack { -namespace math { - -/** - * Shuffle a dataset and associated labels (or responses). It is expected that - * inputPoints and inputLabels have the same number of columns (so, be sure that - * inputLabels, if it is a vector, is a row vector). - * - * Shuffled data will be output into outputPoints and outputLabels. - */ -template -void ShuffleData(const MatType& inputPoints, - const LabelsType& inputLabels, - MatType& outputPoints, - LabelsType& outputLabels, - const std::enable_if_t::value>* = 0, - const std::enable_if_t::value>* = 0) -{ - // Generate ordering. - arma::uvec ordering = arma::shuffle(arma::linspace(0, - inputPoints.n_cols - 1, inputPoints.n_cols)); - - outputPoints = inputPoints.cols(ordering); - outputLabels = inputLabels.cols(ordering); -} - -/** - * Shuffle a sparse dataset and associated labels (or responses). It is - * expected that inputPoints and inputLabels have the same number of columns - * (so, be sure that inputLabels, if it is a vector, is a row vector). - * - * Shuffled data will be output into outputPoints and outputLabels. - */ -template -void ShuffleData(const MatType& inputPoints, - const LabelsType& inputLabels, - MatType& outputPoints, - LabelsType& outputLabels, - const std::enable_if_t::value>* = 0, - const std::enable_if_t::value>* = 0) -{ - // Generate ordering. - arma::uvec ordering = arma::shuffle(arma::linspace(0, - inputPoints.n_cols - 1, inputPoints.n_cols)); - - // Extract coordinate list representation. - arma::umat locations(2, inputPoints.n_nonzero); - arma::Col values(inputPoints.n_nonzero); - typename MatType::const_iterator it = inputPoints.begin(); - size_t index = 0; - while (it != inputPoints.end()) - { - locations(0, index) = it.row(); - locations(1, index) = ordering[it.col()]; - values(index) = (*it); - ++it; - ++index; - } - - if (&inputPoints == &outputPoints || &inputLabels == &outputLabels) - { - MatType newOutputPoints(locations, values, inputPoints.n_rows, - inputPoints.n_cols, true); - LabelsType newOutputLabels(inputLabels.n_elem); - newOutputLabels.cols(ordering) = inputLabels; - - outputPoints = std::move(newOutputPoints); - outputLabels = std::move(newOutputLabels); - } - else - { - outputPoints = MatType(locations, values, inputPoints.n_rows, - inputPoints.n_cols, true); - outputLabels.set_size(inputLabels.n_elem); - outputLabels.cols(ordering) = inputLabels; - } -} - -/** - * Shuffle a cube-shaped dataset and associated labels (or responses) which are - * also cube-shaped. It is expected that inputPoints and inputLabels have the - * same number of columns. - * - * Shuffled data will be output into outputPoints and outputLabels. - */ -template -void ShuffleData(const MatType& inputPoints, - const LabelsType& inputLabels, - MatType& outputPoints, - LabelsType& outputLabels, - const std::enable_if_t::value>* = 0, - const std::enable_if_t::value>* = 0, - const std::enable_if_t::value>* = 0) -{ - // Generate ordering. - arma::uvec ordering = arma::shuffle(arma::linspace(0, - inputPoints.n_cols - 1, inputPoints.n_cols)); - - // Properly handle the case where the input and output data are the same - // object. - MatType* outputPointsPtr = &outputPoints; - LabelsType* outputLabelsPtr = &outputLabels; - if (&inputPoints == &outputPoints) - outputPointsPtr = new MatType(); - if (&inputLabels == &outputLabels) - outputLabelsPtr = new LabelsType(); - - outputPointsPtr->set_size(inputPoints.n_rows, inputPoints.n_cols, - inputPoints.n_slices); - outputLabelsPtr->set_size(inputLabels.n_rows, inputLabels.n_cols, - inputLabels.n_slices); - for (size_t i = 0; i < ordering.n_elem; ++i) - { - outputPointsPtr->tube(0, ordering[i], outputPointsPtr->n_rows - 1, - ordering[i]) = inputPoints.tube(0, i, inputPoints.n_rows - 1, i); - outputLabelsPtr->tube(0, ordering[i], outputLabelsPtr->n_rows - 1, - ordering[i]) = inputLabels.tube(0, i, inputLabels.n_rows - 1, i); - } - - // Clean up memory if needed. - if (&inputPoints == &outputPoints) - { - outputPoints = std::move(*outputPointsPtr); - delete outputPointsPtr; - } - - if (&inputLabels == &outputLabels) - { - outputLabels = std::move(*outputLabelsPtr); - delete outputLabelsPtr; - } -} - -/** - * Shuffle a dataset and associated labels (or responses) and weights. It is - * expected that inputPoints and inputLabels and inputWeights have the same - * number of columns (so, be sure that inputLabels, if it is a vector, is a row - * vector). - * - * Shuffled data will be output into outputPoints and outputLabels and - * outputWeights. - */ -template -void ShuffleData(const MatType& inputPoints, - const LabelsType& inputLabels, - const WeightsType& inputWeights, - MatType& outputPoints, - LabelsType& outputLabels, - WeightsType& outputWeights, - const std::enable_if_t::value>* = 0, - const std::enable_if_t::value>* = 0) -{ - // Generate ordering. - arma::uvec ordering = arma::shuffle(arma::linspace(0, - inputPoints.n_cols - 1, inputPoints.n_cols)); - - outputPoints = inputPoints.cols(ordering); - outputLabels = inputLabels.cols(ordering); - outputWeights = inputWeights.cols(ordering); -} - -/** - * Shuffle a sparse dataset and associated labels (or responses) and weights. - * It is expected that inputPoints and inputLabels and inputWeights have the - * same number of columns (so, be sure that inputLabels, if it is a vector, is a - * row vector). - * - * Shuffled data will be output into outputPoints and outputLabels and - * outputWeights. - */ -template -void ShuffleData(const MatType& inputPoints, - const LabelsType& inputLabels, - const WeightsType& inputWeights, - MatType& outputPoints, - LabelsType& outputLabels, - WeightsType& outputWeights, - const std::enable_if_t::value>* = 0, - const std::enable_if_t::value>* = 0) -{ - // Generate ordering. - arma::uvec ordering = arma::shuffle(arma::linspace(0, - inputPoints.n_cols - 1, inputPoints.n_cols)); - - // Extract coordinate list representation. - arma::umat locations(2, inputPoints.n_nonzero); - arma::Col values(inputPoints.n_nonzero); - typename MatType::const_iterator it = inputPoints.begin(); - size_t index = 0; - while (it != inputPoints.end()) - { - locations(0, index) = it.row(); - locations(1, index) = ordering[it.col()]; - values(index) = (*it); - ++it; - ++index; - } - - if (&inputPoints == &outputPoints || &inputLabels == &outputLabels || - &inputWeights == &outputWeights) - { - MatType newOutputPoints(locations, values, inputPoints.n_rows, - inputPoints.n_cols, true); - LabelsType newOutputLabels(inputLabels.n_elem); - WeightsType newOutputWeights(inputWeights.n_elem); - newOutputLabels.cols(ordering) = inputLabels; - newOutputWeights.cols(ordering) = inputWeights; - - outputPoints = std::move(newOutputPoints); - outputLabels = std::move(newOutputLabels); - outputWeights = std::move(newOutputWeights); - } - else - { - outputPoints = MatType(locations, values, inputPoints.n_rows, - inputPoints.n_cols, true); - outputLabels.set_size(inputLabels.n_elem); - outputLabels.cols(ordering) = inputLabels; - outputWeights.set_size(inputWeights.n_elem); - outputWeights.cols(ordering) = inputWeights; - } -} - -} // namespace math -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/metrics/ip_metric.hpp b/src/sdk/mlpack/include/mlpack/core/metrics/ip_metric.hpp deleted file mode 100644 index a24552de3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/metrics/ip_metric.hpp +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @file ip_metric.hpp - * @author Ryan Curtin - * - * Inner product induced metric. If given a kernel function, this gives the - * complementary metric. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_IP_METRIC_HPP -#define MLPACK_METHODS_FASTMKS_IP_METRIC_HPP - -namespace mlpack { -namespace metric { - -/** - * The inner product metric, IPMetric, takes a given Mercer kernel (KernelType), - * and when Evaluate() is called, returns the distance between the two points in - * kernel space: - * - * @f[ - * d(x, y) = \sqrt{ K(x, x) + K(y, y) - 2K(x, y) }. - * @f] - * - * @tparam KernelType Type of Kernel to use. This must be a Mercer kernel - * (positive definite), otherwise the metric may not be valid. - */ -template -class IPMetric -{ - public: - //! Create the IPMetric without an instantiated kernel. - IPMetric(); - - //! Create the IPMetric with an instantiated kernel. - IPMetric(KernelType& kernel); - - //! Destroy the IPMetric object. - ~IPMetric(); - - /** - * Evaluate the metric. - * - * @tparam VecTypeA Type of first vector. - * @tparam VecTypeB Type of second vector. - * @param a First vector. - * @param b Second vector. - * @return Distance between the two points in kernel space. - */ - template - typename VecTypeA::elem_type Evaluate(const VecTypeA& a, const VecTypeB& b); - - //! Get the kernel. - const KernelType& Kernel() const { return *kernel; } - //! Modify the kernel. - KernelType& Kernel() { return *kernel; } - - //! Serialize the metric. - template - void serialize(Archive& ar, const unsigned int version); - - private: - //! The kernel we are using. - KernelType* kernel; - //! If true, we are responsible for deleting the kernel. - bool kernelOwner; -}; - -} // namespace metric -} // namespace mlpack - -// Include implementation. -#include "ip_metric_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/metrics/ip_metric_impl.hpp b/src/sdk/mlpack/include/mlpack/core/metrics/ip_metric_impl.hpp deleted file mode 100644 index d39026593..000000000 --- a/src/sdk/mlpack/include/mlpack/core/metrics/ip_metric_impl.hpp +++ /dev/null @@ -1,90 +0,0 @@ -/** - * @file ip_metric_impl.hpp - * @author Ryan Curtin - * - * Implementation of the IPMetric. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_IP_METRIC_IMPL_HPP -#define MLPACK_METHODS_FASTMKS_IP_METRIC_IMPL_HPP - -// In case it hasn't been included yet. -#include "ip_metric_impl.hpp" - -#include -#include - -namespace mlpack { -namespace metric { - -// Constructor with no instantiated kernel. -template -IPMetric::IPMetric() : - kernel(new KernelType()), - kernelOwner(true) -{ - // Nothing to do. -} - -// Constructor with instantiated kernel. -template -IPMetric::IPMetric(KernelType& kernel) : - kernel(&kernel), - kernelOwner(false) -{ - // Nothing to do. -} - -// Destructor for the IPMetric. -template -IPMetric::~IPMetric() -{ - if (kernelOwner) - delete kernel; -} - -template -template -inline typename Vec1Type::elem_type IPMetric::Evaluate( - const Vec1Type& a, - const Vec2Type& b) -{ - // This is the metric induced by the kernel function. - // Maybe we can do better by caching some of this? - return sqrt(kernel->Evaluate(a, a) + kernel->Evaluate(b, b) - - 2 * kernel->Evaluate(a, b)); -} - -// Serialize the kernel. -template -template -void IPMetric::serialize(Archive& ar, - const unsigned int /* version */) -{ - // If we're loading, we need to allocate space for the kernel, and we will own - // the kernel. - if (Archive::is_loading::value) - kernelOwner = true; - - ar & BOOST_SERIALIZATION_NVP(kernel); -} - -// A specialization for the linear kernel, which actually just turns out to be -// the Euclidean distance. -template<> -template -inline typename Vec1Type::elem_type IPMetric::Evaluate( - const Vec1Type& a, - const Vec2Type& b) -{ - return metric::LMetric<2, true>::Evaluate(a, b); -} - -} // namespace metric -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/metrics/lmetric.hpp b/src/sdk/mlpack/include/mlpack/core/metrics/lmetric.hpp deleted file mode 100644 index d92bc0ea8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/metrics/lmetric.hpp +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @file lmetric.hpp - * @author Ryan Curtin - * - * Generalized L-metric, allowing both squared distances to be returned as well - * as non-squared distances. The squared distances are faster to compute. - * - * This also gives several convenience typedefs for commonly used L-metrics. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_METRICS_LMETRIC_HPP -#define MLPACK_CORE_METRICS_LMETRIC_HPP - -#include - -namespace mlpack { -namespace metric { - -/** - * The L_p metric for arbitrary integer p, with an option to take the root. - * - * This class implements the standard L_p metric for two arbitrary vectors @f$ x - * @f$ and @f$ y @f$ of dimensionality @f$ n @f$: - * - * @f[ - * d(x, y) = \left( \sum_{i = 1}^{n} | x_i - y_i |^p \right)^{\frac{1}{p}}. - * @f] - * - * The value of p is given as a template parameter. - * - * In addition, the function @f$ d(x, y) @f$ can be simplified, neglecting the - * p-root calculation. This is done by specifying the TakeRoot template - * parameter to be false. Then, - * - * @f[ - * d(x, y) = \sum_{i = 1}^{n} | x_i - y_i |^p - * @f] - * - * It is faster to compute that distance, so TakeRoot is by default off. - * However, when TakeRoot is false, the distance given is not actually a true - * metric -- it does not satisfy the triangle inequality. Some mlpack methods - * do not require the triangle inequality to operate correctly (such as the - * BinarySpaceTree), but setting TakeRoot = false in some cases will cause - * incorrect results. - * - * A few convenience typedefs are given: - * - * - ManhattanDistance - * - EuclideanDistance - * - SquaredEuclideanDistance - * - * @tparam Power Power of metric; i.e. Power = 1 gives the L1-norm (Manhattan - * distance). - * @tparam TakeRoot If true, the Power'th root of the result is taken before it - * is returned. Setting this to false causes the metric to not satisfy the - * Triangle Inequality (be careful!). - */ -template -class LMetric -{ - public: - /*** - * Default constructor does nothing, but is required to satisfy the Metric - * policy. - */ - LMetric() { } - - /** - * Computes the distance between two points. - * - * @tparam VecTypeA Type of first vector (generally arma::vec or - * arma::sp_vec). - * @tparam VecTypeB Type of second vector. - * @param a First vector. - * @param b Second vector. - * @return Distance between vectors a and b. - */ - template - static typename VecTypeA::elem_type Evaluate(const VecTypeA& a, - const VecTypeB& b); - - //! Serialize the metric (nothing to do). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } - - //! The power of the metric. - static const int Power = TPower; - //! Whether or not the root is taken. - static const bool TakeRoot = TTakeRoot; -}; - -// Convenience typedefs. - -/** - * The Manhattan (L1) distance. - */ -typedef LMetric<1, false> ManhattanDistance; - -/** - * The squared Euclidean (L2) distance. Note that this is not technically a - * metric! But it can sometimes be used when distances are required. - */ -typedef LMetric<2, false> SquaredEuclideanDistance; - -/** - * The Euclidean (L2) distance. - */ -typedef LMetric<2, true> EuclideanDistance; - -/** - * The L-infinity distance. - */ -typedef LMetric ChebyshevDistance; - - -} // namespace metric -} // namespace mlpack - -// Include implementation. -#include "lmetric_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/metrics/lmetric_impl.hpp b/src/sdk/mlpack/include/mlpack/core/metrics/lmetric_impl.hpp deleted file mode 100644 index 4128ae9bd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/metrics/lmetric_impl.hpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @file lmetric_impl.hpp - * @author Ryan Curtin - * - * Implementation of template specializations of LMetric class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_METRICS_LMETRIC_IMPL_HPP -#define MLPACK_CORE_METRICS_LMETRIC_IMPL_HPP - -// In case it hasn't been included. -#include "lmetric.hpp" - -namespace mlpack { -namespace metric { - -// Unspecialized implementation. This should almost never be used... -template -template -typename VecTypeA::elem_type LMetric::Evaluate( - const VecTypeA& a, - const VecTypeB& b) -{ - typename VecTypeA::elem_type sum = 0; - for (size_t i = 0; i < a.n_elem; i++) - sum += std::pow(fabs(a[i] - b[i]), Power); - - if (!TakeRoot) // The compiler should optimize this correctly at compile-time. - return sum; - - return std::pow(sum, (1.0 / Power)); -} - -// L1-metric specializations; the root doesn't matter. -template<> -template -typename VecTypeA::elem_type LMetric<1, true>::Evaluate( - const VecTypeA& a, - const VecTypeB& b) -{ - return arma::accu(abs(a - b)); -} - -template<> -template -typename VecTypeA::elem_type LMetric<1, false>::Evaluate( - const VecTypeA& a, - const VecTypeB& b) -{ - return arma::accu(abs(a - b)); -} - -// L2-metric specializations. -template<> -template -typename VecTypeA::elem_type LMetric<2, true>::Evaluate( - const VecTypeA& a, - const VecTypeB& b) -{ - return sqrt(arma::accu(square(a - b))); -} - -template<> -template -typename VecTypeA::elem_type LMetric<2, false>::Evaluate( - const VecTypeA& a, - const VecTypeB& b) -{ - return accu(arma::square(a - b)); -} - -// L3-metric specialization (not very likely to be used, but just in case). -template<> -template -typename VecTypeA::elem_type LMetric<3, true>::Evaluate( - const VecTypeA& a, - const VecTypeB& b) -{ - typename VecTypeA::elem_type sum = 0; - for (size_t i = 0; i < a.n_elem; i++) - sum += std::pow(fabs(a[i] - b[i]), 3.0); - - return std::pow(arma::accu(arma::pow(arma::abs(a - b), 3.0)), 1.0 / 3.0); -} - -template<> -template -typename VecTypeA::elem_type LMetric<3, false>::Evaluate( - const VecTypeA& a, - const VecTypeB& b) -{ - return arma::accu(arma::pow(arma::abs(a - b), 3.0)); -} - -// L-infinity (Chebyshev distance) specialization -template<> -template -typename VecTypeA::elem_type LMetric::Evaluate( - const VecTypeA& a, - const VecTypeB& b) -{ - return arma::as_scalar(arma::max(arma::abs(a - b))); -} - -} // namespace metric -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/metrics/mahalanobis_distance.hpp b/src/sdk/mlpack/include/mlpack/core/metrics/mahalanobis_distance.hpp deleted file mode 100644 index 22879b12a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/metrics/mahalanobis_distance.hpp +++ /dev/null @@ -1,126 +0,0 @@ -/*** - * @file mahalanobis_dstance.h - * @author Ryan Curtin - * - * The Mahalanobis distance. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_METRICS_MAHALANOBIS_DISTANCE_HPP -#define MLPACK_CORE_METRICS_MAHALANOBIS_DISTANCE_HPP - -#include - -namespace mlpack { -namespace metric { - -/** - * The Mahalanobis distance, which is essentially a stretched Euclidean - * distance. Given a square covariance matrix @f$ Q @f$ of size @f$ d @f$ x - * @f$ d @f$, where @f$ d @f$ is the dimensionality of the points it will be - * evaluating, and given two vectors @f$ x @f$ and @f$ y @f$ also of - * dimensionality @f$ d @f$, - * - * @f[ - * d(x, y) = \sqrt{(x - y)^T Q (x - y)} - * @f] - * - * where Q is the covariance matrix. - * - * Because each evaluation multiplies (x_1 - x_2) by the covariance matrix, it - * is typically much quicker to use an LMetric and simply stretch the actual - * dataset itself before performing any evaluations. However, this class is - * provided for convenience. - * - * If you wish to use the KNN class or other tree-based algorithms with this - * distance, it is recommended to instead stretch the dataset first, by - * decomposing Q = L^T L (perhaps via a Cholesky decomposition), and then - * multiply the data by L. If you still wish to use the KNN class with a custom - * distance anyway, you will need to use a different tree type than the default - * KDTree, which only works with the LMetric class. - * - * Similar to the LMetric class, this offers a template parameter TakeRoot - * which, when set to false, will instead evaluate the distance - * - * @f[ - * d(x, y) = (x - y)^T Q (x - y) - * @f] - * - * which is faster to evaluate. - * - * @tparam TakeRoot If true, takes the root of the output. It is slightly - * faster to leave this at the default of false, but this means the metric may - * not satisfy the triangle inequality and may not be usable for methods that - * expect a true metric. - */ -template -class MahalanobisDistance -{ - public: - /** - * Initialize the Mahalanobis distance with the empty matrix as covariance. - * Don't call Evaluate() until you set the covariance with Covariance()! - */ - MahalanobisDistance() { } - - /** - * Initialize the Mahalanobis distance with the identity matrix of the given - * dimensionality. - * - * @param dimensionality Dimesnsionality of the covariance matrix. - */ - MahalanobisDistance(const size_t dimensionality) : - covariance(arma::eye(dimensionality, dimensionality)) { } - - /** - * Initialize the Mahalanobis distance with the given covariance matrix. The - * given covariance matrix will be copied (this is not optimal). - * - * @param covariance The covariance matrix to use for this distance. - */ - MahalanobisDistance(const arma::mat& covariance) : covariance(covariance) { } - - /** - * Evaluate the distance between the two given points using this Mahalanobis - * distance. If the covariance matrix has not been set (i.e. if you used the - * empty constructor and did not later modify the covariance matrix), calling - * this method will probably result in a crash. - * - * @param a First vector. - * @param b Second vector. - */ - template - double Evaluate(const VecTypeA& a, const VecTypeB& b); - - /** - * Access the covariance matrix. - * - * @return Constant reference to the covariance matrix. - */ - const arma::mat& Covariance() const { return covariance; } - - /** - * Modify the covariance matrix. - * - * @return Reference to the covariance matrix. - */ - arma::mat& Covariance() { return covariance; } - - //! Serialize the Mahalanobis distance. - template - void serialize(Archive& ar, const unsigned int version); - - private: - //! The covariance matrix associated with this distance. - arma::mat covariance; -}; - -} // namespace metric -} // namespace mlpack - -#include "mahalanobis_distance_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/metrics/mahalanobis_distance_impl.hpp b/src/sdk/mlpack/include/mlpack/core/metrics/mahalanobis_distance_impl.hpp deleted file mode 100644 index cacabb451..000000000 --- a/src/sdk/mlpack/include/mlpack/core/metrics/mahalanobis_distance_impl.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/*** - * @file mahalanobis_distance.cc - * @author Ryan Curtin - * - * Implementation of the Mahalanobis distance. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_METRICS_MAHALANOBIS_DISTANCE_IMPL_HPP -#define MLPACK_CORE_METRICS_MAHALANOBIS_DISTANCE_IMPL_HPP - -#include "mahalanobis_distance.hpp" - -namespace mlpack { -namespace metric { - -/** - * Specialization for non-rooted case. - */ -template<> -template -double MahalanobisDistance::Evaluate(const VecTypeA& a, - const VecTypeB& b) -{ - arma::vec m = (a - b); - arma::mat out = trans(m) * covariance * m; // 1x1 - return out[0]; -} -/** - * Specialization for rooted case. This requires one extra evaluation of - * sqrt(). - */ -template<> -template -double MahalanobisDistance::Evaluate(const VecTypeA& a, - const VecTypeB& b) -{ - // Check if covariance matrix has been initialized. - if (covariance.n_rows == 0) - covariance = arma::eye(a.n_elem, a.n_elem); - - arma::vec m = (a - b); - arma::mat out = trans(m) * covariance * m; // 1x1; - return sqrt(out[0]); -} - -// Serialize the Mahalanobis distance. -template -template -void MahalanobisDistance::serialize(Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(covariance); -} - -} // namespace metric -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/ada_delta/ada_delta.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/ada_delta/ada_delta.hpp deleted file mode 100644 index e13137fea..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/ada_delta/ada_delta.hpp +++ /dev/null @@ -1,154 +0,0 @@ -/** - * @file ada_delta.hpp - * @author Ryan Curtin - * @author Vasanth Kalingeri - * @author Abhinav Moudgil - * - * Implementation of the AdaDelta optimizer. AdaDelta is an optimizer that - * dynamically adapts over time using only first order information. - * Additionally, AdaDelta requires no manual tuning of a learning rate. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADA_DELTA_ADA_DELTA_HPP -#define MLPACK_CORE_OPTIMIZERS_ADA_DELTA_ADA_DELTA_HPP - -#include -#include -#include "ada_delta_update.hpp" - -namespace mlpack { -namespace optimization { - -/** - * AdaDelta is an optimizer that uses two ideas to improve upon the two main - * drawbacks of the Adagrad method: - * - * - Accumulate Over Window - * - Correct Units with Hessian Approximation - * - * For more information, see the following. - * - * @code - * @article{Zeiler2012, - * author = {Matthew D. Zeiler}, - * title = {{ADADELTA:} An Adaptive Learning Rate Method}, - * journal = {CoRR}, - * year = {2012} - * } - * @endcode - * - * For AdaDelta to work, a DecomposableFunctionType template parameter is - * required. This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - */ -class AdaDelta -{ - public: - /** - * Construct the AdaDelta optimizer with the given function and parameters. - * The defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Number of points to process in one step. - * @param rho Smoothing constant. - * @param epsilon Value used to initialise the mean squared gradient - * parameter. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - */ - AdaDelta(const double stepSize = 1.0, - const size_t batchSize = 32, - const double rho = 0.95, - const double epsilon = 1e-6, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true); - - /** - * Optimize the given function using AdaDelta. The given starting point will - * be modified to store the finishing point of the algorithm, and the final - * objective value is returned. The DecomposableFunctionType is checked for - * API consistency at compile time. - * - * @tparam DecomposableFunctionType Type of the function to optimize. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate) - { - return optimizer.Optimize(function, iterate); - } - - //! Get the step size. - double StepSize() const { return optimizer.StepSize(); } - //! Modify the step size. - double& StepSize() { return optimizer.StepSize(); } - - //! Get the batch size. - size_t BatchSize() const { return optimizer.BatchSize(); } - //! Modify the batch size. - size_t& BatchSize() { return optimizer.BatchSize(); } - - //! Get the smoothing parameter. - double Rho() const { return optimizer.UpdatePolicy().Rho(); } - //! Modify the smoothing parameter. - double& Rho() { return optimizer.UpdatePolicy().Rho(); } - - //! Get the value used to initialise the mean squared gradient parameter. - double Epsilon() const { return optimizer.UpdatePolicy().Epsilon(); } - //! Modify the value used to initialise the mean squared gradient parameter. - double& Epsilon() { return optimizer.UpdatePolicy().Epsilon(); } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return optimizer.MaxIterations(); } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return optimizer.MaxIterations(); } - - //! Get the tolerance for termination. - double Tolerance() const { return optimizer.Tolerance(); } - //! Modify the tolerance for termination. - double& Tolerance() { return optimizer.Tolerance(); } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return optimizer.Shuffle(); } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return optimizer.Shuffle(); } - - private: - //! The Stochastic Gradient Descent object with AdaDelta policy. - SGD optimizer; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/ada_delta/ada_delta_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/ada_delta/ada_delta_update.hpp deleted file mode 100644 index 150a09560..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/ada_delta/ada_delta_update.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @file ada_delta_update.hpp - * @author Vasanth Kalingeri - * @author Abhinav Moudgil - * - * AdaDelta update for Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADA_DELTA_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_ADA_DELTA_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Implementation of the AdaDelta update policy. AdaDelta is an optimizer that - * uses two ideas to improve upon the two main drawbacks of the AdaGrad method: - * - * - Accumulate Over Window - * - Correct Units with Hessian Approximation - * - * For more information, see the following. - * - * @code - * @article{Zeiler2012, - * author = {Matthew D. Zeiler}, - * title = {{ADADELTA:} An Adaptive Learning Rate Method}, - * journal = {CoRR}, - * year = {2012} - * } - * @endcode - * - */ -class AdaDeltaUpdate -{ - public: - /** - * Construct the AdaDelta update policy with given rho and epsilon parameters. - * - * @param rho The smoothing parameter. - * @param epsilon The epsilon value used to initialise the squared gradient - * parameter. - */ - AdaDeltaUpdate(const double rho = 0.95, const double epsilon = 1e-6) : - rho(rho), - epsilon(epsilon) - { - // Nothing to do. - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. In AdaDelta update policy, the mean squared - * and the delta mean squared gradient matrices are initialized to the zeros - * matrix with the same size as gradient matrix - * (see mlpack::optimization::SGD::Optimizer). - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - // Initialize empty matrices for mean sum of squares of parameter gradient. - meanSquaredGradient = arma::zeros(rows, cols); - meanSquaredGradientDx = arma::zeros(rows, cols); - } - - /** - * Update step for SGD. The AdaDelta update dynamically adapts over time using - * only first order information. Additionally, AdaDelta requires no manual - * tuning of a learning rate. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Accumulate gradient. - meanSquaredGradient *= rho; - meanSquaredGradient += (1 - rho) * (gradient % gradient); - arma::mat dx = arma::sqrt((meanSquaredGradientDx + epsilon) / - (meanSquaredGradient + epsilon)) % gradient; - - // Accumulate updates. - meanSquaredGradientDx *= rho; - meanSquaredGradientDx += (1 - rho) * (dx % dx); - - // Apply update. - iterate -= (stepSize * dx); - } - - //! Get the smoothing parameter. - double Rho() const { return rho; } - //! Modify the smoothing parameter. - double& Rho() { return rho; } - - //! Get the value used to initialise the mean squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the mean squared gradient parameter. - double& Epsilon() { return epsilon; } - - private: - // The smoothing parameter. - double rho; - - // The epsilon value used to initialise the mean squared gradient parameter. - double epsilon; - - // The mean squared gradient matrix. - arma::mat meanSquaredGradient; - - // The delta mean squared gradient matrix. - arma::mat meanSquaredGradientDx; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/ada_grad/ada_grad.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/ada_grad/ada_grad.hpp deleted file mode 100644 index b1e9d9b68..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/ada_grad/ada_grad.hpp +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @file ada_grad.hpp - * @author Abhinav Moudgil - * - * Implementation of the AdaGrad optimizer. AdaGrad is an optimizer that - * chooses learning rate dynamically by adapting to the data. Hence AdaGrad - * eliminates the need to manually tune the learning rate. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADA_GRAD_ADA_GRAD_HPP -#define MLPACK_CORE_OPTIMIZERS_ADA_GRAD_ADA_GRAD_HPP - -#include -#include -#include "ada_grad_update.hpp" - -namespace mlpack { -namespace optimization { - -/** - * AdaGrad is a modified version of stochastic gradient descent which performs - * larger updates for more sparse parameters and smaller updates for less sparse - * parameters. - * - * For more information, see the following. - * - * @code - * @article{duchi2011adaptive, - * author = {Duchi, John and Hazan, Elad and Singer, Yoram}, - * title = {Adaptive subgradient methods for online learning and stochastic - * optimization}, - * journal = {Journal of Machine Learning Research}, - * volume = {12}, - * number = {Jul}, - * pages = {2121--2159}, - * year = {2011} - * } - * @endcode - * - * For AdaGrad to work, a DecomposableFunctionTypes template parameter is - * required. This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - */ -class AdaGrad -{ - public: - /** - * Construct the AdaGrad optimizer with the given function and parameters. - * The defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Number of points to process in one step. - * @param epsilon Value used to initialise the squared gradient parameter. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - */ - AdaGrad(const double stepSize = 0.01, - const size_t batchSize = 32, - const double epsilon = 1e-8, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true); - - /** - * Optimize the given function using AdaGrad. The given starting point will - * be modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to optimize. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate) - { - return optimizer.Optimize(function, iterate); - } - - //! Get the step size. - double StepSize() const { return optimizer.StepSize(); } - //! Modify the step size. - double& StepSize() { return optimizer.StepSize(); } - - //! Get the batch size. - size_t BatchSize() const { return optimizer.BatchSize(); } - //! Modify the batch size. - size_t& BatchSize() { return optimizer.BatchSize(); } - - //! Get the value used to initialise the squared gradient parameter. - double Epsilon() const { return optimizer.UpdatePolicy().Epsilon(); } - //! Modify the value used to initialise the squared gradient parameter. - double& Epsilon() { return optimizer.UpdatePolicy().Epsilon(); } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return optimizer.MaxIterations(); } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return optimizer.MaxIterations(); } - - //! Get the tolerance for termination. - double Tolerance() const { return optimizer.Tolerance(); } - //! Modify the tolerance for termination. - double& Tolerance() { return optimizer.Tolerance(); } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return optimizer.Shuffle(); } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return optimizer.Shuffle(); } - - private: - //! The Stochastic Gradient Descent object with AdaGrad policy. - SGD optimizer; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/ada_grad/ada_grad_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/ada_grad/ada_grad_update.hpp deleted file mode 100644 index 93c3ac0f1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/ada_grad/ada_grad_update.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @file ada_grad_update.hpp - * @author Abhinav Moudgil - * - * AdaGrad update for Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADA_GRAD_ADA_GRAD_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_ADA_GRAD_ADA_GRAD_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Implementation of the AdaGrad update policy. AdaGrad update policy chooses - * learning rate dynamically by adapting to the data. Hence AdaGrad eliminates - * the need to manually tune the learning rate. - * - * For more information, see the following. - * - * @code - * @article{duchi2011adaptive, - * author = {Duchi, John and Hazan, Elad and Singer, Yoram}, - * title = {Adaptive subgradient methods for online learning and - * stochastic optimization}, - * journal = {Journal of Machine Learning Research}, - * volume = {12}, - * number = {Jul}, - * pages = {2121--2159}, - * year = {2011} - * } - * @endcode - * - */ -class AdaGradUpdate -{ - public: - /** - * Construct the AdaGrad update policy with given epsilon parameter. - * - * @param epsilon The epsilon value used to initialise the squared gradient - * parameter. - */ - AdaGradUpdate(const double epsilon = 1e-8) : epsilon(epsilon) - { - // Nothing to do. - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. In AdaGrad update policy, squared - * gradient matrix is initialized to the zeros matrix with the same size as - * gradient matrix (see mlpack::optimization::SGD::Optimizer). - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - // Initialize an empty matrix for sum of squares of parameter gradient. - squaredGradient = arma::zeros(rows, cols); - } - - /** - * Update step for SGD. The AdaGrad update adapts the learning rate by - * performing larger updates for more sparse parameters and smaller updates - * for less sparse parameters . - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - squaredGradient += (gradient % gradient); - iterate -= (stepSize * gradient) / (arma::sqrt(squaredGradient) + epsilon); - } - - //! Get the value used to initialise the squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the squared gradient parameter. - double& Epsilon() { return epsilon; } - - private: - // The epsilon value used to initialise the squared gradient parameter. - double epsilon; - - // The squared gradient matrix. - arma::mat squaredGradient; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam.hpp deleted file mode 100644 index e1fa7d6df..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam.hpp +++ /dev/null @@ -1,198 +0,0 @@ -/** - * @file adam.hpp - * @author Ryan Curtin - * @author Vasanth Kalingeri - * @author Marcus Edel - * @author Vivek Pal - * @author Sourabh Varshney - * @author Haritha Nair - * - * Adam, AdaMax, AMSGrad, Nadam and Nadamax optimizers. Adam is an an algorithm - * for first-order gradient-based optimization of stochastic objective - * functions, based on adaptive estimates of lower-order moments. AdaMax is - * simply a variant of Adam based on the infinity norm. AMSGrad is another - * variant of Adam with guaranteed convergence. Nadam is another variant of - * Adam based on NAG. NadaMax is a variant for Nadam based on Infinity form. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADAM_ADAM_HPP -#define MLPACK_CORE_OPTIMIZERS_ADAM_ADAM_HPP - -#include - -#include -#include "adam_update.hpp" -#include "adamax_update.hpp" -#include "amsgrad_update.hpp" -#include "nadam_update.hpp" -#include "nadamax_update.hpp" -#include "optimisticadam_update.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Adam is an optimizer that computes individual adaptive learning rates for - * different parameters from estimates of first and second moments of the - * gradients. AdaMax is a variant of Adam based on the infinity norm as given - * in the section 7 of the following paper. Nadam is an optimizer that - * combines the Adam and NAG. NadaMax is an variant of Nadam based on Infinity - * form. - * - * For more information, see the following. - * - * @code - * @article{Kingma2014, - * author = {Diederik P. Kingma and Jimmy Ba}, - * title = {Adam: {A} Method for Stochastic Optimization}, - * journal = {CoRR}, - * year = {2014}, - * url = {http://arxiv.org/abs/1412.6980} - * } - * @article{ - * title = {On the convergence of Adam and beyond}, - * url = {https://openreview.net/pdf?id=ryQu7f-RZ} - * year = {2018} - * } - * @endcode - * - * For Adam, AdaMax, AMSGrad, Nadam and NadaMax to work, a DecomposableFunctionType - * template parameter is required. This class must implement the following - * function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - * - * @tparam UpdateRule Adam optimizer update rule to be used. - */ -template -class AdamType -{ - public: - /** - * Construct the Adam optimizer with the given function and parameters. The - * defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Number of points to process in a single step. - * @param beta1 Exponential decay rate for the first moment estimates. - * @param beta2 Exponential decay rate for the weighted infinity norm - estimates. - * @param eps Value used to initialise the mean squared gradient parameter. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - */ - AdamType(const double stepSize = 0.001, - const size_t batchSize = 32, - const double beta1 = 0.9, - const double beta2 = 0.999, - const double eps = 1e-8, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true); - - /** - * Optimize the given function using Adam. The given starting point will be - * modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to optimize. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate) - { - return optimizer.Optimize(function, iterate); - } - - //! Get the step size. - double StepSize() const { return optimizer.StepSize(); } - //! Modify the step size. - double& StepSize() { return optimizer.StepSize(); } - - //! Get the batch size. - size_t BatchSize() const { return optimizer.BatchSize(); } - //! Modify the batch size. - size_t& BatchSize() { return optimizer.BatchSize(); } - - //! Get the smoothing parameter. - double Beta1() const { return optimizer.UpdatePolicy().Beta1(); } - //! Modify the smoothing parameter. - double& Beta1() { return optimizer.UpdatePolicy().Beta1(); } - - //! Get the second moment coefficient. - double Beta2() const { return optimizer.UpdatePolicy().Beta2(); } - //! Modify the second moment coefficient. - double& Beta2() { return optimizer.UpdatePolicy().Beta2(); } - - //! Get the value used to initialise the mean squared gradient parameter. - double Epsilon() const { return optimizer.UpdatePolicy().Epsilon(); } - //! Modify the value used to initialise the mean squared gradient parameter. - double& Epsilon() { return optimizer.UpdatePolicy().Epsilon(); } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return optimizer.MaxIterations(); } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return optimizer.MaxIterations(); } - - //! Get the tolerance for termination. - double Tolerance() const { return optimizer.Tolerance(); } - //! Modify the tolerance for termination. - double& Tolerance() { return optimizer.Tolerance(); } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return optimizer.Shuffle(); } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return optimizer.Shuffle(); } - - private: - //! The Stochastic Gradient Descent object with Adam policy. - SGD optimizer; -}; - -using Adam = AdamType; - -using AdaMax = AdamType; - -using AMSGrad = AdamType; - -using Nadam = AdamType; - -using NadaMax = AdamType; - -using OptimisticAdam = AdamType; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "adam_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam_impl.hpp deleted file mode 100644 index 7b247d2dd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam_impl.hpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @file adam_impl.hpp - * @author Ryan Curtin - * @author Vasanth Kalingeri - * @author Marcus Edel - * @author Vivek Pal - * - * Implementation of the Adam, AdaMax, AMSGrad, Nadam and NadaMax optimizer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADAM_ADAM_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_ADAM_ADAM_IMPL_HPP - -// In case it hasn't been included yet. -#include "adam.hpp" - -namespace mlpack { -namespace optimization { - -template -AdamType::AdamType( - const double stepSize, - const size_t batchSize, - const double beta1, - const double beta2, - const double epsilon, - const size_t maxIterations, - const double tolerance, - const bool shuffle) : - optimizer(stepSize, - batchSize, - maxIterations, - tolerance, - shuffle, - UpdateRule(epsilon, beta1, beta2)) -{ /* Nothing to do. */ } - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam_update.hpp deleted file mode 100644 index 266b66285..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adam_update.hpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @file adam_update.hpp - * @author Ryan Curtin - * @author Vasanth Kalingeri - * @author Marcus Edel - * @author Vivek Pal - * - * Adam optimizer. Adam is an an algorithm for first-order gradient-based - * optimization of stochastic objective functions, based on adaptive estimates - * of lower-order moments. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADAM_ADAM_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_ADAM_ADAM_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Adam is an optimizer that computes individual adaptive learning rates for - * different parameters from estimates of first and second moments of the - * gradients as given in the section 7 of the following paper. - * - * For more information, see the following. - * - * @code - * @article{Kingma2014, - * author = {Diederik P. Kingma and Jimmy Ba}, - * title = {Adam: {A} Method for Stochastic Optimization}, - * journal = {CoRR}, - * year = {2014}, - * url = {http://arxiv.org/abs/1412.6980} - * } - * @endcode - */ -class AdamUpdate -{ - public: - /** - * Construct the Adam update policy with the given parameters. - * - * @param epsilon The epsilon value used to initialise the squared gradient - * parameter. - * @param beta1 The smoothing parameter. - * @param beta2 The second moment coefficient. - */ - AdamUpdate(const double epsilon = 1e-8, - const double beta1 = 0.9, - const double beta2 = 0.999) : - epsilon(epsilon), - beta1(beta1), - beta2(beta2), - iteration(0) - { - // Nothing to do. - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - m = arma::zeros(rows, cols); - v = arma::zeros(rows, cols); - } - - /** - * Update step for Adam. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Increment the iteration counter variable. - ++iteration; - - // And update the iterate. - m *= beta1; - m += (1 - beta1) * gradient; - - v *= beta2; - v += (1 - beta2) * (gradient % gradient); - - const double biasCorrection1 = 1.0 - std::pow(beta1, iteration); - const double biasCorrection2 = 1.0 - std::pow(beta2, iteration); - - /** - * It should be noted that the term, m / (arma::sqrt(v) + eps), in the - * following expression is an approximation of the following actual term; - * m / (arma::sqrt(v) + (arma::sqrt(biasCorrection2) * eps). - */ - iterate -= (stepSize * std::sqrt(biasCorrection2) / biasCorrection1) * - m / (arma::sqrt(v) + epsilon); - } - - //! Get the value used to initialise the squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the squared gradient parameter. - double& Epsilon() { return epsilon; } - - //! Get the smoothing parameter. - double Beta1() const { return beta1; } - //! Modify the smoothing parameter. - double& Beta1() { return beta1; } - - //! Get the second moment coefficient. - double Beta2() const { return beta2; } - //! Modify the second moment coefficient. - double& Beta2() { return beta2; } - - private: - // The epsilon value used to initialise the squared gradient parameter. - double epsilon; - - // The smoothing parameter. - double beta1; - - // The second moment coefficient. - double beta2; - - // The exponential moving average of gradient values. - arma::mat m; - - // The exponential moving average of squared gradient values. - arma::mat v; - - // The number of iterations. - double iteration; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adamax_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adamax_update.hpp deleted file mode 100644 index 0d8b6320c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/adamax_update.hpp +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @file adamax_update.hpp - * @author Ryan Curtin - * @author Vasanth Kalingeri - * @author Marcus Edel - * @author Vivek Pal - * - * AdaMax update rule. Adam is an an algorithm for first-order gradient- - * -based optimization of stochastic objective functions, based on adaptive - * estimates of lower-order moments. AdaMax is simply a variant of Adam based - * on the infinity norm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADAM_ADAMAX_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_ADAM_ADAMAX_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * AdaMax is a variant of Adam, an optimizer that computes individual adaptive - * learning rates for different parameters from estimates of first and second - * moments of the gradients.based on the infinity norm as given in the section - * 7 of the following paper. - * - * For more information, see the following. - * - * @code - * @article{Kingma2014, - * author = {Diederik P. Kingma and Jimmy Ba}, - * title = {Adam: {A} Method for Stochastic Optimization}, - * journal = {CoRR}, - * year = {2014}, - * url = {http://arxiv.org/abs/1412.6980} - * } - * @endcode - */ -class AdaMaxUpdate -{ - public: - /** - * Construct the AdaMax update policy with the given parameters. - * - * @param epsilon The epsilon value used to initialise the squared gradient - * parameter. - * @param beta1 The smoothing parameter. - * @param beta2 The second moment coefficient. - */ - AdaMaxUpdate(const double epsilon = 1e-8, - const double beta1 = 0.9, - const double beta2 = 0.999) : - epsilon(epsilon), - beta1(beta1), - beta2(beta2), - iteration(0) - { - // Nothing to do. - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - m = arma::zeros(rows, cols); - u = arma::zeros(rows, cols); - } - - /** - * Update step for Adam. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Increment the iteration counter variable. - ++iteration; - - // And update the iterate. - m *= beta1; - m += (1 - beta1) * gradient; - - // Update the exponentially weighted infinity norm. - u *= beta2; - u = arma::max(u, arma::abs(gradient)); - - const double biasCorrection1 = 1.0 - std::pow(beta1, iteration); - - if (biasCorrection1 != 0) - iterate -= (stepSize / biasCorrection1 * m / (u + epsilon)); - } - - //! Get the value used to initialise the squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the squared gradient parameter. - double& Epsilon() { return epsilon; } - - //! Get the smoothing parameter. - double Beta1() const { return beta1; } - //! Modify the smoothing parameter. - double& Beta1() { return beta1; } - - //! Get the second moment coefficient. - double Beta2() const { return beta2; } - //! Modify the second moment coefficient. - double& Beta2() { return beta2; } - - private: - // The epsilon value used to initialise the squared gradient parameter. - double epsilon; - - // The smoothing parameter. - double beta1; - - // The second moment coefficient. - double beta2; - - // The exponential moving average of gradient values. - arma::mat m; - - // The exponentially weighted infinity norm. - arma::mat u; - - // The number of iterations. - double iteration; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/amsgrad_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/adam/amsgrad_update.hpp deleted file mode 100644 index f2a126f18..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/amsgrad_update.hpp +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @file amsgrad_update.hpp - * @author Haritha Nair - * - * Implementation of AMSGrad optimizer. AMSGrad is an exponential moving average - * optimizer that dynamically adapts over time with guaranteed convergence. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_AMS_GRAD_AMS_GRAD_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_AMS_GRAD_AMS_GRAD_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * AMSGrad is an exponential moving average variant which along with having - * benefits of optimizers like Adam and RMSProp, also guarantees convergence. - * Unlike Adam, it uses maximum of past squared gradients rather than their - * exponential average for updation. - * - * For more information, see the following. - * - * @code - * @article{ - * title = {On the convergence of Adam and beyond}, - * url = {https://openreview.net/pdf?id=ryQu7f-RZ} - * year = {2018} - * } - * @endcode - */ -class AMSGradUpdate -{ - public: - /** - * Construct the AMSGrad update policy with the given parameters. - * - * @param epsilon The epsilon value used to initialise the squared gradient - * parameter. - * @param beta1 The smoothing parameter. - * @param beta2 The second moment coefficient. - */ - AMSGradUpdate(const double epsilon = 1e-8, - const double beta1 = 0.9, - const double beta2 = 0.999) : - epsilon(epsilon), - beta1(beta1), - beta2(beta2), - iteration(0) - { - // Nothing to do. - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - m = arma::zeros(rows, cols); - v = arma::zeros(rows, cols); - vImproved = arma::zeros(rows, cols); - } - - /** - * Update step for AMSGrad. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Increment the iteration counter variable. - ++iteration; - - // And update the iterate. - m *= beta1; - m += (1 - beta1) * gradient; - - v *= beta2; - v += (1 - beta2) * (gradient % gradient); - - const double biasCorrection1 = 1.0 - std::pow(beta1, iteration); - const double biasCorrection2 = 1.0 - std::pow(beta2, iteration); - - // Element wise maximum of past and present squared gradients. - vImproved = arma::max(vImproved, v); - - iterate -= (stepSize * std::sqrt(biasCorrection2) / biasCorrection1) * - m / (arma::sqrt(vImproved) + epsilon); - } - - //! Get the value used to initialise the squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the squared gradient parameter. - double& Epsilon() { return epsilon; } - - //! Get the smoothing parameter. - double Beta1() const { return beta1; } - //! Modify the smoothing parameter. - double& Beta1() { return beta1; } - - //! Get the second moment coefficient. - double Beta2() const { return beta2; } - //! Modify the second moment coefficient. - double& Beta2() { return beta2; } - - private: - // The epsilon value used to initialise the squared gradient parameter. - double epsilon; - - // The smoothing parameter. - double beta1; - - // The second moment coefficient. - double beta2; - - // The exponential moving average of gradient values. - arma::mat m; - - // The exponential moving average of squared gradient values. - arma::mat v; - - // The optimal sqaured gradient value. - arma::mat vImproved; - - // The number of iterations. - double iteration; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/nadam_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/adam/nadam_update.hpp deleted file mode 100644 index 5d245f9f3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/nadam_update.hpp +++ /dev/null @@ -1,173 +0,0 @@ -/** - * @file nadam_update.hpp - * @author Sourabh Varshney - * - * Nadam update rule. Nadam is an optimizer that combines the effect of Adam - * and NAG to the gradient descent to improve its Performance. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADAM_NADAM_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_ADAM_NADAM_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Nadam is an optimizer that combines the Adam and NAG optimization strategies. - * - * For more information, see the following. - * - * @code - * @techreport{Dozat2015, - * title = {Incorporating Nesterov momentum into Adam}, - * author = {Timothy Dozat}, - * institution = {Stanford University}, - * address = {Stanford}, - * year = {2015}, - * url = {https://openreview.net/pdf?id=OM0jvwB8jIp57ZJjtNEZ} - * } - * @endcode - */ -class NadamUpdate -{ - public: - /** - * Construct the Nadam update policy with the given parameters. - * - * @param epsilon The epsilon value used to initialise the squared gradient - * parameter. - * @param beta1 The smoothing parameter. - * @param beta2 The second moment coefficient - * @param scheduleDecay The decay parameter for decay coefficients - */ - NadamUpdate(const double epsilon = 1e-8, - const double beta1 = 0.9, - const double beta2 = 0.99, - const double scheduleDecay = 4e-3) : - epsilon(epsilon), - beta1(beta1), - beta2(beta2), - scheduleDecay(scheduleDecay), - iteration(0), - cumBeta1(1) - { - // Nothing to do. - } - - /** - * The Initialize() method is called by the optimizer before the start of the - * iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - m = arma::zeros(rows, cols); - v = arma::zeros(rows, cols); - } - - /** - * Update step for Nadam. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Increment the iteration counter variable. - ++iteration; - - // And update the iterate. - m *= beta1; - m += (1 - beta1) * gradient; - - v *= beta2; - v += (1 - beta2) * gradient % gradient; - - double beta1T = beta1 * (1 - (0.5 * - std::pow(0.96, iteration * scheduleDecay))); - - double beta1T1 = beta1 * (1 - (0.5 * - std::pow(0.96, (iteration + 1) * scheduleDecay))); - - cumBeta1 *= beta1T; - - const double biasCorrection1 = 1.0 - cumBeta1; - - const double biasCorrection2 = 1.0 - std::pow(beta2, iteration); - - const double biasCorrection3 = 1.0 - (cumBeta1 * beta1T1); - - /* Note :- arma::sqrt(v) + epsilon * sqrt(biasCorrection2) is approximated - * as arma::sqrt(v) + epsilon - */ - iterate -= (stepSize * (((1 - beta1T) / biasCorrection1) * gradient - + (beta1T1 / biasCorrection3) * m) * sqrt(biasCorrection2)) - / (arma::sqrt(v) + epsilon); - } - - //! Get the value used to initialise the squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the squared gradient parameter. - double& Epsilon() { return epsilon; } - - //! Get the value of the cumulative product of decay coefficients - double CumBeta1() const { return cumBeta1; } - //! Modify the value of the cumulative product of decay coefficients - double& CumBeta1() { return cumBeta1; } - - //! Get the smoothing parameter. - double Beta1() const { return beta1; } - //! Modify the smoothing parameter. - double& Beta1() { return beta1; } - - //! Get the second moment coefficient. - double Beta2() const { return beta2; } - //! Modify the second moment coefficient. - double& Beta2() { return beta2; } - - //! Get the decay parameter for decay coefficients - double ScheduleDecay() const { return scheduleDecay; } - //! Modify the decay parameter for decay coefficients - double& ScheduleDecay() { return scheduleDecay; } - - private: - // The epsilon value used to initialise the squared gradient parameter. - double epsilon; - - // The smoothing parameter. - double beta1; - - // The second moment coefficient. - double beta2; - - // The exponential moving average of gradient values. - arma::mat m; - - // The exponential moving average of squared gradient values. - arma::mat v; - - // The decay parameter for decay coefficients - double scheduleDecay; - - // The number of iterations. - double iteration; - - // The cumulative product of decay coefficients - double cumBeta1; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/nadamax_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/adam/nadamax_update.hpp deleted file mode 100644 index 4f69f1758..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/nadamax_update.hpp +++ /dev/null @@ -1,169 +0,0 @@ -/** - * @file nadamax_update.hpp - * @author Sourabh Varshney - * - * NadaMax update rule. NadaMax is an optimizer that combines the effect of - * Adamax and NAG to the gradient descent to improve its Performance. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADAM_NADAMAX_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_ADAM_NADAMAX_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * NadaMax is an optimizer that combines the AdaMax and NAG. - * - * For more information, see the following. - * - * @code - * @techreport{Dozat2015, - * title = {Incorporating Nesterov momentum into Adam}, - * author = {Timothy Dozat}, - * institution = {Stanford University}, - * address = {Stanford}, - * year = {2015}, - * url = {https://openreview.net/pdf?id=OM0jvwB8jIp57ZJjtNEZ} - * } - * @endcode - */ -class NadaMaxUpdate -{ - public: - /** - * Construct the NadaMax update policy with the given parameters. - * - * @param epsilon The epsilon value used to initialise the squared gradient - * parameter. - * @param beta1 The smoothing parameter. - * @param beta2 The second moment coefficient - * @param scheduleDecay The decay parameter for decay coefficients - */ - NadaMaxUpdate(const double epsilon = 1e-8, - const double beta1 = 0.9, - const double beta2 = 0.99, - const double scheduleDecay = 4e-3) : - epsilon(epsilon), - beta1(beta1), - beta2(beta2), - scheduleDecay(scheduleDecay), - cumBeta1(1), - iteration(0) - { - // Nothing to do. - } - - /** - * The Initialize() method is called by the optimizer before the start of the - * iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - m = arma::zeros(rows, cols); - u = arma::zeros(rows, cols); - } - - /** - * Update step for NadaMax. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Increment the iteration counter variable. - ++iteration; - - // And update the iterate. - m *= beta1; - m += (1 - beta1) * gradient; - - u = arma::max(u * beta2, arma::abs(gradient)); - - double beta1T = beta1 * (1 - (0.5 * - std::pow(0.96, iteration * scheduleDecay))); - - double beta1T1 = beta1 * (1 - (0.5 * - std::pow(0.96, (iteration + 1) * scheduleDecay))); - - cumBeta1 *= beta1T; - - const double biasCorrection1 = 1.0 - cumBeta1; - - const double biasCorrection2 = 1.0 - (cumBeta1 * beta1T1); - - if ((biasCorrection1 != 0) && (biasCorrection2 != 0)) - { - iterate -= (stepSize * (((1 - beta1T) / biasCorrection1) * gradient - + (beta1T1 / biasCorrection2) * m)) / (u + epsilon); - } - } - - //! Get the value used to initialise the squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the squared gradient parameter. - double& Epsilon() { return epsilon; } - - //! Get the value of the cumulative product of decay coefficients - double CumBeta1() const { return cumBeta1; } - //! Modify the value of the cumulative product of decay coefficients - double& CumBeta1() { return cumBeta1; } - - //! Get the smoothing parameter. - double Beta1() const { return beta1; } - //! Modify the smoothing parameter. - double& Beta1() { return beta1; } - - //! Get the second moment coefficient. - double Beta2() const { return beta2; } - //! Modify the second moment coefficient. - double& Beta2() { return beta2; } - - //! Get the decay parameter for decay coefficients - double ScheduleDecay() const { return scheduleDecay; } - //! Modify the decay parameter for decay coefficients - double& ScheduleDecay() { return scheduleDecay; } - - private: - // The epsilon value used to initialise the squared gradient parameter. - double epsilon; - - // The smoothing parameter. - double beta1; - - // The second moment coefficient. - double beta2; - - // The exponential moving average of gradient values. - arma::mat m; - - // The exponentially weighted infinity norm. - arma::mat u; - - // The decay parameter for decay coefficients - double scheduleDecay; - - // The cumulative product of decay coefficients - double cumBeta1; - - // The number of iterations. - double iteration; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/optimisticadam_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/adam/optimisticadam_update.hpp deleted file mode 100644 index 06b45d927..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/adam/optimisticadam_update.hpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @file optimisticadam_update.hpp - * @author Moksh Jain - * - * OptmisticAdam optimizer. Implements Optimistic Adam, an algorithm which - * uses Optimistic Mirror Descent with the Adam optimizer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADAM_OPTIMISTICADAM_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_ADAM_OPTIMISTICADAM_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * OptimisticAdam is an optimizer which implements the Optimistic Adam - * algorithm which uses Optmistic Mirror Descent with the Adam Optimizer. - * It addresses the problem of limit cycling while training GANs. It uses - * OMD to achieve faster regret rates in solving the zero sum game of - * training a GAN. It consistently achieves a smaller KL divergnce with - * respect to the true underlying data distribution. - * - * For more information, see the following. - * - * @code - * @article{ - * author = {Constantinos Daskalakis, Andrew Ilyas, Vasilis Syrgkanis, - * Haoyang Zeng}, - * title = {Training GANs with Optimism}, - * year = {2017}, - * url = {https://arxiv.org/abs/1711.00141} - * } - * @endcode - */ -class OptimisticAdamUpdate -{ - public: - /** - * Construct the OptimisticAdam update policy with the given parameters. - * - * @param epsilon The epsilon value used to initialize the squared gradient - * parameter. - * @param beta1 The smoothing parameter. - * @param beta2 The second moment coefficient. - */ - OptimisticAdamUpdate(const double epsilon = 1e-8, - const double beta1 = 0.9, - const double beta2 = 0.999) : - epsilon(epsilon), - beta1(beta1), - beta2(beta2), - iteration(0) - { - // Nothing to do. - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - m = arma::zeros(rows, cols); - v = arma::zeros(rows, cols); - g = arma::zeros(rows, cols); - } - - /** - * Update step for OptimisticAdam. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Increment the iteration counter variable. - ++iteration; - - // And update the iterate. - m *= beta1; - m += (1 - beta1) * gradient; - - v *= beta2; - v += (1 - beta2) * arma::square(gradient); - - arma::mat mCorrected = m / (1.0 - std::pow(beta1, iteration)); - arma::mat vCorrected = v / (1.0 - std::pow(beta2, iteration)); - - arma::mat update = mCorrected / (arma::sqrt(vCorrected) + epsilon); - - iterate -= (2 * stepSize * update - stepSize * g); - - g = std::move(update); - } - - //! Get the value used to initialize the squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialize the squared gradient parameter. - double& Epsilon() { return epsilon; } - - //! Get the smoothing parameter. - double Beta1() const { return beta1; } - //! Modify the smoothing parameter. - double& Beta1() { return beta1; } - - //! Get the second moment coefficient. - double Beta2() const { return beta2; } - //! Modify the second moment coefficient. - double& Beta2() { return beta2; } - - private: - // The epsilon value used to initialize the squared gradient parameter. - double epsilon; - - // The smoothing parameter. - double beta1; - - // The second moment coefficient. - double beta2; - - // The exponential moving average of gradient values. - arma::mat m; - - // The exponential moving average of squared gradient values. - arma::mat v; - // The previous update. - arma::mat g; - - // The number of iterations. - double iteration; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian.hpp deleted file mode 100644 index 17b4172f7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian.hpp +++ /dev/null @@ -1,146 +0,0 @@ -/** - * @file aug_lagrangian.hpp - * @author Ryan Curtin - * - * Definition of AugLagrangian class, which implements the Augmented Lagrangian - * optimization method (also called the 'method of multipliers'. This class - * uses the L-BFGS optimizer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_HPP -#define MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_HPP - -#include -#include - -#include "aug_lagrangian_function.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The AugLagrangian class implements the Augmented Lagrangian method of - * optimization. In this scheme, a penalty term is added to the Lagrangian. - * This method is also called the "method of multipliers". - * - * The template class LagrangianFunctionType, used by the Optimize() method, - * must implement the following five methods: - * - * - double Evaluate(const arma::mat& coordinates); - * - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - * - size_t NumConstraints(); - * - double EvaluateConstraint(size_t index, const arma::mat& coordinates); - * - double GradientConstraint(size_t index, const arma::mat& coordinates, - * arma::mat& gradient); - * - * The number of constraints must be greater than or equal to 0, and - * EvaluateConstraint() should evaluate the constraint at the given index for - * the given coordinates. Evaluate() should provide the objective function - * value for the given coordinates. - */ -class AugLagrangian -{ - public: - /** - * Initialize the Augmented Lagrangian with the default L-BFGS optimizer. We - * limit the number of L-BFGS iterations to 1000, rather than the unlimited - * default L-BFGS. - */ - AugLagrangian(); - - /** - * Initialize the Augmented Lagrangian with a custom L-BFGS optimizer. - * - * @param lbfgs The custom L-BFGS optimizer to be used. This should have - * already been initialized with the given AugLagrangianFunction. - */ - AugLagrangian(L_BFGS& lbfgs); - - /** - * Optimize the function. The value '1' is used for the initial value of each - * Lagrange multiplier. To set the Lagrange multipliers yourself, use the - * other overload of Optimize(). - * - * @tparam LagrangianFunctionType Function which can be optimized by this - * class. - * @param function The function to optimize. - * @param coordinates Output matrix to store the optimized coordinates in. - * @param maxIterations Maximum number of iterations of the Augmented - * Lagrangian algorithm. 0 indicates no maximum. - */ - template - bool Optimize(LagrangianFunctionType& function, - arma::mat& coordinates, - const size_t maxIterations = 1000); - - /** - * Optimize the function, giving initial estimates for the Lagrange - * multipliers. The vector of Lagrange multipliers will be modified to - * contain the Lagrange multipliers of the final solution (if one is found). - * - * @tparam LagrangianFunctionType Function which can be optimized by this - * class. - * @param function The function to optimize. - * @param coordinates Output matrix to store the optimized coordinates in. - * @param initLambda Vector of initial Lagrange multipliers. Should have - * length equal to the number of constraints. - * @param initSigma Initial penalty parameter. - * @param maxIterations Maximum number of iterations of the Augmented - * Lagrangian algorithm. 0 indicates no maximum. - */ - template - bool Optimize(LagrangianFunctionType& function, - arma::mat& coordinates, - const arma::vec& initLambda, - const double initSigma, - const size_t maxIterations = 1000); - - //! Get the L-BFGS object used for the actual optimization. - const L_BFGS& LBFGS() const { return lbfgs; } - //! Modify the L-BFGS object used for the actual optimization. - L_BFGS& LBFGS() { return lbfgs; } - - //! Get the Lagrange multipliers. - const arma::vec& Lambda() const { return lambda; } - //! Modify the Lagrange multipliers (i.e. set them before optimization). - arma::vec& Lambda() { return lambda; } - - //! Get the penalty parameter. - double Sigma() const { return sigma; } - //! Modify the penalty parameter. - double& Sigma() { return sigma; } - - private: - //! If the user did not pass an L_BFGS object, we'll use our own internal one. - L_BFGS lbfgsInternal; - - //! The L-BFGS optimizer that we will use. - L_BFGS& lbfgs; - - //! Lagrange multipliers. - arma::vec lambda; - //! Penalty parameter. - double sigma; - - /** - * Internal optimization function: given an initialized AugLagrangianFunction, - * perform the optimization itself. - */ - template - bool Optimize(AugLagrangianFunction& augfunc, - arma::mat& coordinates, - const size_t maxIterations); -}; - -} // namespace optimization -} // namespace mlpack - -#include "aug_lagrangian_impl.hpp" - -#endif // MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_function.hpp deleted file mode 100644 index 7f01d48e4..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_function.hpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @file aug_lagrangian_function.hpp - * @author Ryan Curtin - * - * Contains a utility class for AugLagrangian. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * This is a utility class used by AugLagrangian, meant to wrap a - * LagrangianFunction into a function usable by a simple optimizer like L-BFGS. - * Given a LagrangianFunction which follows the format outlined in the - * documentation for AugLagrangian, this class provides Evaluate(), Gradient(), - * and GetInitialPoint() functions which allow this class to be used with a - * simple optimizer like L-BFGS. - * - * This class can be specialized for your particular implementation -- commonly, - * a faster method for computing the overall objective and gradient of the - * augmented Lagrangian function can be implemented than the naive, default - * implementation given. Use class template specialization and re-implement all - * of the methods (unfortunately, C++ specialization rules mean you have to - * re-implement everything). - * - * @tparam LagrangianFunction Lagrangian function to be used. - */ -template -class AugLagrangianFunction -{ - public: - /** - * Initialize the AugLagrangianFunction, but don't set the Lagrange - * multipliers or penalty parameters yet. Make sure you set the Lagrange - * multipliers before you use this... - * - * @param function Lagrangian function. - */ - AugLagrangianFunction(LagrangianFunction& function); - - /** - * Initialize the AugLagrangianFunction with the given LagrangianFunction, - * Lagrange multipliers, and initial penalty parameter. - * - * @param function Lagrangian function. - * @param lambda Initial Lagrange multipliers. - * @param sigma Initial penalty parameter. - */ - AugLagrangianFunction(LagrangianFunction& function, - const arma::vec& lambda, - const double sigma); - /** - * Evaluate the objective function of the Augmented Lagrangian function, which - * is the standard Lagrangian function evaluation plus a penalty term, which - * penalizes unsatisfied constraints. - * - * @param coordinates Coordinates to evaluate function at. - * @return Objective function. - */ - double Evaluate(const arma::mat& coordinates) const; - - /** - * Evaluate the gradient of the Augmented Lagrangian function. - * - * @param coordinates Coordinates to evaluate gradient at. - * @param gradient Matrix to store gradient into. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const; - - /** - * Get the initial point of the optimization (supplied by the - * LagrangianFunction). - * - * @return Initial point. - */ - const arma::mat& GetInitialPoint() const; - - //! Get the Lagrange multipliers. - const arma::vec& Lambda() const { return lambda; } - //! Modify the Lagrange multipliers. - arma::vec& Lambda() { return lambda; } - - //! Get sigma (the penalty parameter). - double Sigma() const { return sigma; } - //! Modify sigma (the penalty parameter). - double& Sigma() { return sigma; } - - //! Get the Lagrangian function. - const LagrangianFunction& Function() const { return function; } - //! Modify the Lagrangian function. - LagrangianFunction& Function() { return function; } - - private: - //! Instantiation of the function to be optimized. - LagrangianFunction& function; - - //! The Lagrange multipliers. - arma::vec lambda; - //! The penalty parameter. - double sigma; -}; - -} // namespace optimization -} // namespace mlpack - -// Include basic implementation. -#include "aug_lagrangian_function_impl.hpp" - -#endif // MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_FUNCTION_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_function_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_function_impl.hpp deleted file mode 100644 index 98105bdd8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_function_impl.hpp +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file aug_lagrangian_function_impl.hpp - * @author Ryan Curtin - * - * Simple, naive implementation of AugLagrangianFunction. Better - * specializations can probably be given in many cases, but this is the most - * general case. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_FUNCTION_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_FUNCTION_IMPL_HPP - -// In case it hasn't been included. -#include "aug_lagrangian_function.hpp" - -namespace mlpack { -namespace optimization { - -// Initialize the AugLagrangianFunction. -template -AugLagrangianFunction::AugLagrangianFunction( - LagrangianFunction& function) : - function(function), - lambda(function.NumConstraints()), - sigma(10) -{ - // Initialize lambda vector to all zeroes. - lambda.zeros(); -} - -// Initialize the AugLagrangianFunction. -template -AugLagrangianFunction::AugLagrangianFunction( - LagrangianFunction& function, - const arma::vec& lambda, - const double sigma) : - function(function), - lambda(lambda), - sigma(sigma) -{ - // Nothing else to do. -} - -// Evaluate the AugLagrangianFunction at the given coordinates. -template -double AugLagrangianFunction::Evaluate( - const arma::mat& coordinates) const -{ - // The augmented Lagrangian is evaluated as - // f(x) + {-lambda_i * c_i(x) + (sigma / 2) c_i(x)^2} for all constraints - - // First get the function's objective value. - double objective = function.Evaluate(coordinates); - - // Now loop for each constraint. - for (size_t i = 0; i < function.NumConstraints(); ++i) - { - double constraint = function.EvaluateConstraint(i, coordinates); - - objective += (-lambda[i] * constraint) + - sigma * std::pow(constraint, 2) / 2; - } - - return objective; -} - -// Evaluate the gradient of the AugLagrangianFunction at the given coordinates. -template -void AugLagrangianFunction::Gradient( - const arma::mat& coordinates, - arma::mat& gradient) const -{ - // The augmented Lagrangian's gradient is evaluted as - // f'(x) + {(-lambda_i + sigma * c_i(x)) * c'_i(x)} for all constraints - gradient.zeros(); - function.Gradient(coordinates, gradient); - - arma::mat constraintGradient; // Temporary for constraint gradients. - for (size_t i = 0; i < function.NumConstraints(); i++) - { - function.GradientConstraint(i, coordinates, constraintGradient); - - // Now calculate scaling factor and add to existing gradient. - arma::mat tmpGradient; - tmpGradient = (-lambda[i] + sigma * - function.EvaluateConstraint(i, coordinates)) * constraintGradient; - gradient += tmpGradient; - } -} - -// Get the initial point. -template -const arma::mat& AugLagrangianFunction::GetInitialPoint() - const -{ - return function.GetInitialPoint(); -} - -} // namespace optimization -} // namespace mlpack - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_impl.hpp deleted file mode 100644 index 774137008..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_impl.hpp +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @file aug_lagrangian_impl.hpp - * @author Ryan Curtin - * - * Implementation of AugLagrangian class (Augmented Lagrangian optimization - * method). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_IMPL_HPP - -#include -#include -#include "aug_lagrangian_function.hpp" - -namespace mlpack { -namespace optimization { - -template -bool AugLagrangian::Optimize(LagrangianFunctionType& function, - arma::mat& coordinates, - const arma::vec& initLambda, - const double initSigma, - const size_t maxIterations) -{ - lambda = initLambda; - sigma = initSigma; - - AugLagrangianFunction augfunc(function, - lambda, sigma); - - return Optimize(augfunc, coordinates, maxIterations); -} - -template -bool AugLagrangian::Optimize(LagrangianFunctionType& function, - arma::mat& coordinates, - const size_t maxIterations) -{ - // If the user did not specify the right size for sigma and lambda, we will - // use defaults. - if (!lambda.is_empty()) - { - AugLagrangianFunction augfunc(function, lambda, - sigma); - return Optimize(augfunc, coordinates, maxIterations); - } - else - { - AugLagrangianFunction augfunc(function); - return Optimize(augfunc, coordinates, maxIterations); - } -} - -template -bool AugLagrangian::Optimize( - AugLagrangianFunction& augfunc, - arma::mat& coordinates, - const size_t maxIterations) -{ - traits::CheckConstrainedFunctionTypeAPI(); - - LagrangianFunctionType& function = augfunc.Function(); - - // Ensure that we update lambda immediately. - double penaltyThreshold = DBL_MAX; - - // Track the last objective to compare for convergence. - double lastObjective = function.Evaluate(coordinates); - - // Then, calculate the current penalty. - double penalty = 0; - for (size_t i = 0; i < function.NumConstraints(); i++) - penalty += std::pow(function.EvaluateConstraint(i, coordinates), 2); - - Log::Debug << "Penalty is " << penalty << " (threshold " << penaltyThreshold - << ")." << std::endl; - - // The odd comparison allows user to pass maxIterations = 0 (i.e. no limit on - // number of iterations). - size_t it; - for (it = 0; it != (maxIterations - 1); it++) - { - Log::Info << "AugLagrangian on iteration " << it - << ", starting with objective " << lastObjective << "." << std::endl; - - if (!lbfgs.Optimize(augfunc, coordinates)) - Log::Info << "L-BFGS reported an error during optimization." - << std::endl; - - // Check if we are done with the entire optimization (the threshold we are - // comparing with is arbitrary). - if (std::abs(lastObjective - function.Evaluate(coordinates)) < 1e-10 && - augfunc.Sigma() > 500000) - { - lambda = std::move(augfunc.Lambda()); - sigma = augfunc.Sigma(); - return true; - } - - lastObjective = function.Evaluate(coordinates); - - // Assuming that the optimization has converged to a new set of coordinates, - // we now update either lambda or sigma. We update sigma if the penalty - // term is too high, and we update lambda otherwise. - - // First, calculate the current penalty. - double penalty = 0; - for (size_t i = 0; i < function.NumConstraints(); i++) - { - penalty += std::pow(function.EvaluateConstraint(i, coordinates), 2); - } - - Log::Info << "Penalty is " << penalty << " (threshold " - << penaltyThreshold << ")." << std::endl; - - if (penalty < penaltyThreshold) // We update lambda. - { - // We use the update: lambda_{k + 1} = lambda_k - sigma * c(coordinates), - // but we have to write a loop to do this for each constraint. - for (size_t i = 0; i < function.NumConstraints(); i++) - augfunc.Lambda()[i] -= augfunc.Sigma() * - function.EvaluateConstraint(i, coordinates); - - // We also update the penalty threshold to be a factor of the current - // penalty. TODO: this factor should be a parameter (from CLI). The - // value of 0.25 is taken from Burer and Monteiro (2002). - penaltyThreshold = 0.25 * penalty; - Log::Info << "Lagrange multiplier estimates updated." << std::endl; - } - else - { - // We multiply sigma by a constant value. TODO: this factor should be a - // parameter (from CLI). The value of 10 is taken from Burer and Monteiro - // (2002). - augfunc.Sigma() *= 10; - Log::Info << "Updated sigma to " << augfunc.Sigma() << "." << std::endl; - } - } - - return false; -} - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_AUG_LAGRANGIAN_IMPL_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_test_functions.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_test_functions.hpp deleted file mode 100644 index 9e9e4a028..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/aug_lagrangian/aug_lagrangian_test_functions.hpp +++ /dev/null @@ -1,143 +0,0 @@ -/** - * @file aug_lagrangian_test_functions.hpp - * @author Ryan Curtin - * - * Define test functions for the augmented Lagrangian method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_TEST_FUNCTIONS_HPP -#define MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_TEST_FUNCTIONS_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * This function is taken from "Practical Mathematical Optimization" (Snyman), - * section 5.3.8 ("Application of the Augmented Lagrangian Method"). It has - * only one constraint. - * - * The minimum that satisfies the constraint is x = [1, 4], with an objective - * value of 70. - */ -class AugLagrangianTestFunction -{ - public: - AugLagrangianTestFunction(); - AugLagrangianTestFunction(const arma::mat& initial_point); - - double Evaluate(const arma::mat& coordinates); - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - - size_t NumConstraints() const { return 1; } - - double EvaluateConstraint(const size_t index, const arma::mat& coordinates); - void GradientConstraint(const size_t index, - const arma::mat& coordinates, - arma::mat& gradient); - - const arma::mat& GetInitialPoint() const { return initialPoint; } - - private: - arma::mat initialPoint; -}; - -/** - * This function is taken from M. Gockenbach's lectures on general nonlinear - * programs, found at: - * http://www.math.mtu.edu/~msgocken/ma5630spring2003/lectures/nlp/nlp.pdf - * - * The program we are using is example 2.5 from this document. - * I have arbitrarily decided that this will be called the Gockenbach function. - * - * The minimum that satisfies the two constraints is given as - * x = [0.12288, -1.1078, 0.015100], with an objective value of about 29.634. - */ -class GockenbachFunction -{ - public: - GockenbachFunction(); - GockenbachFunction(const arma::mat& initial_point); - - double Evaluate(const arma::mat& coordinates); - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - - size_t NumConstraints() const { return 2; } - - double EvaluateConstraint(const size_t index, const arma::mat& coordinates); - void GradientConstraint(const size_t index, - const arma::mat& coordinates, - arma::mat& gradient); - - const arma::mat& GetInitialPoint() const { return initialPoint; } - - private: - arma::mat initialPoint; -}; - -/** - * This function is the Lovasz-Theta semidefinite program, as implemented in the - * following paper: - * - * S. Burer, R. Monteiro - * "A nonlinear programming algorithm for solving semidefinite programs via - * low-rank factorization." - * Journal of Mathematical Programming, 2004 - * - * Given a simple, undirected graph G = (V, E), the Lovasz-Theta SDP is defined - * by: - * - * min_X{Tr(-(e e^T)^T X) : Tr(X) = 1, X_ij = 0 for all (i, j) in E, X >= 0} - * - * where e is the vector of all ones and X has dimension |V| x |V|. - * - * In the Monteiro-Burer formulation, we take X = R * R^T, where R is the - * coordinates given to the Evaluate(), Gradient(), EvaluateConstraint(), and - * GradientConstraint() functions. - */ -class LovaszThetaSDP -{ - public: - LovaszThetaSDP(); - - /** - * Initialize the Lovasz-Theta SDP with the given set of edges. The edge - * matrix should consist of rows of two dimensions, where dimension 0 is the - * first vertex of the edge and dimension 1 is the second edge (or vice versa, - * as it doesn't make a difference). - * - * @param edges Matrix of edges. - */ - LovaszThetaSDP(const arma::mat& edges); - - double Evaluate(const arma::mat& coordinates); - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - - size_t NumConstraints() const; - - double EvaluateConstraint(const size_t index, const arma::mat& coordinates); - void GradientConstraint(const size_t index, - const arma::mat& coordinates, - arma::mat& gradient); - - const arma::mat& GetInitialPoint(); - - const arma::mat& Edges() const { return edges; } - arma::mat& Edges() { return edges; } - - private: - arma::mat edges; - size_t vertices; - - arma::mat initialPoint; -}; - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_AUG_LAGRANGIAN_TEST_FUNCTIONS_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/adaptive_stepsize.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/adaptive_stepsize.hpp deleted file mode 100644 index fbddc5565..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/adaptive_stepsize.hpp +++ /dev/null @@ -1,173 +0,0 @@ -/** - * @file adaptive_stepsize.hpp - * @author Marcus Edel - * - * Definition of the adaptive stepsize technique as described in: - * "Big Batch SGD: Automated Inference using Adaptive Batch Sizes" by - * S. De et al. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_ADAPTIVE_STEPSIZE_HPP -#define MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_ADAPTIVE_STEPSIZE_HPP - -namespace mlpack { -namespace optimization { - -/** - * Definition of the adaptive stepize technique, a non-monotonic stepsize scheme - * that uses curvature estimates to propose new stepsize choices. - * direction. - * - * For more information, please refer to: - * - * @code - * @article{De2017, - * title = {Big Batch {SGD:} Automated Inference using Adaptive Batch - * Sizes}, - * author = {Soham De and Abhay Kumar Yadav and David W. Jacobs and - Tom Goldstein}, - * journal = {CoRR}, - * year = {2017}, - * url = {http://arxiv.org/abs/1610.05792}, - * } - * @endcode - */ -class AdaptiveStepsize -{ - public: - /** - * Construct the AdaptiveStepsize object with the given function and - * parameters. The defaults here are not necessarily good for the given - * problem, so it is suggested that the values used be tailored to the task at - * hand. - * - * @param backtrackStepSize The backtracking step size for each iteration. - * @param searchParameter The backtracking search parameter for each - * iteration. - */ - AdaptiveStepsize(const double backtrackStepSize = 0.1, - const double searchParameter = 0.1) : - backtrackStepSize(backtrackStepSize), - searchParameter(searchParameter) - { /* Nothing to do here. */ } - - /** - * This function is called in each iteration. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to be optimized (minimized). - * @param stepSize Step size to be used for the given iteration. - * @param iterate Parameters that minimize the function. - * @param gradient The gradient matrix. - * @param gradientNorm The gradient norm to be used for the given iteration. - * @param offset The batch offset to be used for the given iteration. - * @param batchSize Batch size to be used for the given iteration. - * @param backtrackingBatchSize Backtracking batch size to be used for the - * given iteration. - * @param reset Reset the step size decay parameter. - */ - template - void Update(DecomposableFunctionType& function, - double& stepSize, - arma::mat& iterate, - const arma::mat& gradient, - const double gradientNorm, - const double sampleVariance, - const size_t offset, - const size_t batchSize, - const size_t backtrackingBatchSize, - const bool /* reset */) - { - Backtracking(function, stepSize, iterate, gradient, gradientNorm, offset, - backtrackingBatchSize); - - // Update the iterate. - iterate -= stepSize * gradient; - - double stepSizeDecay = 0; - if (batchSize < function.NumFunctions()) - { - stepSizeDecay = (1 - (1 / ((double) batchSize - 1) * sampleVariance) / - (batchSize * gradientNorm)) / batchSize; - } - else - { - stepSizeDecay = 1 / function.NumFunctions(); - } - - // Stepsize smoothing. - stepSize *= (1 - ((double) batchSize / function.NumFunctions())); - stepSize += stepSizeDecay * ((double) batchSize / function.NumFunctions()); - - Backtracking(function, stepSize, iterate, gradient, gradientNorm, offset, - backtrackingBatchSize); - } - - //! Get the backtracking step size. - double BacktrackStepSize() const { return backtrackStepSize; } - //! Modify the backtracking step size. - double& BacktrackStepSize() { return backtrackStepSize; } - - //! Get the search parameter. - double SearchParameter() const { return searchParameter; } - //! Modify the search parameter. - double& SearchParameter() { return searchParameter; } - - private: - /** - * Definition of the backtracking line search algorithm based on the - * Armijo–Goldstein condition to determine the maximum amount to move along - * the given search direction. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to be optimized (minimized). - * @param stepSize Step size to be used for the given iteration. - * @param iterate Parameters that minimize the function. - * @param gradient The gradient matrix. - * @param gradientNorm The gradient norm to be used for the given iteration. - * @param offset The batch offset to be used for the given iteration. - * @param backtrackingBatchSize The backtracking batch size. - */ - template - void Backtracking(DecomposableFunctionType& function, - double& stepSize, - const arma::mat& iterate, - const arma::mat& gradient, - const double gradientNorm, - const size_t offset, - const size_t backtrackingBatchSize) - { - double overallObjective = function.Evaluate(iterate, offset, - backtrackingBatchSize); - - arma::mat iterateUpdate = iterate - (stepSize * gradient); - double overallObjectiveUpdate = function.Evaluate(iterateUpdate, offset, - backtrackingBatchSize); - - while (overallObjectiveUpdate > - (overallObjective + searchParameter * stepSize * gradientNorm)) - { - stepSize *= backtrackStepSize; - - iterateUpdate = iterate - (stepSize * gradient); - overallObjectiveUpdate = function.Evaluate(iterateUpdate, offset, - backtrackingBatchSize); - } - } - - //! The backtracking step size for each iteration. - double backtrackStepSize; - - //! The search parameter for each iteration. - double searchParameter; -}; - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_ADAPTIVE_STEPSIZE_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/backtracking_line_search.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/backtracking_line_search.hpp deleted file mode 100644 index 3d8f1fc19..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/backtracking_line_search.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file backtracking_line_search.hpp - * @author Marcus Edel - * - * Definition of the backtracking line search technique as described in: - * "Big Batch SGD: Automated Inference using Adaptive Batch Sizes" by - * S. De et al. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BACKTRACKING_LINE_SEARCH_HPP -#define MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BACKTRACKING_LINE_SEARCH_HPP - -namespace mlpack { -namespace optimization { - -/** - * Definition of the backtracking line search algorithm based on the - * Armijo–Goldstein condition to determine the maximum amount to move along the - * given search direction. - * - * For more information, please refer to: - * - * @code - * @article{De2017, - * title = {Big Batch {SGD:} Automated Inference using Adaptive Batch - * Sizes}, - * author = {Soham De and Abhay Kumar Yadav and David W. Jacobs and - Tom Goldstein}, - * journal = {CoRR}, - * year = {2017}, - * url = {http://arxiv.org/abs/1610.05792}, - * } - * @endcode - */ -class BacktrackingLineSearch -{ - public: - /** - * Construct the BacktrackingLineSearch object with the given function and - * parameters. The defaults here are not necessarily good for the given - * problem, so it is suggested that the values used be tailored to the task at - * hand. - * - * @param function Function to be optimized (minimized). - */ - BacktrackingLineSearch(const double searchParameter = 0.1) : - searchParameter(searchParameter) - { /* Nothing to do here. */ } - - /** - * This function is called in each iteration. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to be optimized (minimized). - * @param stepSize Step size to be used for the given iteration. - * @param iterate Parameters that minimize the function. - * @param gradient The gradient matrix. - * @param gradientNorm The gradient norm to be used for the given iteration. - * @param offset The batch offset to be used for the given iteration. - * @param batchSize Batch size to be used for the given iteration. - * @param backtrackingBatchSize Backtracking batch size to be used for the - * given iteration. - * @param reset Reset the step size decay parameter. - */ - template - void Update(DecomposableFunctionType& function, - double& stepSize, - arma::mat& iterate, - const arma::mat& gradient, - const double gradientNorm, - const double /* sampleVariance */, - const size_t offset, - const size_t /* batchSize */, - const size_t backtrackingBatchSize, - const bool reset) - { - if (reset) - stepSize *= 2; - - double overallObjective = function.Evaluate(iterate, offset, - backtrackingBatchSize); - - arma::mat iterateUpdate = iterate - (stepSize * gradient); - double overallObjectiveUpdate = function.Evaluate(iterateUpdate, - offset, backtrackingBatchSize); - - while (overallObjectiveUpdate > - (overallObjective + searchParameter * stepSize * gradientNorm)) - { - stepSize /= 2; - - iterateUpdate = iterate - (stepSize * gradient); - overallObjectiveUpdate = function.Evaluate(iterateUpdate, - offset, backtrackingBatchSize); - } - } - - private: - //! The search parameter for each iteration. - double searchParameter; -}; - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BACKTRACKING_LINE_SEARCH_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd.hpp deleted file mode 100644 index f5aeec8be..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd.hpp +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @file bigbatch_sgd.hpp - * @author Marcus Edel - * - * Definition of Big-batch Stochastic Gradient Descent (BBSGD) as described in: - * "Big Batch SGD: Automated Inference using Adaptive Batch Sizes" - * by Soham De et al. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BIGBATCH_SGD_HPP -#define MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BIGBATCH_SGD_HPP - -#include - -#include "adaptive_stepsize.hpp" -#include "backtracking_line_search.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Big-batch Stochastic Gradient Descent is a technique for minimizing a - * function which can be expressed as a sum of other functions. That is, - * suppose we have - * - * \f[ - * f(A) = \sum_{i = 0}^{n} f_i(A) - * \f] - * - * and our task is to minimize \f$ A \f$. Big-batch SGD iterates over batches - * of functions \f$ \{ f_{i0}(A), f_{i1}(A), \ldots, f_{i(m - 1)}(A) \f$ for - * some batch size \f$ m \f$, producing the following update scheme: - * - * \f[ - * A_{j + 1} = A_j + \alpha \left(\sum_{k = 0}^{m - 1} \nabla f_{ik}(A) \right) - * \f] - * - * where \f$ \alpha \f$ is a parameter which specifies the step size. Each - * big-batch is passed through either sequentially or randomly. The algorithm - * continues until \f$ j \f$ reaches the maximum number of iterations---or when - * a full sequence of updates through each of the big-batches produces an - * improvement within a certain tolerance \f$ \epsilon \f$. - * - * The parameter \f$ \epsilon \f$ is specified by the tolerance parameter tot he - * constructor, as is the maximum number of iterations specified by the - * maxIterations parameter. - * - * This class is useful for data-dependent functions whose objective function - * can be expressed as a sum of objective functions operating on an individual - * point. Then, big-batch SGD considers the gradient of the objective function - * operation on an individual big-batch of points in its update of \f$ A \f$. - * - * For more information, please refer to: - * - * @code - * @article{De2017, - * title = {Big Batch {SGD:} Automated Inference using Adaptive Batch - * Sizes}, - * author = {Soham De and Abhay Kumar Yadav and David W. Jacobs and - Tom Goldstein}, - * journal = {CoRR}, - * year = {2017}, - * url = {http://arxiv.org/abs/1610.05792}, - * } - * @endcode - * - * For big-batch SGD to work, a DecomposableFunctionType template parameter is - * required. - * This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, const size_t i); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient); - * - * NumFunctions() should return the number of functions, and in the other two - * functions, the parameter i refers to which individual function (or gradient) - * is being evaluated. So, for the case of a data-dependent function, such as - * NCA (see mlpack::nca::NCA), NumFunctions() should return the number of points - * in the dataset, and Evaluate(coordinates, 0) will evaluate the objective - * function on the first point in the dataset (presumably, the dataset is held - * internally in the DecomposableFunctionType). - * - * @tparam UpdatePolicyType Update policy used during the iterative update - * process. By default the AdaptiveStepsize update policy is used. - */ -template -class BigBatchSGD -{ - public: - /** - * Construct the BigBatchSGD optimizer with the given function and - * parameters. The defaults here are not necessarily good for the given - * problem, so it is suggested that the values used be tailored for the task - * at hand. The maximum number of iterations refers to the maximum number of - * batches that are processed. - * - * @param batchSize Initial batch size. - * @param stepSize Step size for each iteration. - * @param batchDelta Factor for the batch update step. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the batch order is shuffled; otherwise, each - * batch is visited in linear order. - */ - BigBatchSGD(const size_t batchSize = 1000, - const double stepSize = 0.01, - const double batchDelta = 0.1, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true); - /** - * Optimize the given function using big-batch SGD. The given starting point - * will be modified to store the finishing point of the algorithm, and the - * final objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, - arma::mat& iterate); - - //! Get the batch size. - size_t BatchSize() const { return batchSize; } - //! Modify the batch size. - size_t& BatchSize() { return batchSize; } - - //! Get the step size. - double StepSize() const { return stepSize; } - //! Modify the step size. - double& StepSize() { return stepSize; } - - //! Get the batch delta. - double BatchDelta() const { return batchDelta; } - //! Modify the batch delta. - double& BatchDelta() { return batchDelta; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return shuffle; } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return shuffle; } - - //! Get the update policy. - UpdatePolicyType UpdatePolicy() const { return updatePolicy; } - //! Modify the update policy. - UpdatePolicyType& UpdatePolicy() { return updatePolicy; } - - private: - //! The size of the current batch. - size_t batchSize; - - //! The step size for each example. - double stepSize; - - //! The factor for the batch update step. - double batchDelta; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The tolerance for termination. - double tolerance; - - //! Controls whether or not the individual functions are shuffled when - //! iterating. - bool shuffle; - - //! The update policy used to update the parameters in each iteration. - UpdatePolicyType updatePolicy; -}; - -using BBS_Armijo = BigBatchSGD; -using BBS_BB = BigBatchSGD; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "bigbatch_sgd_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd_impl.hpp deleted file mode 100644 index 4375e580c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/bigbatch_sgd/bigbatch_sgd_impl.hpp +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @file bigbatch_sgd_impl.hpp - * @author Marcus Edel - * - * Implementation of big-batch SGD. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BIGBATCH_SGD_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_BIGBATCH_SGD_BIGBATCH_SGD_IMPL_HPP - -// In case it hasn't been included yet. -#include "bigbatch_sgd.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -BigBatchSGD::BigBatchSGD( - const size_t batchSize, - const double stepSize, - const double batchDelta, - const size_t maxIterations, - const double tolerance, - const bool shuffle) : - batchSize(batchSize), - stepSize(stepSize), - batchDelta(batchDelta), - maxIterations(maxIterations), - tolerance(tolerance), - shuffle(shuffle), - updatePolicy(UpdatePolicyType()) -{ /* Nothing to do. */ } - -//! Optimize the function (minimize). -template -template -double BigBatchSGD::Optimize( - DecomposableFunctionType& function, arma::mat& iterate) -{ - typedef Function FullFunctionType; - FullFunctionType& f(static_cast(function)); - - // Make sure we have all the methods that we need. - traits::CheckDecomposableFunctionTypeAPI(); - - - // Find the number of functions to use. - const size_t numFunctions = f.NumFunctions(); - - // To keep track of where we are and how things are going. - size_t currentFunction = 0; - double overallObjective = 0; - double lastObjective = DBL_MAX; - bool reset = false; - arma::mat delta0, delta1; - - // Now iterate! - arma::mat gradient(iterate.n_rows, iterate.n_cols); - arma::mat functionGradient(iterate.n_rows, iterate.n_cols); - const size_t actualMaxIterations = (maxIterations == 0) ? - std::numeric_limits::max() : maxIterations; - for (size_t i = 0; i < actualMaxIterations; /* incrementing done manually */) - { - // Is this iteration the start of a sequence? - if ((currentFunction % numFunctions) == 0 && i > 0) - { - // Output current objective function. - Log::Info << "Big-batch SGD: iteration " << i << ", objective " - << overallObjective << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "Big-batch SGD: converged to " << overallObjective - << "; terminating with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "Big-batch SGD: minimized within tolerance " << tolerance - << "; terminating optimization." << std::endl; - return overallObjective; - } - - // Reset the counter variables. - lastObjective = overallObjective; - overallObjective = 0; - currentFunction = 0; - - if (shuffle) // Determine order of visitation. - f.Shuffle(); - } - - // Find the effective batch size; we have to take the minimum of three - // things: - // - the batch size can't be larger than the user-specified batch size; - // - the batch size can't be larger than the number of iterations left - // before actualMaxIterations is hit; - // - the batch size can't be larger than the number of functions left. - size_t effectiveBatchSize = std::min( - std::min(batchSize, actualMaxIterations - i), - numFunctions - currentFunction); - - size_t k = 1; - double vB = 0; - - // Compute the stochastic gradient estimation. - f.Gradient(iterate, currentFunction, gradient, 1); - - delta1 = gradient; - for (size_t j = 1; j < effectiveBatchSize; ++j, ++k) - { - f.Gradient(iterate, currentFunction + j, functionGradient, 1); - delta0 = delta1 + (functionGradient - delta1) / k; - - // Compute sample variance. - vB += arma::norm(functionGradient - delta1, 2.0) * - arma::norm(functionGradient - delta0, 2.0); - - delta1 = delta0; - gradient += functionGradient; - } - double gB = std::pow(arma::norm(gradient / effectiveBatchSize, 2), 2.0); - - // Reset the batch size update process counter. - reset = false; - - // Increase batchSize only if there are more samples left. - if (effectiveBatchSize == batchSize) - { - // Update batch size. - while (gB <= ((1 / ((double) batchSize - 1) * vB) / batchSize)) - { - // Increase batch size at least by one. - size_t batchOffset = batchDelta * batchSize; - if (batchOffset <= 0) - batchOffset = 1; - - if ((currentFunction + batchSize + batchOffset) >= numFunctions) - break; - - // Update the stochastic gradient estimation. - const size_t batchStart = (currentFunction + batchSize + batchOffset - - 1) < numFunctions ? currentFunction + batchSize - 1 : 0; - for (size_t j = 0; j < batchOffset; ++j, ++k) - { - f.Gradient(iterate, batchStart + j, functionGradient, 1); - delta0 = delta1 + (functionGradient - delta1) / (k + 1); - - // Compute sample variance. - vB += arma::norm(functionGradient - delta1, 2.0) * - arma::norm(functionGradient - delta0, 2.0); - - delta1 = delta0; - gradient += functionGradient; - } - gB = std::pow(arma::norm(gradient / (batchSize + batchOffset), 2), 2.0); - - // Update the batchSize. - batchSize += batchOffset; - effectiveBatchSize += batchOffset; - - // Batch size updated. - reset = true; - } - } - - updatePolicy.Update(f, stepSize, iterate, gradient, gB, vB, - currentFunction, batchSize, effectiveBatchSize, reset); - - // Update the iterate. - iterate -= stepSize * gradient; - - overallObjective += f.Evaluate(iterate, currentFunction, - effectiveBatchSize); - - i += effectiveBatchSize; - currentFunction += effectiveBatchSize; - } - - Log::Info << "Big-batch SGD: maximum iterations (" << maxIterations << ") " - << "reached; terminating optimization." << std::endl; - - // Calculate final objective. - overallObjective = 0; - for (size_t i = 0; i < numFunctions; i += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - i); - overallObjective += f.Evaluate(iterate, i, effectiveBatchSize); - } - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/cmaes.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/cmaes.hpp deleted file mode 100644 index c8ec8f8f3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/cmaes.hpp +++ /dev/null @@ -1,178 +0,0 @@ -/** - * @file cmaes.hpp - * @author Marcus Edel - * @author Kartik Nighania - * - * Definition of the Covariance Matrix Adaptation Evolution Strategy as proposed - * by N. Hansen et al. in "Completely Derandomized Self-Adaptation in Evolution - * Strategies". - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_CMAES_CMAES_HPP -#define MLPACK_CORE_OPTIMIZERS_CMAES_CMAES_HPP - -#include - -#include "full_selection.hpp" -#include "random_selection.hpp" - -namespace mlpack { -namespace optimization { - -/** - * CMA-ES - Covariance Matrix Adaptation Evolution Strategy is s a stochastic - * search algorithm. CMA-ES is a second order approach estimating a positive - * definite matrix within an iterative procedure using the covariance matrix. - * - * For more information, please refer to: - * - * @code - * @article{Hansen2001 - * author = {Hansen, Nikolaus and Ostermeier, Andreas}, - * title = {Completely Derandomized Self-Adaptation in Evolution - * Strategies}, - * journal = {Evol. Comput.}, - * volume = {9}, - * number = {2}, - * year = {2001}, - * pages = {159--195}, - * publisher = {MIT Press}, - * } - * @endcode - * - * For CMA-ES to work, the class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, const size_t i); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - * - * @tparam SelectionPolicy The selection strategy used for the evaluation step. - */ -template -class CMAES -{ - public: - /** - * Construct the CMA-ES optimizer with the given function and parameters. The - * defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param lambda The population size (0 use the default size). - * @param lowerBound Lower bound of decision variables. - * @param upperBound Upper bound of decision variables. - * @param batchSize Batch size to use for the objective calculation. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param selectionPolicy Instantiated selection policy used to calculate the - * objective. - */ - CMAES(const size_t lambda = 0, - const double lowerBound = -10, - const double upperBound = 10, - const size_t batchSize = 32, - const size_t maxIterations = 1000, - const double tolerance = 1e-5, - const SelectionPolicyType& selectionPolicy = SelectionPolicyType()); - - /** - * Optimize the given function using CMA-ES. The given starting point will be - * modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the step size. - size_t PopulationSize() const { return lambda; } - //! Modify the step size. - size_t& PopulationSize() { return lambda; } - - //! Get the lower bound of decision variables. - double LowerBound() const { return lowerBound; } - //! Modify the lower bound of decision variables. - double& LowerBound() { return lowerBound; } - - //! Get the upper bound of decision variables - double UpperBound() const { return upperBound; } - //! Modify the upper bound of decision variables - double& UpperBound() { return upperBound; } - - //! Get the batch size. - size_t BatchSize() const { return batchSize; } - //! Modify the batch size. - size_t& BatchSize() { return batchSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get the selection policy. - const SelectionPolicyType& SelectionPolicy() const { return selectionPolicy; } - //! Modify the selection policy. - SelectionPolicyType& SelectionPolicy() { return selectionPolicy; } - - private: - //! Population size. - size_t lambda; - - //! Lower bound of decision variables. - double lowerBound; - - //! Upper bound of decision variables - double upperBound; - - //! The batch size for processing. - size_t batchSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The tolerance for termination. - double tolerance; - - //! The selection policy used to calculate the objective. - SelectionPolicyType selectionPolicy; -}; - -/** - * Convenient typedef for CMAES approximation. - */ -template -using ApproxCMAES = CMAES; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "cmaes_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/cmaes_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/cmaes_impl.hpp deleted file mode 100644 index 8a726ce71..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/cmaes_impl.hpp +++ /dev/null @@ -1,286 +0,0 @@ -/** - * @file cmaes_impl.hpp - * @author Marcus Edel - * @author Kartik Nighania - * - * Implementation of the Covariance Matrix Adaptation Evolution Strategy as - * proposed by N. Hansen et al. in "Completely Derandomized Self-Adaptation in - * Evolution Strategies". - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_CMAES_CMAES_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_CMAES_CMAES_IMPL_HPP - -// In case it hasn't been included yet. -#include "cmaes.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -CMAES::CMAES(const size_t lambda, - const double lowerBound, - const double upperBound, - const size_t batchSize, - const size_t maxIterations, - const double tolerance, - const SelectionPolicyType& selectionPolicy) : - lambda(lambda), - lowerBound(lowerBound), - upperBound(upperBound), - batchSize(batchSize), - maxIterations(maxIterations), - tolerance(tolerance), - selectionPolicy(selectionPolicy) -{ /* Nothing to do. */ } - -//! Optimize the function (minimize). -template -template -double CMAES::Optimize( - DecomposableFunctionType& function, arma::mat& iterate) -{ - // Make sure that we have the methods that we need. Long name... - traits::CheckNonDifferentiableDecomposableFunctionTypeAPI< - DecomposableFunctionType>(); - - // Find the number of functions to use. - const size_t numFunctions = function.NumFunctions(); - - // Population size. - if (lambda == 0) - lambda = (4 + std::round(3 * std::log(iterate.n_elem))) * 10; - - // Parent weights. - const size_t mu = std::round(lambda / 2); - arma::vec w = std::log(mu + 0.5) - arma::log( - arma::linspace(0, mu - 1, mu) + 1.0); - w /= arma::sum(w); - - // Number of effective solutions. - const double muEffective = 1 / arma::accu(arma::pow(w, 2)); - - // Step size control parameters. - arma::vec sigma(3); - sigma(0) = 0.3 * (upperBound - lowerBound); - const double cs = (muEffective + 2) / (iterate.n_elem + muEffective + 5); - const double ds = 1 + cs + 2 * std::max(std::sqrt((muEffective - 1) / - (iterate.n_elem + 1)) - 1, 0.0); - const double enn = std::sqrt(iterate.n_elem) * (1.0 - 1.0 / - (4.0 * iterate.n_elem) + 1.0 / (21 * std::pow(iterate.n_elem, 2))); - - // Covariance update parameters. - // Cumulation for distribution. - const double cc = (4 + muEffective / iterate.n_elem) / - (4 + iterate.n_elem + 2 * muEffective / iterate.n_elem); - const double h = (1.4 + 2.0 / (iterate.n_elem + 1.0)) * enn; - - const double c1 = 2 / (std::pow(iterate.n_elem + 1.3, 2) + muEffective); - const double alphaMu = 2; - const double cmu = std::min(1 - c1, alphaMu * (muEffective - 2 + 1 / - muEffective) / (std::pow(iterate.n_elem + 2, 2) + - alphaMu * muEffective / 2)); - - arma::cube mPosition(iterate.n_rows, iterate.n_cols, 3); - mPosition.slice(0) = lowerBound + arma::randu( - iterate.n_rows, iterate.n_cols) * (upperBound - lowerBound); - - arma::mat step = arma::zeros(iterate.n_rows, iterate.n_cols); - - // Calculate the first objective function. - double currentObjective = 0; - for (size_t f = 0; f < numFunctions; f += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - f); - currentObjective += function.Evaluate(mPosition.slice(0), f, - effectiveBatchSize); - } - - double overallObjective = currentObjective; - double lastObjective = DBL_MAX; - - // Population parameters. - arma::cube pStep(iterate.n_rows, iterate.n_cols, lambda); - arma::cube pPosition(iterate.n_rows, iterate.n_cols, lambda); - arma::vec pObjective(lambda); - arma::cube ps = arma::zeros(iterate.n_rows, iterate.n_cols, 2); - arma::cube pc = ps; - arma::cube C(iterate.n_elem, iterate.n_elem, 2); - C.slice(0).eye(); - - // Covariance matrix parameters. - arma::vec eigval; - arma::mat eigvec; - arma::vec eigvalZero = arma::zeros(iterate.n_elem); - - // The current visitation order (sorted by population objectives). - arma::uvec idx = arma::linspace(0, lambda - 1, lambda); - - // Now iterate! - for (size_t i = 1; i < maxIterations; ++i) - { - // To keep track of where we are. - const size_t idx0 = (i - 1) % 2; - const size_t idx1 = i % 2; - - const arma::mat covLower = arma::chol(C.slice(idx0), "lower"); - - for (size_t j = 0; j < lambda; ++j) - { - if (iterate.n_rows > iterate.n_cols) - { - pStep.slice(idx(j)) = covLower * - arma::randn(iterate.n_rows, iterate.n_cols); - } - else - { - pStep.slice(idx(j)) = arma::randn(iterate.n_rows, iterate.n_cols) * - covLower; - } - - pPosition.slice(idx(j)) = mPosition.slice(idx0) + sigma(idx0) * - pStep.slice(idx(j)); - - // Calculate the objective function. - pObjective(idx(j)) = selectionPolicy.Select(function, batchSize, - pPosition.slice(idx(j))); - } - - // Sort population. - idx = sort_index(pObjective); - - step = w(0) * pStep.slice(idx(0)); - for (size_t j = 1; j < mu; ++j) - step += w(j) * pStep.slice(idx(j)); - - mPosition.slice(idx1) = mPosition.slice(idx0) + sigma(idx0) * step; - - // Calculate the objective function. - currentObjective = selectionPolicy.Select(function, batchSize, - mPosition.slice(idx1)); - - // Update best parameters. - if (currentObjective < overallObjective) - { - overallObjective = currentObjective; - iterate = mPosition.slice(idx1); - } - - // Update Step Size. - if (iterate.n_rows > iterate.n_cols) - { - ps.slice(idx1) = (1 - cs) * ps.slice(idx0) + std::sqrt( - cs * (2 - cs) * muEffective) * covLower.t() * step; - } - else - { - ps.slice(idx1) = (1 - cs) * ps.slice(idx0) + std::sqrt( - cs * (2 - cs) * muEffective) * step * covLower.t(); - } - - const double psNorm = arma::norm(ps.slice(idx1)); - sigma(idx1) = sigma(idx0) * std::pow( - std::exp(cs / ds * psNorm / enn - 1), 0.3); - - // Update covariance matrix. - if ((psNorm / sqrt(1 - std::pow(1 - cs, 2 * i))) < h) - { - pc.slice(idx1) = (1 - cc) * pc.slice(idx0) + std::sqrt(cc * (2 - cc) * - muEffective) * step; - - - if (iterate.n_rows > iterate.n_cols) - { - C.slice(idx1) = (1 - c1 - cmu) * C.slice(idx0) + c1 * - (pc.slice(idx1) * pc.slice(idx1).t()); - } - else - { - C.slice(idx1) = (1 - c1 - cmu) * C.slice(idx0) + c1 * - (pc.slice(idx1).t() * pc.slice(idx1)); - } - } - else - { - pc.slice(idx1) = (1 - cc) * pc.slice(idx0); - - if (iterate.n_rows > iterate.n_cols) - { - C.slice(idx1) = (1 - c1 - cmu) * C.slice(idx0) + c1 * (pc.slice(idx1) * - pc.slice(idx1).t() + (cc * (2 - cc)) * C.slice(idx0)); - } - else - { - C.slice(idx1) = (1 - c1 - cmu) * C.slice(idx0) + c1 * - (pc.slice(idx1).t() * pc.slice(idx1) + (cc * (2 - cc)) * - C.slice(idx0)); - } - } - - if (iterate.n_rows > iterate.n_cols) - { - for (size_t j = 0; j < mu; ++j) - { - C.slice(idx1) = C.slice(idx1) + cmu * w(j) * - pStep.slice(idx(j)) * pStep.slice(idx(j)).t(); - } - } - else - { - for (size_t j = 0; j < mu; ++j) - { - C.slice(idx1) = C.slice(idx1) + cmu * w(j) * - pStep.slice(idx(j)).t() * pStep.slice(idx(j)); - } - } - - arma::eig_sym(eigval, eigvec, C.slice(idx1)); - const arma::uvec negativeEigval = find(eigval < 0, 1); - if (!negativeEigval.is_empty()) - { - if (negativeEigval(0) == 0) - { - C.slice(idx1).zeros(); - } - else - { - C.slice(idx1) = eigvec.cols(0, negativeEigval(0) - 1) * - arma::diagmat(eigval.subvec(0, negativeEigval(0) - 1)) * - eigvec.cols(0, negativeEigval(0) - 1).t(); - } - } - - // Output current objective function. - Log::Info << "CMA-ES: iteration " << i << ", objective " << overallObjective - << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "CMA-ES: converged to " << overallObjective << "; " - << "terminating with failure. Try a smaller step size?" << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "CMA-ES: minimized within tolerance " << tolerance << "; " - << "terminating optimization." << std::endl; - return overallObjective; - } - - lastObjective = overallObjective; - } - - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/full_selection.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/full_selection.hpp deleted file mode 100644 index 162f570bd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/full_selection.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @file full_selection.hpp - * @author Marcus Edel - * - * Select the full dataset for use in the Evaluation step. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_CMAES_FULL_SELECTION_HPP -#define MLPACK_CORE_OPTIMIZERS_CMAES_FULL_SELECTION_HPP - -#include - -namespace mlpack { -namespace optimization { - -/* - * Select the full dataset for use in the Evaluation step. - */ -class FullSelection -{ - public: - /** - * Select the full dataset to calculate the objective function. - * - * @tparam DecomposableFunctionType Type of the function to be evaluated. - * @param function Function to optimize. - * @param batchSize Batch size to use for each step. - * @param iterate starting point. - */ - template - double Select(DecomposableFunctionType& function, - const size_t batchSize, - const arma::mat& iterate) - { - // Find the number of functions to use. - const size_t numFunctions = function.NumFunctions(); - - double objective = 0; - for (size_t f = 0; f < numFunctions; f += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - f); - objective += function.Evaluate(iterate, f, effectiveBatchSize); - } - - return objective; - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/random_selection.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/random_selection.hpp deleted file mode 100644 index 0dd5def9d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/cmaes/random_selection.hpp +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @file random_selection.hpp - * @author Marcus Edel - * - * Randomly select dataset points for use in the Evaluation step. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_CMAES_RANDOM_SELECTION_HPP -#define MLPACK_CORE_OPTIMIZERS_CMAES_RANDOM_SELECTION_HPP - -#include - -namespace mlpack { -namespace optimization { - -/* - * Randomly select dataset points for use in the Evaluation step. - */ -class RandomSelection -{ - public: - /** - * Constructor for the random selection strategy. - * - * @param fraction The dataset fraction used for the selection (Default 0.3). - */ - RandomSelection(const double fraction = 0.3) : fraction(fraction) - { - // Nothing to do here. - } - - //! Get the dataset fraction. - double Fraction() const { return fraction; } - //! Modify the dataset fraction. - double& Fraction() { return fraction; } - - /** - * Randomly select dataset points to calculate the objective function. - * - * @tparam DecomposableFunctionType Type of the function to be evaluated. - * @param function Function to optimize. - * @param batchSize Batch size to use for each step. - * @param iterate starting point. - */ - template - double Select(DecomposableFunctionType& function, - const size_t batchSize, - const arma::mat& iterate) - { - // Find the number of functions to use. - const size_t numFunctions = function.NumFunctions(); - - double objective = 0; - for (size_t f = 0; f < std::floor(numFunctions * fraction); f += batchSize) - { - const size_t selection = math::RandInt(0, numFunctions); - const size_t effectiveBatchSize = std::min(batchSize, - numFunctions - selection); - - objective += function.Evaluate(iterate, selection, effectiveBatchSize); - } - - return objective; - } - - private: - //! Dataset fraction parameter. - double fraction; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/cne/cne.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/cne/cne.hpp deleted file mode 100644 index 1c404bef3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/cne/cne.hpp +++ /dev/null @@ -1,221 +0,0 @@ -/** - * @file cne.hpp - * @author Marcus Edel - * @author Kartik Nighania - * - * Conventional Neural Evolution - * An optimizer that works like biological evolution which selects best - * candidates based on their fitness scores and creates new generation by - * mutation and crossover of population. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_CNE_CNE_HPP -#define MLPACK_CORE_OPTIMIZERS_CNE_CNE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Conventional Neural Evolution (CNE) is a class of evolutionary algorithms - * focused on dealing with fixed topology. This class implements this algorithm - * as an optimization technique to converge a given function to minima. - * - * The algorithm works by creating a fixed number of candidates, with random - * weights. Each candidate is tested upon the training set, and a fitness score - * is assigned to it. Given the selection percentage of best candidates by the - * user, for a single generation that many percentage of candidates are selected - * for the next generation and the rest are removed The selected candidates for - * a particular generation then become the parents for the next generation and - * evolution takes place. - * - * The evolution process basically takes place in two types: - * - Crossover - * - Mutation - * - * Crossover takes two parents and generates two children from them. Both the - * children have properties inherited by their parents. The parameters of the - * parents are mixed using equal probability selection, creating two children. - * This is just a mix of link weights or the parameters. - * - * In mutation parameters are updated by pertubating small noise. - * If \f$ \Lambda \f$ is the number of weights in the network. - * - * \f[ \sum_{n=1}^{\Lambda}\omega_n = \omega_n + \rho, \f] - * - * where \f$ \rho \f$ is the small pertubation value determined randomly between - * 0 and the mutation size given by the user as a constructor parameter. Also - * the mutation probability taken as a constructor parameter decides the amount - * of mutation addition into the network. - * - * Both the above mentioned processes create new candidates as well as change - * the existing candidates to obtain better candidates in the next generation. - * - * The whole process then repeats for multiple generation until at least one of - * the termination criteria is met: - * - * 1) The final value of the objective function (Not considered if not provided). - * 2) The maximum number of generation reached (optional but highly recommended). - * 3) Minimum change in best fitness values between two consecutive generations - * should be greater than a threshold value (Not considered if not provided). - * - * The final value and the parameters are returned by the Optimize() method. - * - * For CNE to work, a FunctionType template parameter is required. - * This class must implement the following function: - * - * double Evaluate(const arma::mat& iterate); - */ -class CNE -{ - public: - /** - * Constructor for the CNE optimizer. - * - * The default values provided over here are not necessarily suitable for a - * given function. Therefore it is highly recommended to adjust the - * parameters according to the problem. - * - * @param populationSize The number of candidates in the population. - * This should be at least 4 in size. - * @param maxGenerations The maximum number of generations allowed for CNE. - * @param mutationProb Probability that a weight will get mutated. - * @param mutationSize The range of mutation noise to be added. This range - * is between 0 and mutationSize. - * @param selectPercent The percentage of candidates to select to become the - * the next generation. - * @param tolerance The final value of the objective function for termination. - * If set to negative value, tolerance is not considered. - * @param objectiveChange Minimum change in best fitness values between two - * consecutive generations should be greater than threshold. If set to - * negative value, objectiveChange is not considered. - */ - CNE(const size_t populationSize = 500, - const size_t maxGenerations = 5000, - const double mutationProb = 0.1, - const double mutationSize = 0.02, - const double selectPercent = 0.2, - const double tolerance = 1e-5, - const double objectiveChange = 1e-5); - - /** - * Optimize the given function using CNE. The given - * starting point will be modified to store the finishing point of the - * algorithm, and the final objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the population size. - size_t PopulationSize() const { return populationSize; } - //! Modify the population size. - size_t& PopulationSize() { return populationSize; } - - //! Get maximum number of generations. - size_t MaxGenerations() const { return maxGenerations; } - //! Modify maximum number of generations. - size_t& MaxGenerations() { return maxGenerations; } - - //! Get the mutation probability. - double MutationProbability() const { return mutationProb; } - //! Modify the mutation probability. - double& MutationProbability() { return mutationProb; } - - //! Get the mutation size. - double MutationSize() const { return mutationSize; } - //! Modify the mutation size. - double& MutationSize() { return mutationSize; } - - //! Get the selection percentage. - double SelectionPercentage() const { return selectPercent; } - //! Modify the selection percentage. - double& SelectionPercentage() { return selectPercent; } - - //! Get the final objective value. - double Tolerance() const { return tolerance; } - //! Modify the final objective value. - double& Tolerance() { return tolerance; } - - //! Get the change in fitness history between generations. - double ObjectiveChange() const { return objectiveChange; } - //! Modify the termination criteria of change in fitness value. - double& ObjectiveChange() { return objectiveChange; } - - private: - //! Reproduce candidates to create the next generation. - void Reproduce(); - - //! Modify weights with some noise for the evolution of next generation. - void Mutate(); - - /** - * Crossover parents and create new childs. Two parents create two new childs. - * - * @param mom First parent from the elite population. - * @param dad Second parent from the elite population. - * @param dropout1 The place to delete the candidate of the present - * generation and place a child over there for the - * next generation. - * @param dropout2 The place to delete the candidate of the present - * generation and place a child over there for the - * next generation. - */ - void Crossover(const size_t mom, - const size_t dad, - const size_t dropout1, - const size_t dropout2); - - //! Population matrix. Each column is a candidate. - arma::cube population; - - //! Vector of fintness values corresponding to each candidate. - arma::vec fitnessValues; - - //! Index of sorted fitness values. - arma::uvec index; - - //! The number of candidates in the population. - size_t populationSize; - - //! Maximum number of generations before termination criteria is met. - size_t maxGenerations; - - //! Probability that a weight will get mutated. - double mutationProb; - - //! The range of mutation noise to be added. - double mutationSize; - - //! The percentage of best candidates to be selected for parents. - double selectPercent; - - //! The final value of the objective function. - double tolerance; - - //! Minimum change in best fitness values between two generations. - double objectiveChange; - - //! Number of candidates to become parent for the next generation. - size_t numElite; - - //! Store the number of elements in a cube slice or a matrix column. - size_t elements; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "cne_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/cne/cne_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/cne/cne_impl.hpp deleted file mode 100644 index 9b6431514..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/cne/cne_impl.hpp +++ /dev/null @@ -1,222 +0,0 @@ -/** - * @file cne_impl.hpp - * @author Marcus Edel - * @author Kartik Nighania - * - * Conventional Neural Evolution - * An optimizer that works like biological evolution which selects best - * candidates based on their fitness scores and creates new generation by - * mutation and crossover of population. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_CNE_CNE_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_CNE_CNE_IMPL_HPP - -#include "cne.hpp" - -namespace mlpack { -namespace optimization { - -CNE::CNE(const size_t populationSize, - const size_t maxGenerations, - const double mutationProb, - const double mutationSize, - const double selectPercent, - const double tolerance, - const double objectiveChange) : - populationSize(populationSize), - maxGenerations(maxGenerations), - mutationProb(mutationProb), - mutationSize(mutationSize), - selectPercent(selectPercent), - tolerance(tolerance), - objectiveChange(objectiveChange), - numElite(0), - elements(0) -{ /* Nothing to do here. */ } - -//! Optimize the function. -template -double CNE::Optimize(DecomposableFunctionType& function, arma::mat& iterate) -{ - // Make sure for evolution to work at least four candidates are present. - if (populationSize < 4) - { - throw std::logic_error("CNE::Optimize(): population size should be at least" - " 4!"); - } - - // Find the number of elite canditates from population. - numElite = floor(selectPercent * populationSize); - - // Making sure we have even number of candidates to remove and create. - if ((populationSize - numElite) % 2 != 0) - numElite--; - - // Terminate if two parents can not be created. - if (numElite < 2) - { - throw std::logic_error("CNE::Optimize(): unable to select two parents. " - "Increase selection percentage."); - } - - // Terminate if at least two childs are not possible. - if ((populationSize - numElite) < 2) - { - throw std::logic_error("CNE::Optimize(): no space to accomodate even 2 " - "children. Increase population size."); - } - - // Set the population size and fill random values [0,1]. - population = arma::randu(iterate.n_rows, iterate.n_cols, populationSize); - - // Store the number of elements in a cube slice or a matrix column. - elements = population.n_rows * population.n_cols; - - // initializing helper variables. - fitnessValues.set_size(populationSize); - - Log::Info << "CNE initialized successfully. Optimization started." - << std::endl; - - // Find the fitness before optimization using given iterate parameters. - size_t lastBestFitness = function.Evaluate(iterate); - - // Iterate until maximum number of generations is obtained. - for (size_t gen = 1; gen <= maxGenerations; gen++) - { - // Calculating fitness values of all candidates. - for (size_t i = 0; i < populationSize; i++) - { - // Select a candidate and insert the parameters in the function. - iterate = population.slice(i); - - // Find fitness of candidate. - fitnessValues[i] = function.Evaluate(iterate); - } - - Log::Info << "Generation number: " << gen << " best fitness = " - << fitnessValues.min() << std::endl; - - // Create next generation of species. - Reproduce(); - - // Check for termination criteria. - if (tolerance >= fitnessValues.min()) - { - Log::Info << "CNE::Optimize(): terminating. Given fitness criteria " - << tolerance << " > " << fitnessValues.min() << "." << std::endl; - break; - } - - // Check for termination criteria. - if (lastBestFitness - fitnessValues.min() < objectiveChange) - { - Log::Info << "CNE::Optimize(): terminating. Fitness history change " - << (lastBestFitness - fitnessValues.min()) - << " < " << objectiveChange << "." << std::endl; - break; - } - - // Store the best fitness of present generation. - lastBestFitness = fitnessValues.min(); - } - - // Set the best candidate into the network parameters. - iterate = population.slice(index(0)); - - return function.Evaluate(iterate); -} - -//! Reproduce candidates to create the next generation. -void CNE::Reproduce() -{ - // Sort fitness values. Smaller fitness value means better performance. - index = arma::sort_index(fitnessValues); - - // First parent. - size_t mom; - - // Second parent. - size_t dad; - - for (size_t i = numElite; i < populationSize - 1; i++) - { - // Select 2 different parents from elite group randomly [0, numElite). - mom = mlpack::math::RandInt(0, numElite); - dad = mlpack::math::RandInt(0, numElite); - - // Making sure both parents are not the same. - if (mom == dad) - { - if (dad != numElite - 1) - { - dad++; - } - else - { - dad--; - } - } - - // Parents generate 2 children replacing the dropped-out candidates. - // Also finding the index of these candidates in the population matrix. - Crossover(index[mom], index[dad], index[i], index[i + 1]); - } - - // Mutating the weights with small noise values. - // This is done to bring change in the next generation. - Mutate(); -} - -//! Crossover parents to create new children. -void CNE::Crossover(const size_t mom, - const size_t dad, - const size_t child1, - const size_t child2) -{ - // Replace the candidates with parents at their place. - population.slice(child1) = population.slice(mom); - population.slice(child2) = population.slice(dad); - - // Preallocate random selection vector (values between 0 and 1). - arma::vec selection = arma::randu(elements); - - // Randomly alter mom and dad genome weights to get two different children. - for (size_t i = 0; i < elements; i++) - { - // Using it to alter the weights of the children. - if (selection(i) > 0.5) - { - population.slice(child1)(i) = population.slice(mom)(i); - population.slice(child2)(i) = population.slice(dad)(i); - } - else - { - population.slice(child1)(i) = population.slice(dad)(i); - population.slice(child2)(i) = population.slice(mom)(i); - } - } -} - -//! Modify weights with some noise for the evolution of next generation. -void CNE::Mutate() -{ - // Mutate the whole matrix with the given rate and probability. - // The best candidate is not altered. - for (size_t i = 1; i < populationSize; i++) - { - population.slice(index(i)) += (arma::randu( - population.n_rows, population.n_cols) < mutationProb) % - (mutationSize * arma::randn(population.n_rows, population.n_cols)); - } -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function.hpp deleted file mode 100644 index 8ca821252..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function.hpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @file function.hpp - * @author Ryan Curtin - * - * The Function class is a wrapper class for any objective function that - * provides any of the functions that an optimizer might use. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { - -template -class Function; - -} // namespace optimization -} // namespace mlpack - -#include "function/traits.hpp" -#include "function/static_checks.hpp" -#include "function/add_evaluate.hpp" -#include "function/add_gradient.hpp" -#include "function/add_evaluate_with_gradient.hpp" -#include "function/add_decomposable_evaluate.hpp" -#include "function/add_decomposable_gradient.hpp" -#include "function/add_decomposable_evaluate_with_gradient.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The Function class is a wrapper class for any FunctionType that will add any - * possible derived methods. For instance, if the given FunctionType has - * Evaluate() and Gradient(), then Function will have - * EvaluateWithGradient(). This infrastructure allows two things: - * - * 1. Optimizers can expect FunctionTypes to have a wider array of functions - * than those FunctionTypes may actually implement. - * - * 2. FunctionTypes don't need to implement every single method that an - * optimizer might require, just those from which every method can be - * inferred. - * - * This class works by inheriting from a large set of "mixin" classes that - * provide missing functions, if needed. For instance, the AddGradient<> mixin - * will provide a Gradient() method if the given FunctionType implements an - * EvaluateWithGradient() method. - * - * Since all of the casting is static and each of the mixin classes is an empty - * class, there should be no runtime overhead at all for this functionality. In - * addition, this class does not (to the best of my knowledge) rely on any - * undefined behavior. - */ -template -class Function : - public AddDecomposableEvaluateWithGradientStatic, - public AddDecomposableEvaluateWithGradientConst, - public AddDecomposableEvaluateWithGradient, - public AddDecomposableGradientStatic, - public AddDecomposableGradientConst, - public AddDecomposableGradient, - public AddDecomposableEvaluateStatic, - public AddDecomposableEvaluateConst, - public AddDecomposableEvaluate, - public AddEvaluateWithGradientStatic, - public AddEvaluateWithGradientConst, - public AddEvaluateWithGradient, - public AddGradientStatic, - public AddGradientConst, - public AddGradient, - public AddEvaluateStatic, - public AddEvaluateConst, - public AddEvaluate, - public FunctionType -{ - public: - // All of the mixin classes either reflect existing functionality or provide - // an unconstructable overload with the same name, so we can use using - // declarations here to ensure that they are all accessible. Since we don't - // know what FunctionType has, we can't use any using declarations there. - using AddDecomposableEvaluateWithGradientStatic< - FunctionType>::EvaluateWithGradient; - using AddDecomposableEvaluateWithGradientConst< - FunctionType>::EvaluateWithGradient; - using AddDecomposableEvaluateWithGradient::EvaluateWithGradient; - using AddDecomposableGradientStatic::Gradient; - using AddDecomposableGradientConst::Gradient; - using AddDecomposableGradient::Gradient; - using AddDecomposableEvaluateStatic::Evaluate; - using AddDecomposableEvaluateConst::Evaluate; - using AddDecomposableEvaluate::Evaluate; - using AddEvaluateWithGradientStatic::EvaluateWithGradient; - using AddEvaluateWithGradientConst::EvaluateWithGradient; - using AddEvaluateWithGradient::EvaluateWithGradient; - using AddGradientStatic::Gradient; - using AddGradientConst::Gradient; - using AddGradient::Gradient; - using AddEvaluateStatic::Evaluate; - using AddEvaluateConst::Evaluate; - using AddEvaluate::Evaluate; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate.hpp deleted file mode 100644 index e494e3700..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate.hpp +++ /dev/null @@ -1,216 +0,0 @@ -/** - * @file add_decomposable_evaluate.hpp - * @author Ryan Curtin - * - * Adds a decomposable Evaluate() function if a decomposable - * EvaluateWithGradient() function exists. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_DECOMPOSABLE_EVALUATE_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_DECOMPOSABLE_EVALUATE_HPP - -#include "traits.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The AddDecomposableEvaluate mixin class will add a decomposable Evaluate() - * method if a decomposable EvaluateWithGradient() function exists, or nothing - * otherwise. - */ -template::value, - bool HasDecomposableEvaluate = - traits::HasEvaluate::value> -class AddDecomposableEvaluate -{ - public: - // Provide a dummy overload so the name 'Evaluate' exists for this object. - double Evaluate(traits::UnconstructableType&, const size_t, const size_t); -}; - -/** - * Reflect the existing Evaluate(). - */ -template -class AddDecomposableEvaluate -{ - public: - // Reflect the existing Evaluate(). - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) - { - return static_cast( - static_cast*>(this))->Evaluate(coordinates, - begin, batchSize); - } -}; - -/** - * If we have a decomposable EvaluateWithGradient() but not a decomposable - * Evaluate(), add a decomposable Evaluate() method. - */ -template -class AddDecomposableEvaluate -{ - public: - /** - * Return the objective function for the given coordinates, starting at the - * given decomposable function using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of first function to evaluate. - * @param batchSize Number of functions to evaluate. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) - { - arma::mat gradient; // This will be ignored. - return static_cast*>(this)->EvaluateWithGradient( - coordinates, begin, gradient, batchSize); - } -}; - -/** - * The AddDecomposableEvaluateConst mixin class will add a decomposable const - * Evaluate() method if a decomposable const EvaluateWithGradient() function - * exists, or nothing otherwise. - */ -template::value, - bool HasDecomposableEvaluate = - traits::HasEvaluate::value> -class AddDecomposableEvaluateConst -{ - public: - // Provide a dummy overload so the name 'Evaluate' exists for this object. - double Evaluate(traits::UnconstructableType&, const size_t, const size_t) - const; -}; - -/** - * Reflect the existing Evaluate(). - */ -template -class AddDecomposableEvaluateConst -{ - public: - // Reflect the existing Evaluate(). - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const - { - return static_cast( - static_cast*>(this))->Evaluate(coordinates, - begin, batchSize); - } -}; - -/** - * If we have a decomposable const EvaluateWithGradient() but not a decomposable - * const Evaluate(), add a decomposable const Evaluate() method. - */ -template -class AddDecomposableEvaluateConst -{ - public: - /** - * Return the objective function for the given coordinates, starting at the - * given decomposable function using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of first function to evaluate. - * @param batchSize Number of functions to evaluate. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const - { - arma::mat gradient; // This will be ignored. - return - static_cast*>(this)->EvaluateWithGradient( - coordinates, begin, gradient, batchSize); - } -}; - -/** - * The AddDecomposableEvaluateStatic mixin class will add a decomposable static - * Evaluate() method if a decomposable static EvaluateWithGradient() function - * exists, or nothing otherwise. - */ -template::value, - bool HasDecomposableEvaluate = - traits::HasEvaluate::value> -class AddDecomposableEvaluateStatic -{ - public: - // Provide a dummy overload so the name 'Evaluate' exists for this object. - double Evaluate(traits::UnconstructableType&, const size_t) const; -}; - -/** - * Reflect the existing Evaluate(). - */ -template -class AddDecomposableEvaluateStatic -{ - public: - // Reflect the existing Evaluate(). - static double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) - { - return FunctionType::Evaluate(coordinates, begin, batchSize); - } -}; - -/** - * If we have a decomposable EvaluateWithGradient() but not a decomposable - * Evaluate(), add a decomposable Evaluate() method. - */ -template -class AddDecomposableEvaluateStatic -{ - public: - /** - * Return the objective function for the given coordinates, starting at the - * given decomposable function using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of first function to evaluate. - * @param batchSize Number of functions to evaluate. - */ - static double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) - { - arma::mat gradient; // This will be ignored. - return FunctionType::EvaluateWithGradient(coordinates, begin, gradient, - batchSize); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_const.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_const.hpp deleted file mode 100644 index 234fd4479..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_const.hpp +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @file add_decomposable_evaluate.hpp - * @author Ryan Curtin - * - * Adds a decomposable Evaluate() function if a decomposable - * EvaluateWithGradient() function exists. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_DECOMPOSABLE_EVALUATE_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_DECOMPOSABLE_EVALUATE_HPP - -#include "traits.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The AddDecomposableEvaluate mixin class will add a decomposable Evaluate() - * method if a decomposable EvaluateWithGradient() function exists, or nothing - * otherwise. - */ -template::value, - bool HasDecomposableEvaluate = - traits::HasEvaluate::value> -class AddDecomposableEvaluate -{ - public: - // Provide a dummy overload so the name 'Evaluate' exists for this object. - double Evaluate(traits::UnconstructableType&, const size_t); -}; - -/** - * Reflect the existing Evaluate(). - */ -template -class AddDecomposableEvaluate -{ - public: - // Reflect the existing Evaluate(). - double Evaluate(const arma::mat& coordinates, const size_t index) - { - return static_cast( - static_cast*>(this))->Evaluate(coordinates, - index); - } -}; - -/** - * If we have a decomposable EvaluateWithGradient() but not a decomposable - * Evaluate(), add a decomposable Evaluate() method. - */ -template -class AddDecomposableEvaluate -{ - public: - /** - * Return the objective function for the given coordinates, starting at the - * given decomposable function using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of first function to evaluate. - * @param batchSize Number of functions to evaluate. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) - { - arma::mat gradient; // This will be ignored. - return static_cast*>(this)->EvaluateWithGradient( - coordinates, begin, gradient, batchSize); - } -}; - -/** - * The AddDecomposableEvaluateConst mixin class will add a decomposable const - * Evaluate() method if a decomposable const EvaluateWithGradient() function - * exists, or nothing otherwise. - */ -template::value, - bool HasDecomposableEvaluate = - traits::HasEvaluate::value> -class AddDecomposableEvaluateConst { }; - -/** - * If we have a decomposable const EvaluateWithGradient() but not a decomposable - * const Evaluate(), add a decomposable const Evaluate() method. - */ -template -class AddDecomposableEvaluateConst -{ - public: - /** - * Return the objective function for the given coordinates, starting at the - * given decomposable function using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of first function to evaluate. - * @param batchSize Number of functions to evaluate. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const - { - arma::mat gradient; // This will be ignored. - return - static_cast*>(this)->EvaluateWithGradient( - coordinates, begin, gradient, batchSize); - } -}; - -/** - * The AddDecomposableEvaluateStatic mixin class will add a decomposable static - * Evaluate() method if a decomposable static EvaluateWithGradient() function - * exists, or nothing otherwise. - */ -template::value, - bool HasDecomposableEvaluate = - traits::HasEvaluate::value> -class AddDecomposableEvaluateStatic { }; - -/** - * If we have a decomposable EvaluateWithGradient() but not a decomposable - * Evaluate(), add a decomposable Evaluate() method. - */ -template -class AddDecomposableEvaluateStatic -{ - public: - /** - * Return the objective function for the given coordinates, starting at the - * given decomposable function using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of first function to evaluate. - * @param batchSize Number of functions to evaluate. - */ - static double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) - { - arma::mat gradient; // This will be ignored. - return FunctionType::EvaluateWithGradient(coordinates, begin, gradient, - batchSize); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_with_gradient.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_with_gradient.hpp deleted file mode 100644 index 00c33fb77..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_with_gradient.hpp +++ /dev/null @@ -1,261 +0,0 @@ -/** - * @file add_decomposable_evaluate_with_gradient.hpp - * @author Ryan Curtin - * - * Adds a decomposable EvaluateWithGradient() function if both a decomposable - * Evaluate() and a decomposable Gradient() function exist. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_DECOMPOSABLE_EVALUATE_W_GRADIENT_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_DECOMPOSABLE_EVALUATE_W_GRADIENT_HPP - -#include "traits.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The AddDecomposableEvaluateWithGradient mixin class will add a decomposable - * EvaluateWithGradient() method if a decomposable Evaluate() method and a - * decomposable Gradient() method exists, or nothing otherwise. - */ -template::value, - bool HasDecomposableEvaluateWithGradient = - traits::HasEvaluateWithGradient::value> -class AddDecomposableEvaluateWithGradient -{ - public: - // Provide a dummy overload so the name 'EvaluateWithGradient' exists for this - // object. - double EvaluateWithGradient(traits::UnconstructableType&, const size_t, - const size_t); -}; - -/** - * Reflect the existing EvaluateWithGradient(). - */ -template -class AddDecomposableEvaluateWithGradient -{ - public: - // Reflect the existing Evaluate(). - double EvaluateWithGradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - return static_cast( - static_cast*>(this))->EvaluateWithGradient( - coordinates, begin, gradient, batchSize); - } -}; - -/** - * If we have a both decomposable Evaluate() and a decomposable Gradient() but - * not a decomposable EvaluateWithGradient(), add a decomposable - * EvaluateWithGradient() method. - */ -template -class AddDecomposableEvaluateWithGradient -{ - public: - /** - * Return both the evaluated objective function and its gradient, storing the - * gradient in the given matrix, starting at the given decomposable function - * and using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of decomposable function to begin with. - * @param gradient Matrix to store the gradient into. - * @param batchSize Number of decomposable functions to evaluate. - */ - double EvaluateWithGradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - const double objective = - static_cast*>(this)->Evaluate(coordinates, begin, - batchSize); - static_cast*>(this)->Gradient(coordinates, begin, - gradient, batchSize); - return objective; - } -}; - -/** - * The AddDecomposableEvaluateWithGradientConst mixin class will add a - * decomposable const EvaluateWithGradient() method if both a decomposable const - * Evaluate() and a decomposable const Gradient() function exist, or nothing - * otherwise. - */ -template::value, - bool HasDecomposableEvaluateWithGradient = - traits::HasEvaluateWithGradient::value> -class AddDecomposableEvaluateWithGradientConst -{ - public: - // Provide a dummy overload so the name 'EvaluateWithGradient' exists for this - // object. - double EvaluateWithGradient(traits::UnconstructableType&, const size_t, - const size_t) const; -}; - -/** - * Reflect the existing EvaluateWithGradient(). - */ -template -class AddDecomposableEvaluateWithGradientConst -{ - public: - // Reflect the existing Evaluate(). - double EvaluateWithGradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const - { - return static_cast( - static_cast*>(this))->EvaluateWithGradient( - coordinates, begin, gradient, batchSize); - } -}; - -/** - * If we have both a decomposable const Evaluate() and a decomposable const - * Gradient() but not a decomposable const EvaluateWithGradient(), add a - * decomposable const EvaluateWithGradient() method. - */ -template -class AddDecomposableEvaluateWithGradientConst -{ - public: - /** - * Return both the evaluated objective function and its gradient, storing the - * gradient in the given matrix, starting at the given decomposable function - * and using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of decomposable function to begin with. - * @param gradient Matrix to store the gradient into. - * @param batchSize Number of decomposable functions to evaluate. - */ - double EvaluateWithGradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const - { - const double objective = - static_cast*>(this)->Evaluate(coordinates, - begin, batchSize); - static_cast*>(this)->Gradient(coordinates, - begin, gradient, batchSize); - return objective; - } -}; - -/** - * The AddDecomposableEvaluateWithGradientStatic mixin class will add a - * decomposable static EvaluateWithGradient() method if both a decomposable - * static Evaluate() and a decomposable static gradient() function exist, or - * nothing otherwise. - */ -template::value && - traits::HasGradient::value, - bool HasDecomposableEvaluateWithGradient = - traits::HasEvaluateWithGradient::value> -class AddDecomposableEvaluateWithGradientStatic -{ - public: - // Provide a dummy overload so the name 'EvaluateWithGradient' exists for this - // object. - static double EvaluateWithGradient(traits::UnconstructableType&, const size_t, - const size_t); -}; - -/** - * Reflect the existing EvaluateWithGradient(). - */ -template -class AddDecomposableEvaluateWithGradientStatic -{ - public: - // Reflect the existing Evaluate(). - static double EvaluateWithGradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - return FunctionType::EvaluateWithGradient(coordinates, begin, gradient, - batchSize); - } -}; - -/** - * If we have a decomposable static Evaluate() and a decomposable static - * Gradient() but not a decomposable static EvaluateWithGradient(), add a - * decomposable static Gradient() method. - */ -template -class AddDecomposableEvaluateWithGradientStatic -{ - public: - /** - * Return both the evaluated objective function and its gradient, storing the - * gradient in the given matrix, starting at the given decomposable function - * and using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of decomposable function to begin with. - * @param gradient Matrix to store the gradient into. - * @param batchSize Number of decomposable functions to evaluate. - */ - double EvaluateWithGradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const - { - const double objective = FunctionType::Evaluate(coordinates, begin, - batchSize); - FunctionType::Gradient(coordinates, begin, gradient, batchSize); - return objective; - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_with_gradient_const.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_with_gradient_const.hpp deleted file mode 100644 index 64c756d71..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_evaluate_with_gradient_const.hpp +++ /dev/null @@ -1,188 +0,0 @@ -/** - * @file add_decomposable_evaluate_with_gradient.hpp - * @author Ryan Curtin - * - * Add decomposable variants of Evaluate(), Gradient(), and - * EvaluateWithGradient(). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_ADD_DECOMPOSABLE_EVALUATE_WITH_GRADIENT_CONST_HPP -#define MLPACK_CORE_OPTIMIZERS_ADD_DECOMPOSABLE_EVALUATE_WITH_GRADIENT_CONST_HPP - -#include -#include "traits.hpp" - -namespace mlpack { -namespace optimization { - -namespace aux { - -template -using DecomposableEvaluateForm = double(FunctionType::*)(const arma::mat&, - const size_t, - const size_t); - -template -using DecomposableEvaluateConstForm = - double(FunctionType::*)(const arma::mat&, const size_t, const size_t) const; - -template -using DecomposableEvaluateStaticForm = double(*)(const arma::mat&, - size_t, - size_t); - -template -using DecomposableGradientForm = void(FunctionType::*)(const arma::mat&, - const size_t, - arma::mat&, - const size_t); - -template -using DecomposableGradientConstForm = - void(FunctionType::*)(const arma::mat&, - const size_t, - arma::mat&, - const size_t) const; - -template -using DecomposableGradientStaticForm = void(*)(const arma::mat&, - const size_t, - arma::mat&); - -template -using DecomposableEvaluateWithGradientForm = - double(FunctionType::*)(const arma::mat&, - const size_t, - arma::mat&, - const size_t); - -template -using DecomposableEvaluateWithGradientConstForm = - void(FunctionType::*)(const arma::mat&, - const size_t, - arma::mat&, - const size_t) const; - -template -using DecomposableEvaluateWithGradientStaticForm = - double(*)(const arma::mat&, const size_t, arma::mat&, const size_t); - -} // namespace aux - -/** - * The AddDecomposableEvaluateWithGradient mixin class will provide a - * decomposable Evaluate() and Gradient() method if the given class has a - * decomposable EvaluateWithGradient() method, or it will provide a decomposable - * EvaluateWithGradient() method if the class has a decomposable Evaluate() and - * Gradient() method, or it will provide nothing in any other case. - */ -template::value || - aux::HasEvaluate::value || - aux::HasEvaluate::value, - bool HasGradient = - aux::HasGradient::value || - aux::HasGradient::value || - aux::HasGradient::value, - bool HasEvaluateWithGradient = - aux::HasEvaluateWithGradient::value || - aux::HasEvaluateWithGradient::value || - aux::HasEvaluateWithGradient::value> -class AddDecomposableEvaluateWithGradient : public FunctionType { }; - -/** - * If the FunctionType has Evaluate() and Gradient() but not - * EvaluateWithGradient(), we will provide the latter. - */ -template -class AddDecomposableEvaluateWithGradient : - public FunctionType -{ - public: - /** - * Return both the evaluated objective function and its gradient, storing the - * gradient in the given matrix. - * - * @param coordinates Coordinates to evaluate the function at. - * @param gradient Matrix to store the gradient into. - */ - double EvaluateWithGradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - const double objective = FunctionType::Evaluate(coordinates, begin, - batchSize); - FunctionType::Gradient(coordinates, begin, gradient, batchSize); - return objective; - } -}; - -/** - * If the FunctionType has EvaluateWithGradient() but not Evaluate(), provide - * that function. - */ -template -class AddDecomposableEvaluateWithGradient : - public FunctionType -{ - public: - /** - * Return the objective function for the given coordinates. - * - * @param coordinates Coordinates to evaluate the function at. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) - { - arma::mat gradient; // This will be ignored. - return FunctionType::EvaluateWithGradient(coordinates, begin, gradient, - batchSize); - } -}; - -/** - * If the FunctionType has EvaluateWithGradient() but not Gradient(), provide - * that function. - */ -template -class AddDecomposableEvaluateWithGradient : - public FunctionType -{ - public: - /** - * Calculate the gradient and store it in the given matrix. - * - * @param coordinates Coordinates to evaluate the function at. - * @param gradient Matrix to store the gradient into. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - // The returned objective value will be ignored. - (void) FunctionType::EvaluateWithGradient(coordinates, begin, gradient, - batchSize); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_gradient.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_gradient.hpp deleted file mode 100644 index 9df8f9900..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_decomposable_gradient.hpp +++ /dev/null @@ -1,226 +0,0 @@ -/** - * @file add_decomposable_gradient.hpp - * @author Ryan Curtin - * - * Adds a decomposable Gradient() function if a decomposable - * EvaluateWithGradient() function exists. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_DECOMPOSABLE_GRADIENT_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_DECOMPOSABLE_GRADIENT_HPP - -#include "traits.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The AddDecomposableGradient mixin class will add a decomposable Gradient() - * method if a decomposable EvaluateWithGradient() function exists, or nothing - * otherwise. - */ -template::value, - bool HasDecomposableGradient = - traits::HasGradient::value> -class AddDecomposableGradient -{ - public: - // Provide a dummy overload so the name 'Gradient' exists for this object. - void Gradient(traits::UnconstructableType&, const size_t, const size_t); -}; - -/** - * Reflect the existing Gradient(). - */ -template -class AddDecomposableGradient -{ - public: - // Reflect the existing Gradient(). - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - static_cast( - static_cast*>(this))->Gradient(coordinates, - begin, gradient, batchSize); - } -}; - -/** - * If we have a decomposable EvaluateWithGradient() but not a decomposable - * Gradient(), add a decomposable Evaluate() method. - */ -template -class AddDecomposableGradient -{ - public: - /** - * Calculate the gradient and store it in the given matrix, starting at the - * given decomposable function index and using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of decomposable function to start at. - * @param gradient Matrix to store the gradient into. - * @param batchSize Number of decomposable functions to calculate for. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - // The returned objective value will be ignored. - (void) static_cast*>(this)->EvaluateWithGradient( - coordinates, begin, gradient, batchSize); - } -}; - -/** - * The AddDecomposableGradientConst mixin class will add a decomposable const - * Gradient() method if a decomposable const EvaluateWithGradient() function - * exists, or nothing otherwise. - */ -template::value, - bool HasDecomposableGradient = - traits::HasGradient::value> -class AddDecomposableGradientConst -{ - public: - // Provide a dummy overload so the name 'Gradient' exists for this object. - void Gradient(traits::UnconstructableType&, const size_t, const size_t) const; -}; - -/** - * Reflect the existing Gradient(). - */ -template -class AddDecomposableGradientConst -{ - public: - // Reflect the existing Gradient(). - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const - { - static_cast( - static_cast*>(this))->Gradient(coordinates, - begin, gradient, batchSize); - } -}; - -/** - * If we have a decomposable const EvaluateWithGradient() but not a decomposable - * const Gradient(), add a decomposable const Gradient() method. - */ -template -class AddDecomposableGradientConst -{ - public: - /** - * Calculate the gradient and store it in the given matrix, starting at the - * given decomposable function index and using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of decomposable function to start at. - * @param gradient Matrix to store the gradient into. - * @param batchSize Number of decomposable functions to calculate for. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const - { - // The returned objective value will be ignored. - (void) static_cast< - const Function*>(this)->EvaluateWithGradient(coordinates, - begin, gradient, batchSize); - } -}; - -/** - * The AddDecomposableEvaluateStatic mixin class will add a decomposable static - * Gradient() method if a decomposable static EvaluateWithGradient() function - * exists, or nothing otherwise. - */ -template::value, - bool HasDecomposableGradient = - traits::HasGradient::value> -class AddDecomposableGradientStatic -{ - public: - // Provide a dummy overload so the name 'Gradient' exists for this object. - static void Gradient(traits::UnconstructableType&, - const size_t, - const size_t); -}; - -/** - * Reflect the existing Gradient(). - */ -template -class AddDecomposableGradientStatic -{ - public: - // Reflect the existing Gradient(). - static void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - FunctionType::Gradient(coordinates, begin, gradient, batchSize); - } -}; - -/** - * If we have a decomposable EvaluateWithGradient() but not a decomposable - * Gradient(), add a decomposable Gradient() method. - */ -template -class AddDecomposableGradientStatic -{ - public: - /** - * Calculate the gradient and store it in the given matrix, starting at the - * given decomposable function index and using the given batch size. - * - * @param coordinates Coordinates to evaluate the function at. - * @param begin Index of decomposable function to start at. - * @param gradient Matrix to store the gradient into. - * @param batchSize Number of decomposable functions to calculate for. - */ - static void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) - { - // The returned objective value will be ignored. - (void) FunctionType::EvaluateWithGradient(coordinates, begin, gradient, - batchSize); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_evaluate.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_evaluate.hpp deleted file mode 100644 index 6826f9af1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_evaluate.hpp +++ /dev/null @@ -1,188 +0,0 @@ -/** - * @file add_evaluate.hpp - * @author Ryan Curtin - * - * This file defines a mixin for the Function class that will ensure that the - * function Evaluate() is avaliable if EvaluateWithGradient() is available. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_EVALUATE_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_EVALUATE_HPP - -#include -#include "traits.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The AddEvaluate mixin class will provide an Evaluate() method if the given - * FunctionType has EvaluateWithGradient(), or nothing otherwise. - */ -template::value, - bool HasEvaluate = - traits::HasEvaluate::value> -class AddEvaluate -{ - public: - // Provide a dummy overload so the name 'Evaluate' exists for this object. - double Evaluate(traits::UnconstructableType&); -}; - -/** - * Reflect the existing Evaluate(). - */ -template -class AddEvaluate -{ - public: - // Reflect the existing Evaluate(). - double Evaluate(const arma::mat& coordinates) - { - return static_cast(static_cast*>( - this))->Evaluate(coordinates); - } -}; - -/** - * If we have EvaluateWithGradient() but no existing Evaluate(), add an - * Evaluate() method. - */ -template -class AddEvaluate -{ - public: - /** - * Return the objective function for the given coordinates. - * - * @param coordinates Coordinates to evaluate the function at. - */ - double Evaluate(const arma::mat& coordinates) - { - arma::mat gradient; // This will be ignored. - return static_cast*>(this)->EvaluateWithGradient( - coordinates, gradient); - } -}; - -/** - * The AddEvaluateConst mixin class will provide a const Evaluate() method if - * the given FunctionType has EvaluateWithGradient() const, or nothing - * otherwise. - */ -template::value, - bool HasEvaluate = - traits::HasEvaluate::value> -class AddEvaluateConst -{ - public: - // Provide a dummy overload so the name 'Evaluate' exists for this object. - double Evaluate(traits::UnconstructableType&) const; -}; - -/** - * Reflect the existing Evaluate(). - */ -template -class AddEvaluateConst -{ - public: - // Reflect the existing Evaluate(). - double Evaluate(const arma::mat& coordinates) const - { - return static_cast(static_cast*>(this))->Evaluate( - coordinates); - } -}; - -/** - * If we have EvaluateWithGradient() but no existing Evaluate(), add an - * Evaluate() without a using directive to make the base Evaluate() accessible. - */ -template -class AddEvaluateConst -{ - public: - /** - * Return the objective function for the given coordinates. - * - * @param coordinates Coordinates to evaluate the function at. - */ - double Evaluate(const arma::mat& coordinates) const - { - arma::mat gradient; // This will be ignored. - return static_cast< - const Function*>(this)->EvaluateWithGradient(coordinates, - gradient); - } -}; - -/** - * The AddEvaluateStatic mixin class will provide a static Evaluate() method if - * the given FunctionType has EvaluateWithGradient() static, or nothing - * otherwise. - */ -template::value, - bool HasEvaluate = - traits::HasEvaluate::value> -class AddEvaluateStatic -{ - public: - // Provide a dummy overload so the name 'Evaluate' exists for this object. - static double Evaluate(traits::UnconstructableType&); -}; - -/** - * Reflect the existing Evaluate(). - */ -template -class AddEvaluateStatic -{ - public: - // Reflect the existing Evaluate(). - static double Evaluate(const arma::mat& coordinates) - { - return FunctionType::Evaluate(coordinates); - } -}; - -/** - * If we have EvaluateWithGradient() but no existing Evaluate(), add an - * Evaluate() without a using directive to make the base Evaluate() accessible. - */ -template -class AddEvaluateStatic -{ - public: - /** - * Return the objective function for the given coordinates. - * - * @param coordinates Coordinates to evaluate the function at. - */ - static double Evaluate(const arma::mat& coordinates) - { - arma::mat gradient; // This will be ignored. - return FunctionType::EvaluateWithGradient(coordinates, gradient); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_evaluate_with_gradient.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_evaluate_with_gradient.hpp deleted file mode 100644 index 47560f48f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_evaluate_with_gradient.hpp +++ /dev/null @@ -1,226 +0,0 @@ -/** - * @file add_evaluate_with_gradient.hpp - * @author Ryan Curtin - * - * This file defines a mixin for the Function class that will ensure that the - * EvaluateWithGradient() function is available if possible. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_EVALUATE_WITH_GRADIENT_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_EVALUATE_WITH_GRADIENT_HPP - -#include -#include -#include "traits.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The AddEvaluateWithGradient mixin class will provide an - * EvaluateWithGradient() method if the given FunctionType has both Evaluate() - * and Gradient(), or it will provide nothing otherwise. - */ -template::value, - bool HasEvaluateWithGradient = traits::HasEvaluateWithGradient< - FunctionType, - traits::EvaluateWithGradientForm>::value> -class AddEvaluateWithGradient -{ - public: - // Provide a dummy overload so the name 'EvaluateWithGradient' exists for this - // object. - double EvaluateWithGradient(traits::UnconstructableType&); -}; - -/** - * Reflect the existing EvaluateWithGradient(). - */ -template -class AddEvaluateWithGradient -{ - public: - // Reflect the existing EvaluateWithGradient(). - double EvaluateWithGradient(const arma::mat& coordinates, arma::mat& gradient) - { - return static_cast( - static_cast*>(this))->EvaluateWithGradient( - coordinates, gradient); - } -}; - -/** - * If the FunctionType has Evaluate() and Gradient(), provide - * EvaluateWithGradient(). - */ -template -class AddEvaluateWithGradient -{ - public: - /** - * Return both the evaluated objective function and its gradient, storing the - * gradient in the given matrix. - * - * @param coordinates Coordinates to evaluate the function at. - * @param gradient Matrix to store the gradient into. - */ - double EvaluateWithGradient(const arma::mat& coordinates, - arma::mat& gradient) - { - const double objective = - static_cast*>(this)->Evaluate(coordinates); - static_cast*>(this)->Gradient(coordinates, gradient); - return objective; - } -}; - -/** - * The AddEvaluateWithGradient mixin class will provide an - * EvaluateWithGradient() const method if the given FunctionType has both - * Evaluate() const and Gradient() const, or it will provide nothing otherwise. - */ -template::value, - bool HasEvaluateWithGradient = traits::HasEvaluateWithGradient< - FunctionType, - traits::EvaluateWithGradientConstForm>::value> -class AddEvaluateWithGradientConst -{ - public: - // Provide a dummy overload so the name 'EvaluateWithGradient' exists for this - // object. - double EvaluateWithGradient(traits::UnconstructableType&) const; -}; - -/** - * Reflect the existing EvaluateWithGradient(). - */ -template -class AddEvaluateWithGradientConst -{ - public: - // Reflect the existing EvaluateWithGradient(). - double EvaluateWithGradient(const arma::mat& coordinates, arma::mat& gradient) - const - { - return static_cast( - static_cast*>(this))->EvaluateWithGradient( - coordinates, gradient); - } -}; - -/** - * If the FunctionType has Evaluate() const and Gradient() const, provide - * EvaluateWithGradient() const. - */ -template -class AddEvaluateWithGradientConst -{ - public: - /** - * Return both the evaluated objective function and its gradient, storing the - * gradient in the given matrix. - * - * @param coordinates Coordinates to evaluate the function at. - * @param gradient Matrix to store the gradient into. - */ - double EvaluateWithGradient(const arma::mat& coordinates, - arma::mat& gradient) const - { - const double objective = - static_cast*>(this)->Evaluate(coordinates); - static_cast*>(this)->Gradient(coordinates, - gradient); - return objective; - } -}; - -/** - * The AddEvaluateWithGradientStatic mixin class will provide a - * static EvaluateWithGradient() method if the given FunctionType has both - * static Evaluate() and static Gradient(), or it will provide nothing - * otherwise. - */ -template::value && - traits::HasGradient::value, - bool HasEvaluateWithGradient = - traits::HasEvaluateWithGradient::value> -class AddEvaluateWithGradientStatic -{ - public: - // Provide a dummy overload so the name 'EvaluateWithGradient' exists for this - // object. - static double EvaluateWithGradient(traits::UnconstructableType&); -}; - -/** - * Reflect the existing EvaluateWithGradient(). - */ -template -class AddEvaluateWithGradientStatic -{ - public: - // Reflect the existing EvaluateWithGradient(). - static double EvaluateWithGradient(const arma::mat& coordinates, - arma::mat& gradient) - { - return FunctionType::EvaluateWithGradient(coordinates, gradient); - } -}; - -/** - * If the FunctionType has static Evaluate() and static Gradient(), provide - * static EvaluateWithGradient(). - */ -template -class AddEvaluateWithGradientStatic -{ - public: - /** - * Return both the evaluated objective function and its gradient, storing the - * gradient in the given matrix. - * - * @param coordinates Coordinates to evaluate the function at. - * @param gradient Matrix to store the gradient into. - */ - static double EvaluateWithGradient(const arma::mat& coordinates, - arma::mat& gradient) - { - const double objective = FunctionType::Evaluate(coordinates); - FunctionType::Gradient(coordinates, gradient); - return objective; - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_gradient.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_gradient.hpp deleted file mode 100644 index c4483e05c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/add_gradient.hpp +++ /dev/null @@ -1,187 +0,0 @@ -/** - * @file add_gradient.hpp - * @author Ryan Curtin - * - * This file defines a mixin for the Function class that will ensure that the - * function Gradient() is avaiable if EvaluateWithGradient() is available. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_GRADIENT_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_ADD_GRADIENT_HPP - -#include -#include "traits.hpp" - -namespace mlpack { -namespace optimization { - -/** - * The AddGradient mixin class will provide a Gradient() method if the given - * FunctionType has EvaluateWithGradient(), or nothing otherwise. - */ -template::value, - bool HasGradient = traits::HasGradient::value> -class AddGradient -{ - public: - // Provide a dummy overload so the name 'Gradient' exists for this object. - void Gradient(traits::UnconstructableType&) { } -}; - -/** - * Reflect the existing Gradient(). - */ -template -class AddGradient -{ - public: - // Reflect the existing Gradient(). - void Gradient(const arma::mat& coordinates, arma::mat& gradient) - { - static_cast(static_cast*>( - this))->Gradient(coordinates, gradient); - } -}; - -/** - * If we have EvaluateWithGradient() but no existing Gradient(), add an - * Gradient() without a using directive to make the base Gradient() accessible. - */ -template -class AddGradient -{ - public: - /** - * Calculate the gradient and store it in the given matrix. - * - * @param coordinates Coordinates to evaluate the function at. - * @param gradient Matrix to store the gradient into. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) - { - // The returned objective value will be ignored. - (void) static_cast*>(this)->EvaluateWithGradient( - coordinates, gradient); - } -}; - -/** - * The AddGradient mixin class will provide a const Gradient() method if the - * given FunctionType has EvaluateWithGradient() const, or nothing otherwise. - */ -template::value, - bool HasGradient = traits::HasGradient::value> -class AddGradientConst -{ - public: - // Provide a dummy overload so the name 'Gradient' exists for this object. - void Gradient(traits::UnconstructableType&) const { } -}; - -/** - * Reflect the existing Gradient(). - */ -template -class AddGradientConst -{ - public: - // Reflect the existing Gradient(). - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const - { - static_cast(static_cast*>(this))->Gradient(coordinates, - gradient); - } -}; - -/** - * If we have EvaluateWithGradient() but no existing Gradient(), add a - * Gradient() without a using directive to make the base Gradient() accessible. - */ -template -class AddGradientConst -{ - public: - /** - * Calculate the gradient and store it in the given matrix. - * - * @param coordinates Coordinates to evaluate the function at. - * @param gradient Matrix to store the gradient into. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const - { - // The returned objective value will be ignored. - (void) static_cast< - const Function*>(this)->EvaluateWithGradient(coordinates, - gradient); - } -}; - -/** - * The AddGradient mixin class will provide a static Gradient() method if the - * given FunctionType has static EvaluateWithGradient(), or nothing otherwise. - */ -template::value, - bool HasGradient = traits::HasGradient::value> -class AddGradientStatic -{ - public: - // Provide a dummy overload so the name 'Gradient' exists for this object. - static void Gradient(traits::UnconstructableType&) { } -}; - -/** - * Reflect the existing Gradient(). - */ -template -class AddGradientStatic -{ - public: - // Reflect the existing Gradient(). - static void Gradient(const arma::mat& coordinates, arma::mat& gradient) - { - FunctionType::Gradient(coordinates, gradient); - } -}; - -/** - * If we have EvaluateWithGradient() but no existing Gradient(), add a - * Gradient() without a using directive to make the base Gradient() accessible. - */ -template -class AddGradientStatic -{ - public: - /** - * Calculate the gradient and store it in the given matrix. - * - * @param coordinates Coordinates to evaluate the function at. - * @param gradient Matrix to store the gradient into. - */ - static void Gradient(const arma::mat& coordinates, arma::mat& gradient) - { - // The returned objective value will be ignored. - (void) FunctionType::EvaluateWithGradient(coordinates, gradient); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/static_checks.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/static_checks.hpp deleted file mode 100644 index 85ee1662a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/static_checks.hpp +++ /dev/null @@ -1,406 +0,0 @@ -/** - * @file static_checks.hpp - * @author Shikhar Bhardwaj - * - * This file contains the definitions of the method forms required by the - * FunctionType API used by the optimizers. These method forms can be used to - * check the compliance of a user provided FunctionType with the required - * interface from the optimizer at compile time. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_STATIC_CHECKS_HPP -#define MLPACK_CORE_OPTIMIZERS_STATIC_CHECKS_HPP - -#include -#include - -namespace mlpack { -namespace optimization { -namespace traits { - -/** - * Check if a suitable overload of Evaluate() is available. - * - * This is required by the FunctionType API. - */ -template -struct CheckEvaluate -{ - const static bool value = - HasEvaluate::value || - HasEvaluate::value || - HasEvaluate::value; -}; - -/** - * Check if a suitable overload of Gradient() is available. - * - * This is required by the FunctionType API. - */ -template -struct CheckGradient -{ - const static bool value = - HasGradient::value || - HasGradient::value || - HasGradient::value; -}; - -/** - * Check if a suitable overload of NumFunctions() is available. - * - * This is required by the DecomposableFunctionType API. - */ -template -struct CheckNumFunctions -{ - const static bool value = - HasNumFunctions::value || - HasNumFunctions::value || - HasNumFunctions::value; -}; - -/** - * Check if a suitable overload of Shuffle() is available. - * - * This is required by the DecomposableFunctionType API. - */ -template -struct CheckShuffle -{ - const static bool value = - HasShuffle::value || - HasShuffle::value || - HasShuffle::value; -}; - -/** - * Check if a suitable decomposable overload of Evaluate() is available. - * - * This is required by the DecomposableFunctionType API. - */ -template -struct CheckDecomposableEvaluate -{ - const static bool value = - HasEvaluate::value || - HasEvaluate::value || - HasEvaluate::value; -}; - -/** - * Check if a suitable decomposable overload of Gradient() is available. - * - * This is required by the DecomposableFunctionType API. - */ -template -struct CheckDecomposableGradient -{ - const static bool value = - HasGradient::value || - HasGradient::value || - HasGradient::value; -}; - -/** - * Check if a suitable overload of NumConstraints() is available. - * - * This is required by the ConstrainedFunctionType API. - */ -template -struct CheckNumConstraints -{ - const static bool value = - HasNumConstraints::value || - HasNumConstraints::value || - HasNumConstraints::value; -}; - -/** - * Check if a suitable overload of EvaluateConstraint() is available. - * - * This is required by the ConstrainedFunctionType API. - */ -template -struct CheckEvaluateConstraint -{ - const static bool value = - HasEvaluateConstraint::value || - HasEvaluateConstraint::value || - HasEvaluateConstraint::value; -}; - -/** - * Check if a suitable overload of GradientConstraint() is available. - * - * This is required by the ConstrainedFunctionType API. - */ -template -struct CheckGradientConstraint -{ - const static bool value = - HasGradientConstraint::value || - HasGradientConstraint::value || - HasGradientConstraint::value; -}; - -/** - * Check if a suitable overload of Gradient() that supports sparse gradients is - * available. - * - * This is required by the SparseFunctionType API. - */ -template -struct CheckSparseGradient -{ - const static bool value = - HasGradient::value || - HasGradient::value || - HasGradient::value; -}; - -/** - * Check if a suitable overload of NumFeatures() is available. - * - * This is required by the ResolvableFunctionType API. - */ -template -struct CheckNumFeatures -{ - const static bool value = - HasNumFeatures::value || - HasNumFeatures::value || - HasNumFeatures::value; -}; - -/** - * Check if a suitable overload of PartialGradient() is available. - * - * This is required by the ResolvableFunctionType API. - */ -template -struct CheckPartialGradient -{ - const static bool value = - HasPartialGradient::value || - HasPartialGradient::value || - HasPartialGradient::value; -}; - -/** - * Check if a suitable overload of EvaluateWithGradient() is available. - * - * This is required by the FunctionType API. - */ -template -struct CheckEvaluateWithGradient -{ - const static bool value = - HasEvaluateWithGradient::value || - HasEvaluateWithGradient::value || - HasEvaluateWithGradient::value; -}; - -/** - * Check if a suitable decomposable overload of EvaluateWithGradient() is - * available. - * - * This is required by the FunctionType API. - */ -template -struct CheckDecomposableEvaluateWithGradient -{ - const static bool value = - HasEvaluateWithGradient::value || - HasEvaluateWithGradient::value || - HasEvaluateWithGradient::value; -}; - -/** - * Perform checks for the regular FunctionType API. - */ -template -inline void CheckFunctionTypeAPI() -{ - static_assert(CheckEvaluate::value, - "The FunctionType does not have a correct definition of Evaluate(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the FunctionType API; see the optimizer tutorial for details."); - - static_assert(CheckGradient::value, - "The FunctionType does not have a correct definition of Gradient(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the FunctionType API; see the optimizer tutorial for details."); - - static_assert(CheckEvaluateWithGradient::value, - "The FunctionType does not have a correct definition of " - "EvaluateWithGradient(). Please check that the FunctionType fully " - "satisfies the requirements of the FunctionType API; see the optimizer " - "tutorial for more details."); -} - -/** - * Perform checks for the DecomposableFunctionType API. - */ -template -inline void CheckDecomposableFunctionTypeAPI() -{ - static_assert(CheckDecomposableEvaluate::value, - "The FunctionType does not have a correct definition of a decomposable " - "Evaluate() method. Please check that the FunctionType fully satisfies" - " the requirements of the DecomposableFunctionType API; see the optimizer" - " tutorial for more details."); - - static_assert(CheckDecomposableGradient::value, - "The FunctionType does not have a correct definition of a decomposable " - "Gradient() method. Please check that the FunctionType fully satisfies" - " the requirements of the DecomposableFunctionType API; see the optimizer" - " tutorial for more details."); - - static_assert(CheckDecomposableEvaluateWithGradient::value, - "The FunctionType does not have a correct definition of a decomposable " - "EvaluateWithGradient() method. Please check that the FunctionType " - "fully satisfies the requirements of the DecomposableFunctionType API; " - "see the optimizer tutorial for more details."); - - static_assert(CheckNumFunctions::value, - "The FunctionType does not have a correct definition of NumFunctions(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the DecomposableFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckShuffle::value, - "The FunctionType does not have a correct definition of Shuffle(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the DecomposableFunctionType API; see the optimizer tutorial for more " - "details."); -} - -/** - * Perform checks for the SparseFunctionType API. - */ -template -inline void CheckSparseFunctionTypeAPI() -{ - static_assert(CheckNumFunctions::value, - "The FunctionType does not have a correct definition of NumFunctions(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the SparseFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckDecomposableEvaluate::value, - "The FunctionType does not have a correct definition of Evaluate(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the SparseFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckSparseGradient::value, - "The FunctionType does not have a correct definition of a sparse " - "Gradient() method. Please check that the FunctionType fully satisfies " - "the requirements of the SparseFunctionType API; see the optimizer " - "tutorial for more details."); -} - -/** - * Perform checks for the NonDifferentiableFunctionType API. - */ -template -inline void CheckNonDifferentiableFunctionTypeAPI() -{ - static_assert(CheckEvaluate::value, - "The FunctionType does not have a correct definition of Evaluate(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the NonDifferentiableFunctionType API; see the optimizer tutorial for " - "more details."); -} - -/** - * Perform checks for the ResolvableFunctionType API. - */ -template -inline void CheckResolvableFunctionTypeAPI() -{ - static_assert(CheckNumFeatures::value, - "The FunctionType does not have a correct definition of NumFeatures(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the ResolvableFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckEvaluate::value, - "The FunctionType does not have a correct definition of Evaluate(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the ResolvableFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckPartialGradient::value, - "The FunctionType does not have a correct definition of a partial " - "Gradient() function. Please check that the FunctionType fully satisfies " - "the requirements of the ResolvableFunctionType API; see the optimizer " - "tutorial for more details."); -} - -/** - * Perform checks for the ConstrainedFunctionType API. - */ -template -inline void CheckConstrainedFunctionTypeAPI() -{ - static_assert(CheckEvaluate::value, - "The FunctionType does not have a correct definition of Evaluate(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the ConstrainedFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckGradient::value, - "The FunctionType does not have a correct definition of Gradient(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the ConstrainedFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckNumConstraints::value, - "The FunctionType does not have a correct definition of NumConstraints()." - " Please check that the FunctionType fully satisfies the requirements of " - "the ConstrainedFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckEvaluateConstraint::value, - "The FunctionType does not have a correct definition of " - "EvaluateConstraint(). Please check that the FunctionType fully satisfies" - " the ConstrainedFunctionType API; see the optimizer tutorial for more " - "details."); - - static_assert(CheckGradientConstraint::value, - "The FunctionType does not have a correct definition of " - "GradientConstraint(). Please check that the FunctionType fully satisfies" - " the ConstrainedFunctionType API; see the optimizer tutorial for more " - "details."); -} - -/** - * Perform checks for the NonDifferentiableDecomposableFunctionType API. (I - * know, it is a long name...) - */ -template -inline void CheckNonDifferentiableDecomposableFunctionTypeAPI() -{ - static_assert(CheckDecomposableEvaluate::value, - "The FunctionType does not have a correct definition of Evaluate(). " - "Please check that the FunctionType fully satisfies the requirements of " - "the NonDifferentiableDecomposableFunctionType API; see the optimizer " - "tutorial for more details."); -} - -} // namespace traits -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/function/traits.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/function/traits.hpp deleted file mode 100644 index 29abd7aac..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/function/traits.hpp +++ /dev/null @@ -1,341 +0,0 @@ -/** - * @file traits.hpp - * @author Ryan Curtin - * - * This file provides metaprogramming utilities for detecting certain members of - * FunctionType classes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FUNCTION_TRAITS_HPP -#define MLPACK_CORE_OPTIMIZERS_FUNCTION_TRAITS_HPP - -#include -#include - -namespace mlpack { -namespace optimization { -namespace traits { - -//! Detect an Evaluate() method. -HAS_EXACT_METHOD_FORM(Evaluate, HasEvaluate); -//! Detect a Gradient() method. -HAS_EXACT_METHOD_FORM(Gradient, HasGradient); -//! Detect an EvaluateWithGradient() method. -HAS_EXACT_METHOD_FORM(EvaluateWithGradient, HasEvaluateWithGradient); -//! Detect a NumFunctions() method. -HAS_EXACT_METHOD_FORM(NumFunctions, HasNumFunctions); -//! Detect a Shuffle() method. -HAS_EXACT_METHOD_FORM(Shuffle, HasShuffle); -//! Detect a NumConstraints() method. -HAS_EXACT_METHOD_FORM(NumConstraints, HasNumConstraints); -//! Detect an EvaluateConstraint() method. -HAS_EXACT_METHOD_FORM(EvaluateConstraint, HasEvaluateConstraint); -//! Detect a GradientConstraint() method. -HAS_EXACT_METHOD_FORM(GradientConstraint, HasGradientConstraint); -//! Detect a NumFeatures() method. -HAS_EXACT_METHOD_FORM(NumFeatures, HasNumFeatures); -//! Detect a PartialGradient() method. -HAS_EXACT_METHOD_FORM(PartialGradient, HasPartialGradient); - -//! This is the form of a non-const Evaluate() method. -template -using EvaluateForm = double(FunctionType::*)(const arma::mat&); - -//! This is the form of a const Evaluate() method. -template -using EvaluateConstForm = - double(FunctionType::*)(const arma::mat&) const; - -//! This is the form of a static Evaluate() method. -template -using EvaluateStaticForm = double(*)(const arma::mat&); - -//! This is the form of a non-const Gradient() method. -template -using GradientForm = void(FunctionType::*)(const arma::mat&, arma::mat&); - -//! This is the form of a const Gradient() method. -template -using GradientConstForm = - void(FunctionType::*)(const arma::mat&, arma::mat&) const; - -//! This is the form of a static Gradient() method. -template -using GradientStaticForm = void(*)(const arma::mat&, arma::mat&); - -//! This is the form of a non-const EvaluateWithGradient() method. -template -using EvaluateWithGradientForm = - double(FunctionType::*)(const arma::mat&, arma::mat&); - -//! This is the form of a const EvaluateWithGradient() method. -template -using EvaluateWithGradientConstForm = - double(FunctionType::*)(const arma::mat&, arma::mat&) const; - -//! This is the form of a static EvaluateWithGradient() method. -template -using EvaluateWithGradientStaticForm = - double(*)(const arma::mat&, arma::mat&); - -//! This is the form of a non-const NumFunctions() method. -template -using NumFunctionsForm = size_t(FunctionType::*)(); - -//! This is the form of a const NumFunctions() method. -template -using NumFunctionsConstForm = size_t(FunctionType::*)() const; - -//! This is the form of a static NumFunctions() method. -template -using NumFunctionsStaticForm = size_t(*)(); - -//! This is the form of a non-const Shuffle() method. -template -using ShuffleForm = void(FunctionType::*)(); - -//! This is the form of a const Shuffle() method. -template -using ShuffleConstForm = void(FunctionType::*)() const; - -//! This is the form of a static Shuffle() method. -template -using ShuffleStaticForm = void(*)(); - -//! This is the form of a decomposable Evaluate() method. -template -using DecomposableEvaluateForm = double(FunctionType::*)( - const arma::mat&, const size_t, const size_t); - -//! This is the form of a decomposable const Evaluate() method. -template -using DecomposableEvaluateConstForm = double(FunctionType::*)( - const arma::mat&, const size_t, const size_t) const; - -//! This is the form of a decomposable static Evaluate() method. -template -using DecomposableEvaluateStaticForm = double(*)( - const arma::mat&, const size_t, const size_t); - -//! This is the form of a decomposable non-const Gradient() method. -template -using DecomposableGradientForm = void(FunctionType::*)( - const arma::mat&, const size_t, arma::mat&, const size_t); - -//! This the form of a decomposable const Gradient() method. -template -using DecomposableGradientConstForm = void(FunctionType::*)( - const arma::mat&, const size_t, arma::mat&, const size_t) const; - -//! This is the form of a decomposable static Gradient() method. -template -using DecomposableGradientStaticForm = void(*)( - const arma::mat&, const size_t, arma::mat&, const size_t); - -//! This is the form of a decomposable non-const EvaluateWithGradient() method. -template -using DecomposableEvaluateWithGradientForm = double(FunctionType::*)( - const arma::mat&, const size_t, arma::mat&, const size_t); - -//! This is the form of a decomposable const EvaluateWithGradient() method. -template -using DecomposableEvaluateWithGradientConstForm = double(FunctionType::*)( - const arma::mat&, const size_t, arma::mat&, const size_t) const; - -//! This is the form of a decomposable static EvaluateWithGradient() method. -template -using DecomposableEvaluateWithGradientStaticForm = double(*)( - const arma::mat&, const size_t, arma::mat&, const size_t); - -//! This is the form of a non-const NumConstraints() method. -template -using NumConstraintsForm = size_t(FunctionType::*)(); - -//! This is the form of a const NumConstraints() method. -template -using NumConstraintsConstForm = size_t(FunctionType::*)() const; - -//! This is the form of a static NumConstraints() method. -template -using NumConstraintsStaticForm = size_t(*)(); - -//! This is the form of a non-const EvaluateConstraint() method. -template -using EvaluateConstraintForm = double(FunctionType::*)( - const size_t, const arma::mat&); - -//! This is the form of a const EvaluateConstraint() method. -template -using EvaluateConstraintConstForm = double(FunctionType::*)( - const size_t, const arma::mat&) const; - -//! This is the form of a static EvaluateConstraint() method. -template -using EvaluateConstraintStaticForm = double(*)(const size_t, const arma::mat&); - -//! This is the form of a non-const GradientConstraint() method. -template -using GradientConstraintForm = void(FunctionType::*)( - const size_t, const arma::mat&, arma::mat&); - -//! This is the form of a const GradientConstraint() method. -template -using GradientConstraintConstForm = void(FunctionType::*)( - const size_t, const arma::mat&, arma::mat&) const; - -//! This is the form of a static GradientConstraint() method. -template -using GradientConstraintStaticForm = void(*)( - const size_t, const arma::mat&, arma::mat&); - -//! This is the form of a non-const sparse Gradient() method. -template -using SparseGradientForm = void(FunctionType::*)( - const arma::mat&, const size_t, arma::sp_mat&, const size_t); - -//! This is the form of a const sparse Gradient() method. -template -using SparseGradientConstForm = void(FunctionType::*)( - const arma::mat&, const size_t, arma::sp_mat&, const size_t) const; - -//! This is the form of a static sparse Gradient() method. -template -using SparseGradientStaticForm = void(*)( - const arma::mat&, const size_t, arma::sp_mat&, const size_t); - -//! This is the form of a non-const NumFeatures() method. -template -using NumFeaturesForm = size_t(FunctionType::*)(); - -//! This is the form of a const NumFeatures() method. -template -using NumFeaturesConstForm = size_t(FunctionType::*)() const; - -//! This is the form of a static NumFeatures() method. -template -using NumFeaturesStaticForm = size_t(*)(); - -//! This is the form of a non-const PartialGradient() method. -template -using PartialGradientForm = void(FunctionType::*)( - const arma::mat&, const size_t, arma::sp_mat&); - -//! This is the form of a const PartialGradient() method. -template -using PartialGradientConstForm = void(FunctionType::*)( - const arma::mat&, const size_t, arma::sp_mat&) const; - -//! This is the form of a static PartialGradient() method. -template -using PartialGradientStaticForm = void(*)( - const arma::mat&, const size_t, arma::sp_mat&); - -//! This is a utility struct that will match any non-const form. -template -using OtherForm = double(FunctionType::*)(Ts...); - -//! This is a utility struct that will match any const form. -template -using OtherConstForm = double(FunctionType::*)(Ts...) const; - -//! This is a utility struct that will match any static form. -template -using OtherStaticForm = double(*)(Ts...); - -/** - * This is a utility type used to provide unusable overloads from each of the - * mixin classes. If you are seeing an error mentioning this class, the most - * likely issue is that you have not implemented the right methods for your - * FunctionType class. - */ -struct UnconstructableType -{ - private: - UnconstructableType() { } -}; - -/** - * Utility struct: sometimes we want to know if we have two functions available, - * and that at least one of them is non-const and non-static. If the - * corresponding checkers (from HAS_METHOD_FORM()) are given as CheckerA and - * CheckerB, and the corresponding non-const, const, and static function - * signatures are given as SignatureA, ConstSignatureA, StaticSignatureA, - * SignatureB, ConstSignatureB, and StaticSignatureB, then 'value' will be true - * if methods with the correct names exist in the given ClassType and at least - * one of those two methods is non-const and non-static. - */ -template class, size_t> class CheckerA, - template class SignatureA, - template class ConstSignatureA, - template class StaticSignatureA, - template class, size_t> class CheckerB, - template class SignatureB, - template class ConstSignatureB, - template class StaticSignatureB> -struct HasNonConstSignatures -{ - // Check if any const or static version of method A exists. - const static bool HasAnyFormA = - CheckerA::value || - CheckerA::value || - CheckerA::value; - // Check if any const or static versino of method B exists. - const static bool HasAnyFormB = - CheckerB::value || - CheckerB::value || - CheckerB::value; - - // Make sure at least one const version exists. - const static bool HasEitherNonConstForm = - CheckerA::value || - CheckerB::value; - - const static bool value = HasEitherNonConstForm && HasAnyFormA && HasAnyFormB; -}; - -/** - * Utility struct: sometimes we want to know if we have two functions available, - * and that at least one of them is const and both of them are not non-const and - * non-static. If the corresponding checkers (from HAS_METHOD_FORM()) are given - * as CheckerA and CheckerB, and the corresponding const and static function - * signatures are given as ConstSignatureA, StaticSignatureA, ConstSignatureB, - * and StaticSignatureB, then 'value' will be true if methods with the correct - * names exist in the given ClassType and at least one of those two methods is - * const, and neither method is non-const and non-static. - */ -template class, size_t> class CheckerA, - template class ConstSignatureA, - template class StaticSignatureA, - template class, size_t> class CheckerB, - template class ConstSignatureB, - template class StaticSignatureB> -struct HasConstSignatures -{ - // Check if any const or static version of method A exists. - const static bool HasAnyFormA = - CheckerA::value || - CheckerA::value; - // Check if any const or static version of method B exists. - const static bool HasAnyFormB = - CheckerB::value || - CheckerB::value; - - // Make sure at least one const version exists. - const static bool HasEitherConstForm = - CheckerA::value || - CheckerB::value; - - const static bool value = HasEitherConstForm && HasAnyFormA && HasAnyFormB; -}; - -} // namespace traits -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/atoms.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/atoms.hpp deleted file mode 100644 index 558a9204b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/atoms.hpp +++ /dev/null @@ -1,221 +0,0 @@ -/** - * @file atoms.hpp - * @author Chenzhe Diao - * - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_ATOMS_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_ATOMS_HPP - -#include -#include -#include "func_sq.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Class to hold the information and operations of current atoms in the - * soluton space. - */ -class Atoms -{ - public: - Atoms(){ /* Nothing to do. */ } - - /** - * Add atom into the solution space. - * - * @param v new atom to be added. - * @param c coefficient of the new atom. - */ - void AddAtom(const arma::vec& v, FuncSq& function, const double c = 0) - { - if (currentAtoms.is_empty()) - { - CurrentAtoms() = v; - CurrentCoeffs().set_size(1); - CurrentCoeffs().fill(c); - atomSqTerm.set_size(1); - atomSqTerm(0) = std::pow(norm(function.MatrixA() * v, 2), 2); - } - else - { - currentAtoms.insert_cols(0, v); - arma::vec cVec(1); - cVec(0) = c; - currentCoeffs.insert_rows(0, cVec); - double tmp = std::pow(norm(function.MatrixA() * v, 2), 2); - arma::vec tmpVec(1); - tmpVec(0) = tmp; - atomSqTerm.insert_rows(0, tmpVec); - } - } - - - //! Recover the solution coordinate from the coefficients of current atoms. - void RecoverVector(arma::mat& x) - { - x = currentAtoms * currentCoeffs; - } - - /** - * Prune the support, delete previous atoms if they don't contribute much. - * See Algorithm 2 of paper: - * @code - * @article{RaoShaWri:2015Forward--backward, - * Author = {Rao, Nikhil and Shah, Parikshit and Wright, Stephen}, - * Journal = {IEEE Transactions on Signal Processing}, - * Number = {21}, - * Pages = {5798--5811}, - * Publisher = {IEEE}, - * Title = {Forward--backward greedy algorithms for atomic norm regularization}, - * Volume = {63}, - * Year = {2015} - * } - * @endcode - * - * @param F thresholding number. - * @param function function to be optimized. - */ - void PruneSupport(const double F, FuncSq& function) - { - arma::vec sqTerm = 0.5 * atomSqTerm % square(currentCoeffs); - - while (currentAtoms.n_cols > 1) - { - // Solve for current gradient. - arma::mat x; - RecoverVector(x); - arma::mat gradient(size(x)); - function.Gradient(x, gradient); - - // Find possible atom to be deleted. - arma::vec gap = sqTerm - - currentCoeffs % trans(gradient.t() * currentAtoms); - arma::uword ind; - gap.min(ind); - - // Try deleting the atom. - arma::mat newAtoms(currentAtoms.n_rows, currentAtoms.n_cols - 1); - if (ind > 0) - newAtoms.cols(0, ind - 1) = currentAtoms.cols(0, ind - 1); - if (ind < (currentAtoms.n_cols - 1)) - { - newAtoms.cols(ind, newAtoms.n_cols - 1) = - currentAtoms.cols(ind + 1, currentAtoms.n_cols - 1); - } - - // Reoptimize the coefficients, we brute-forcely reoptimize in the span, - // which would be used in UpdateSpan class. Alternatively, if you want to - // add an atom norm constraint, you could use projected gradient method, - // see the implementaton of ProjectedGradientEnhancement(). - arma::vec newCoeffs = - solve(function.MatrixA() * newAtoms, function.Vectorb()); - - // Evaluate the function again. - double Fnew = function.Evaluate(newAtoms * newCoeffs); - - if (Fnew > F) - // Should not delete the atom. - break; - else - { - // Delete the atom from current atoms. - currentAtoms = newAtoms; - currentCoeffs = newCoeffs; - atomSqTerm.shed_row(ind); - sqTerm.shed_row(ind); - } // else - } // while - } - - - /** - * Enhance the solution in the convex hull of current atoms with atom norm - * constraint tau. Used in UpdateFullCorrection class for update step. - * - * Minimize the function in the atom domain defined by current atoms, - * where the solution still need to have atom norm (defined by current atoms) - * less than or equal to tau. We use projected gradient method to solve it, - * see the "Enhancement step" of the following paper: - * @code - * @article{RaoShaWri:2015Forward--backward, - * Author = {Rao, Nikhil and Shah, Parikshit and Wright, Stephen}, - * Journal = {IEEE Transactions on Signal Processing}, - * Number = {21}, - * Pages = {5798--5811}, - * Publisher = {IEEE}, - * Title = {Forward--backward greedy algorithms for atomic norm regularization}, - * Volume = {63}, - * Year = {2015} - * } - * @endcode - * - * @param function function to be minimized. - * @param tau atom norm constraint. - * @param stepSize step size for projected gradient method. - * @param maxIteration maximum iteration number. - * @param tolerance tolerance for projected gradient method. - */ - void ProjectedGradientEnhancement(FuncSq& function, - double tau, - double stepSize, - size_t maxIteration = 100, - double tolerance = 1e-3) - { - arma::mat x; - RecoverVector(x); - double value = function.Evaluate(x); - - for (size_t iter = 1; iter - -namespace mlpack { -namespace optimization { - -/** - * LinearConstrSolver for FrankWolfe algorithm. Constraint domain given in the - * form of lp ball. That is, given \f$ v \f$, solve - * \f$ - * s:=arg\min_{s\in D} - * \f$ - * when \f$ D \f$ is a regularized lp ball. That is, - * \f[ - * D = \{ x: (\sum_j|\lambda_j x_j|^p)^{1/p}\leq 1 \}. - * \f] - * If \f$ \lambda \f$ is not given in the constructor, default is using all - * \f$ \lambda_j = 1 \f$ for all \f$ j \f$. - * - * In applications such as Orthogonal Matching Pursuit (OMP), \f$ \lambda \f$ - * could be ideally set to the norm of the elements in the dictionary. - * - * For \f$ p=1 \f$: take (one) \f$ k = arg\max_j |v_j/\lambda_j|\f$, then the - * solution is: - * \f[ - * s_k = -sign(v_k)/\lambda_k, \qquad s_j = 0, \quad j\neq k. - * \f] - * - * For \f$ 1::infinity()) - { - // l-inf ball. - s = -sign(v); - if (regFlag) - s = s / lambda; // element-wise division. - } - else if (p > 1.0) - { - // lp ball with 1::infinity() for inf norm. - double p; - - //! Regularization flag. - bool regFlag = false; - - //! Regularization parameter. - arma::vec lambda; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/constr_structure_group.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/constr_structure_group.hpp deleted file mode 100644 index 4bd37cb77..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/constr_structure_group.hpp +++ /dev/null @@ -1,244 +0,0 @@ -/** - * @file constr_structure_group.hpp - * @author Chenzhe Diao - * - * Solve the linear constrained problem, where the constrained domain are atom - * domains defined by unit balls under structured group norm. - * Used as LinearConstrSolverType in FrankWolfe. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_CONSTR_STRUCTURE_GROUP_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_CONSTR_STRUCTURE_GROUP_HPP - -#include -#include "constr_lpball.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Linear Constrained Solver for FrankWolfe. Constrained domain given in the - * form of unit ball of different structured group. That is, given original - * vector \f$ v \f$ in high dimensional space, suppose we can map it into - * different smaller dimensional spaces (decomposing the information): - * \f[ - * v \rightarrow v_g, \qquad g\in G. - * \f] - * - * For example, each group corresponds to a specific set of support subsets, - * as in GroupLpBall class. Also, a norm would be equipped for each group: - * \f$ || v_g ||_g \f$, for example lp norm could be used, as in GroupLpBall - * class. Now, the norm defined for the original vector is: - * \f[ - * ||v||_G := \min_{v_g} \sum_{g\in G} ||v_g||_g, \qquad - * s.t. \quad v = \sum_{g\in G} v_g - * \f] - * This norm is an atom norm, and the dual norm is given by - * \f[ - * ||y||^*_G := \max_{g\in G} ||y_g||_g^* - * \f] - * - * See Jaggi's paper: - * @code - * @inproceedings{Jag:2013Revisiting, - * Author = {Jaggi, Martin}, - * Booktitle = {ICML (1)}, - * Pages = {427--435}, - * Title = {Revisiting Frank-Wolfe: Projection-Free Sparse Convex Optimization.}, - * Year = {2013}} - * @endcode - * - * For ConstrStrctGroupSolver to work, we need to use template class GroupType, - * which gives functions: - * - * size_t NumGroups(); - * double DualNorm(const arma::vec& yk, const int group_ind); - * ProjectToGroup(const arma::mat& v, const size_t groupId, arma::vec& y); - * void OptimalFromGroup(const arma::mat& v, const size_t groupId, arma::mat& s); - * - * @tparam GroupType Class that implements functions to map original vectors to - * each group, and to solve linear optimization problem in the - * unit ball defined by the norm of each group. - */ -template -class ConstrStructGroupSolver -{ - public: - /** - * Construct the structure group optimization solver. - * - * @param groupExtractor Class used to project to a group, recovery from a - * group, and compute norm in each group. - */ - ConstrStructGroupSolver(GroupType& groupExtractor) : - groupExtractor(groupExtractor) - { /* Nothing to do */ } - - /** - * Optimizer of structure group ball constrained Problem for FrankWolfe. - * - * @param v Input local gradient. - * @param s Output optimal solution in the constrained atom domain. - */ - void Optimize(const arma::mat& v, arma::mat& s) - { - size_t nGroups = groupExtractor.NumGroups(); - double dualNorm = 0; - size_t optimalGroup = 1; - - // Find the optimal group. - for (size_t i = 1; i <= nGroups; ++i) - { - arma::vec y; - groupExtractor.ProjectToGroup(v, i, y); - double newNorm = groupExtractor.DualNorm(y, i); - - // Find the group with largest dual norm. - if (newNorm > dualNorm) - { - optimalGroup = i; - dualNorm = newNorm; - } - } - - groupExtractor.OptimalFromGroup(v, optimalGroup, s); - } - - private: - //! Information and methods for groups. - GroupType& groupExtractor; -}; - -/** - * Implementation of Structured Group. The projection to each group is using - * restriction of vector support here, and the norm in each group is using lp - * norm. - */ -class GroupLpBall -{ - public: - /** - * Construct the lp ball group extractor class. - * - * @param p lp ball. - * @param dimOrig dimension of the original vector. - * @param groupIndicesList vector of support indices lists of each group. - */ - GroupLpBall(const double p, - const size_t dimOrig, - std::vector groupIndicesList): - p(p), numGroups(groupIndicesList.size()), - dimOrig(dimOrig), - groupIndicesList(groupIndicesList), - lpBallSolver(p) - {/* Nothing to do. */} - - /** - * Projection to specific group. - * - * @param v input vector to be projected. - * @param groupId input ID number of the group, start from 1. - * @param y output projection of the vector to specific group. - */ - void ProjectToGroup(const arma::mat& v, const size_t groupId, arma::vec& y) - { - arma::uvec& indList = groupIndicesList[groupId - 1]; - size_t dim = indList.n_elem; - y.set_size(dim); - - for (size_t i = 0; i < dim; ++i) - y(i) = v(indList(i)); - } - - /** - * Get optimal atom, which belongs to specific group. - * See Jaggi's paper for details. - * - * @param v input gradient vector. - * @param groupId optimal atom belongs to this group. - * @param s output optimal atom. - */ - void OptimalFromGroup(const arma::mat& v, const size_t groupId, arma::mat& s) - { - // Project v to group. - arma::vec yk; - ProjectToGroup(v, groupId, yk); - - // Optimize in this group. - arma::vec sProj(yk.n_elem); - lpBallSolver.Optimize(yk, sProj); - - // Recover s to the original dimension. - arma::uvec& indList = groupIndicesList[groupId - 1]; - size_t dim = indList.n_elem; // dimension of the group. - s.zeros(dimOrig, 1); - - for (size_t i = 0; i < dim; ++i) - s(indList(i)) = sProj(i); - } - - //! Get the number of groups. - size_t NumGroups() const {return numGroups;} - //! Modify the number of groups. - size_t& NumGroups() {return numGroups;} - - /** - * Compute the q-norm of yk, 1/p+1/q=1. - * - * @param yk compute the q-norm of yk. - * @param groupId group ID number. - */ - double DualNorm(const arma::vec& yk, const int groupId) - { - if (p == std::numeric_limits::infinity()) - { - // inf-norm, return 1-norm - return arma::norm(yk, 1); - } - else if (p > 1.0) - { - // p norm, return q-norm - double q = 1.0 / (1.0 - 1.0/p); - return arma::norm(yk, q); - } - else if (p == 1.0) - { - // 1-norm, return inf-norm - return arma::norm(yk, "inf"); - } - else - { - Log::Fatal << "Wrong norm p!" << std::endl; - return 0.0; - } - } - - private: - //! lp norm, 1<=p<=inf; - //! use std::numeric_limits::infinity() for inf norm. - double p; - - //! Number of groups. - size_t numGroups; - - //! Original Problem Dimension. - size_t dimOrig; - - //! Indices list of each group, indices start from 0. - std::vector groupIndicesList; - - //! Each group uses lp norm - ConstrLpBallSolver lpBallSolver; -}; - - -} // namespace optimization -} // namespace mlpack - - - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/frank_wolfe.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/frank_wolfe.hpp deleted file mode 100644 index 27ba27011..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/frank_wolfe.hpp +++ /dev/null @@ -1,170 +0,0 @@ -/** - * @file frank_wolfe.hpp - * @author Chenzhe Diao - * - * Frank-Wolfe Algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_FRANK_WOLFE_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_FRANK_WOLFE_HPP - -#include -#include "update_span.hpp" -#include "constr_lpball.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Frank-Wolfe is a technique to minimize a continuously differentiable convex - * function \f$ f \f$ over a compact convex subset \f$ D \f$ of a vector space. - * It is also known as conditional gradient method. - * - * To find minimum of a function using Frank-Wolfe in each iteration \f$ k \f$: - * 1. One optimize the linearized constrained problem, using LinearConstrSolver: - * \f[ - * s_k:= arg\min_{s\in D} - * \f] - * - * 2. Update \f$ x \f$ using UpdateRule: - * \f[ - * x_{k+1} := (1-\gamma) x_k + \gamma s_k - * \f] - * for some \f$ \gamma \in (0, 1) \f$, or use Fully-Corrective Variant: - * \f[ - * x_{k+1}:= arg\min_{x\in conv(s_0, \cdots, s_k)} f(x) - * \f] - * - * - * The algorithm continues until \f$ k \f$ reaches the maximum number of - * iterations, or when the duality gap is bounded by a certain tolerance - * \f$ \epsilon \f$. - * That is, - * - * \f[ - * g(x):= \max_{s\in D} \quad \leq \epsilon, - * \f] - * - * we also know that \f$ g(x) \geq f(x) - f(x^*) \f$, where \f$ x^* \f$ is the - * optimal solution. - * - * The parameter \f$ \epsilon \f$ is specified by the tolerance parameter to the - * constructor. - * - * For FrankWolfe to work, LinearConstrSolverType and UpdateRuleType - * template parameters are required. - * These classes must implement the following functions: - * - * LinearConstrSolverType: - * - * void Optimize(const arma::mat& gradient, - * arma::mat& s); - * - * UpdateRuleType: - * - * void Update(const arma::mat& old_coords, - * const arma::mat& s, - * arma::mat& new_coords, - * const size_t num_iter); - * - * @tparam LinearConstrSolverType Solver for the linear constrained problem. - * @tparam UpdateRuleType Rule to update the solution in each iteration. - * - */ -template< - typename LinearConstrSolverType, - typename UpdateRuleType> -class FrankWolfe -{ - public: - /** - * Construct the Frank-Wolfe optimizer with the given function and - * parameters. Notice that the constraint domain \f$ D \f$ is input - * at the initialization of linear_constr_solver, the function to be - * optimized is stored in update_rule. - * - * @param linearConstrSolver Solver for linear constrained problem. - * @param updateRule Rule for updating solution in each iteration. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - */ - FrankWolfe(const LinearConstrSolverType linearConstrSolver, - const UpdateRuleType updateRule, - const size_t maxIterations = 100000, - const double tolerance = 1e-10); - - /** - * Optimize the given function using FrankWolfe. The given starting - * point will be modified to store the finishing point of the algorithm, - * the final objective value is returned. - * - * FunctionType template class must provide the following functions: - * - * double Evaluate(const arma::mat& coordinates); - * void Gradient(const arma::mat& coordinates, - * arma::mat& gradient); - * - * @param function Function to be optimized. - * @param iterate Input with starting point, and will be modified to save - * the output optimial solution coordinates. - * @return Objective value at the final solution. - */ - template - double Optimize(FunctionType& function, arma::mat& iterate); - - //! Get the linear constrained solver. - const LinearConstrSolverType& LinearConstrSolver() - const { return linearConstrSolver; } - //! Modify the linear constrained solver. - LinearConstrSolverType& LinearConstrSolver() { return linearConstrSolver; } - - //! Get the update rule. - const UpdateRuleType& UpdateRule() const { return updateRule; } - //! Modify the update rule. - UpdateRuleType& UpdateRule() { return updateRule; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - private: - //! The solver for constrained linear problem in first step. - LinearConstrSolverType linearConstrSolver; - - //! The rule to update, used in the second step. - UpdateRuleType updateRule; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The tolerance for termination. - double tolerance; -}; - -/** - * Orthogonal Matching Pursuit. It is a sparse approximation algorithm which - * involves finding the "best matching" projections of multidimensional data - * onto the span of an over-complete dictionary. To use it, the dictionary is - * input as the columns of MatrixA() in FuncSq class, and the vector to be - * approximated is input as the Vectorb() in FuncSq class. - */ -using OMP = FrankWolfe; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "frank_wolfe_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/frank_wolfe_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/frank_wolfe_impl.hpp deleted file mode 100644 index c819a8584..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/frank_wolfe_impl.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file frank_wolfe_impl.hpp - * @author Chenzhe Diao - * - * Frank-Wolfe Algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_FRANK_WOLFE_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_FRANK_WOLFE_IMPL_HPP - -// In case it hasn't been included yet. -#include "frank_wolfe.hpp" - -#include - -namespace mlpack { -namespace optimization { - -//! Constructor of the FrankWolfe class. -template< - typename LinearConstrSolverType, - typename UpdateRuleType> -FrankWolfe:: -FrankWolfe(const LinearConstrSolverType linearConstrSolver, - const UpdateRuleType updateRule, - const size_t maxIterations, - const double tolerance) : - linearConstrSolver(linearConstrSolver), - updateRule(updateRule), - maxIterations(maxIterations), - tolerance(tolerance) -{ /* Nothing to do*/ } - - -//! Optimize the function (minimize). -template< - typename LinearConstrSolverType, - typename UpdateRuleType> -template -double FrankWolfe:: -Optimize(FunctionType& function, arma::mat& iterate) -{ - typedef Function FullFunctionType; - FullFunctionType& f = static_cast(function); - - // Make sure we have all necessary functions. - traits::CheckFunctionTypeAPI(); - - // To keep track of the function value. - double currentObjective = DBL_MAX; - - arma::mat gradient(iterate.n_rows, iterate.n_cols); - arma::mat s(iterate.n_rows, iterate.n_cols); - arma::mat iterateNew(iterate.n_rows, iterate.n_cols); - double gap = 0; - - for (size_t i = 1; i != maxIterations; ++i) - { - currentObjective = f.EvaluateWithGradient(iterate, gradient); - - // Output current objective function. - Log::Info << "FrankWolfe::Optimize(): iteration " << i << ", objective " - << currentObjective << "." << std::endl; - - // Solve linear constrained problem, solution saved in s. - linearConstrSolver.Optimize(gradient, s); - - // Check duality gap for return condition. - gap = std::fabs(dot(iterate - s, gradient)); - if (gap < tolerance) - { - Log::Info << "FrankWolfe::Optimize(): minimized within tolerance " - << tolerance << "; " << "terminating optimization." << std::endl; - return currentObjective; - } - - - // Update solution, save in iterateNew. - updateRule.Update(f, iterate, s, iterateNew, i); - - iterate = std::move(iterateNew); - } - - Log::Info << "FrankWolfe::Optimize(): maximum iterations (" << maxIterations - << ") reached; " << "terminating optimization." << std::endl; - return currentObjective; -} // Optimize() - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/func_sq.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/func_sq.hpp deleted file mode 100644 index d450c2e20..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/func_sq.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file func_sq.hpp - * @author Chenzhe Diao - * - * Square loss function: \f$ x-> 0.5 * || Ax - b ||_2^2 \f$. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_FUNC_SQ_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_FUNC_SQ_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Square loss function \f$ f(x) = 0.5 * ||Ax - b||_2^2 \f$. - * - * Contains matrix \f$ A \f$ and vector \f$ b \f$. - */ -class FuncSq -{ - public: - /** - * Construct the square loss function. - * - * @param A matrix A. - * @param b vector b. - */ - FuncSq(const arma::mat& A, const arma::vec& b) : A(A), b(b) - {/* Nothing to do. */} - - /** - * Evaluation of the function. - * \f$ f(x) = 0.5 * ||Ax - b||_2^2 \f$ - * - * @param coords vector x. - * @return \f$ f(x) \f$. - */ - double Evaluate(const arma::mat& coords) - { - arma::vec r = A * coords - b; - return arma::dot(r, r) * 0.5; - } - - /** - * Gradient of square loss function. - * \f$ \nabla f(x) = A^T(Ax - b) \f$ - * - * @param coords input vector x. - * @param gradient output gradient vector. - */ - void Gradient(const arma::mat& coords, arma::mat& gradient) - { - arma::vec r = A * coords - b; - gradient = A.t() * r; - } - - //! Get the matrix A. - arma::mat MatrixA() const {return A;} - //! Modify the matrix A. - arma::mat& MatrixA() {return A;} - - //! Get the vector b. - arma::vec Vectorb() const { return b; } - //! Modify the vector b. - arma::vec& Vectorb() { return b; } - - private: - //! Matrix A in square loss function. - arma::mat A; - - //! Vector b in square loss function. - arma::vec b; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/test_func_fw.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/test_func_fw.hpp deleted file mode 100644 index e75a00a30..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/test_func_fw.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @file test_func_sq.hpp - * @author Chenzhe Diao - * - * Simple test function for classic Frank Wolfe Algorithm: - * - * \f$ f(x) = (x1 - 0.1)^2 + (x2 - 0.2)^2 + (x3 - 0.3)^2 \f$ - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_TEST_FUNC_FW_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_TEST_FUNC_FW_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Simple test function for classic Frank Wolfe Algorithm: - * - * \f$ f(x) = (x1 - 0.1)^2 + (x2 - 0.2)^2 + (x3 - 0.3)^2 \f$. - */ -class TestFuncFW -{ - public: - TestFuncFW() - {/* Nothing to do. */} - - /** - * Evaluation of the function. - * - * @param coords input vector x. - */ - double Evaluate(const arma::mat& coords) - { - double f = std::pow(coords[0] - 0.1, 2); - f += std::pow(coords[1] - 0.2, 2); - f += std::pow(coords[2] - 0.3, 2); - return f; - } - - /** - * Gradient of the function. - * - * @param coords input vector x. - * @param gradient output gradient vector. - */ - void Gradient(const arma::mat& coords, arma::mat& gradient) - { - gradient.set_size(3, 1); - gradient[0] = coords[0] - 0.1; - gradient[1] = coords[1] - 0.2; - gradient[2] = coords[2] - 0.3; - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_classic.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_classic.hpp deleted file mode 100644 index 14b726197..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_classic.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file update_classic.hpp - * @author Chenzhe Diao - * - * Classic update method for FrankWolfe algorithm. Used as UpdateRuleType. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_UPDATE_CLASSIC_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_UPDATE_CLASSIC_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Use classic rule in the update step for FrankWolfe algorithm. That is, - * take \f$ \gamma = \frac{2}{k+2} \f$, where \f$ k \f$ is the iteration - * number. The update rule would be: - * \f[ - * x_{k+1} = (1-\gamma) x_k + \gamma s - * \f] - * - */ -class UpdateClassic -{ - public: - /** - * Construct the classic update rule for FrankWolfe algorithm. - */ - UpdateClassic() { /* Do nothing. */ } - - /** - * Classic update rule for FrankWolfe. - * - * \f$ x_{k+1} = (1-\gamma)x_k + \gamma s \f$, where \f$ \gamma = 2/(k+2) \f$ - * - * @param function function to be optimized, not used in this update rule. - * @param oldCoords previous solution coords. - * @param s current linear_constr_solution result. - * @param newCoords output new solution coords. - * @param numIter current iteration number - */ - template - void Update(FunctionType& /* function */, - const arma::mat& oldCoords, - const arma::mat& s, - arma::mat& newCoords, - const size_t numIter) - { - double gamma = 2.0 / (numIter + 2.0); - newCoords = (1.0 - gamma) * oldCoords + gamma * s; - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_full_correction.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_full_correction.hpp deleted file mode 100644 index fd8c0c4e3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_full_correction.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @file update_full_correction.hpp - * @author Chenzhe Diao - * - * Update method for FrankWolfe algorithm, recalculate the coefficents of - * of current atoms, while satisfying the norm constraint. - * Used as UpdateRuleType. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_UPDATE_FULL_CORRECTION_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_UPDATE_FULL_CORRECTION_HPP - -#include -#include "atoms.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Full correction approach to update the solution. - * - * UpdateSpan class reoptimize the solution in the span of all current atoms, - * which is used in OMP, which only focus on sparsity. - * - * UpdateFullCorrection class reoptimize the solution in a similar way, however, - * the solutions need to satisfy the constraint that the atom norm has to be - * smaller than or equal to tau. This constraint optimization problem is solved - * by projected gradient method. See Atoms.ProjectedEnhancement(). - * - * Currently only works for function in FuncSq class. - * - */ -class UpdateFullCorrection -{ - public: - /** - * Construct UpdateFullCorrection class. - * - * @param tau atom norm constraint. - * @param stepSize step size used in projected gradient method. - */ - UpdateFullCorrection(const double tau, const double stepSize) : - tau(tau), stepSize(stepSize) - { /* Do nothing. */ } - - /** - * Update rule for FrankWolfe, recalculate the coefficents of of current - * atoms, while satisfying the norm constraint. - * - * @param function function to be optimized. - * @param oldCoords previous solution coords. - * @param s current linear_constr_solution result. - * @param newCoords new output solution coords. - * @param numIter current iteration number. - */ - void Update(FuncSq& function, - const arma::mat& oldCoords, - const arma::mat& s, - arma::mat& newCoords, - const size_t /* numIter */) - { - // Line search, with explicit solution here. - arma::mat v = tau * s - oldCoords; - arma::mat b = function.Vectorb(); - arma::mat A = function.MatrixA(); - double gamma = arma::dot(b - A * oldCoords, A * v); - gamma = gamma / std::pow(arma::norm(A * v, "fro"), 2); - gamma = std::min(gamma, 1.0); - atoms.CurrentCoeffs() = (1.0 - gamma) * atoms.CurrentCoeffs(); - atoms.AddAtom(s, function, gamma * tau); - - // Projected gradient method for enhancement. - atoms.ProjectedGradientEnhancement(function, tau, stepSize); - atoms.RecoverVector(newCoords); - } - - private: - //! Atom norm constraint. - double tau; - - //! Step size in projected gradient method. - double stepSize; - - //! Atoms information. - Atoms atoms; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_linesearch.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_linesearch.hpp deleted file mode 100644 index da08acee7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_linesearch.hpp +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @file update_linesearch.hpp - * @author Chenzhe Diao - * - * Minimize convex function with line search, using secant method. - * In FrankWolfe algorithm, used as UpdateRuleType. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_UPDATE_LINESEARCH_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_UPDATE_LINESEARCH_HPP - -#include -#include - -namespace mlpack { -namespace optimization { - -/** - * Use line search in the update step for FrankWolfe algorithm. That is, take - * \f$ \gamma = arg\min_{\gamma\in [0, 1]} f((1-\gamma)x + \gamma s) \f$. - * The update rule would be: - * \f[ - * x_{k+1} = (1-\gamma) x_k + \gamma s - * \f] - * - */ -class UpdateLineSearch -{ - public: - /** - * Construct the line search update rule. - * - * @param maxIter Max number of iterations in line search. - * @param tolerance Tolerance for termination of line search. - */ - UpdateLineSearch(const size_t maxIterations = 100000, - const double tolerance = 1e-5) : - tolerance(tolerance), maxIterations(maxIterations) - {/* Do nothing */} - - - /** - * Update rule for FrankWolfe, optimize with line search using secant method. - * - * FunctionType template parameters are required. - * This class must implement the following functions: - * - * FunctionType: - * - * double Evaluate(const arma::mat& coordinates); - * Evaluation of the function at specific coordinates. - * - * void Gradient(const arma::mat& coordinates, - * arma::mat& gradient); - * Solve the gradient of the function at specific coordinate, - * returned in gradient. - * - * @param function function to be optimized, - * @param oldCoords previous solution coordinates, one end of line search. - * @param s current linear_constr_solution result, the other end point of - * line search. - * @param newCoords output new solution coords. - * @param numIter current iteration number, not used here. - */ - template - void Update(FunctionType& function, - const arma::mat& oldCoords, - const arma::mat& s, - arma::mat& newCoords, - const size_t /* numIter */) - - { - LineSearch solver(maxIterations, tolerance); - - newCoords = s; - solver.Optimize(function, oldCoords, newCoords); - } - - //! Get the tolerance for termination. - double Tolerance() const {return tolerance;} - //! Modify the tolerance for termination. - double& Tolerance() {return tolerance;} - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - private: - //! Tolerance for convergence. - double tolerance; - - //! Max number of iterations. - size_t maxIterations; -}; // class UpdateLineSearch - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_span.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_span.hpp deleted file mode 100644 index d86e03d37..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/fw/update_span.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file update_span.hpp - * @author Chenzhe Diao - * - * Update method for FrankWolfe algorithm, recalculate the optimal in the span - * of previous solution space. Used as UpdateRuleType. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_FW_UPDATE_SPAN_HPP -#define MLPACK_CORE_OPTIMIZERS_FW_UPDATE_SPAN_HPP - -#include -#include "func_sq.hpp" -#include "atoms.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Recalculate the optimal solution in the span of all previous solution space, - * used as update step for FrankWolfe algorithm. - * - * Currently only works for function in FuncSq class. - */ -class UpdateSpan -{ - public: - /** - * Construct the span update rule. The function to be optimized is input here. - * - * @param function Function to be optimized in FrankWolfe algorithm. - */ - UpdateSpan(const bool isPrune = false) : isPrune(isPrune) - { /* Do nothing. */ } - - /** - * Update rule for FrankWolfe, reoptimize in the span of current - * solution space. - * - * @param function function to be optimized. - * @param oldCoords previous solution coords. - * @param s current linearConstrSolution result. - * @param newCoords output new solution coords. - * @param numIter current iteration number. - */ - void Update(FuncSq& function, - const arma::mat& oldCoords, - const arma::mat& s, - arma::mat& newCoords, - const size_t /* numIter */) - { - // Add new atom into soluton space. - atoms.AddAtom(s, function); - - // Reoptimize the solution in the current space. - arma::vec b = function.Vectorb(); - atoms.CurrentCoeffs() = solve(function.MatrixA() * atoms.CurrentAtoms(), b); - - // x has coords of only the current atoms, recover the solution - // to the original size. - atoms.RecoverVector(newCoords); - - // Prune the support. - if (isPrune) - { - double oldF = function.Evaluate(oldCoords); - double F = 0.25 * oldF + 0.75 * function.Evaluate(newCoords); - atoms.PruneSupport(F, function); - atoms.RecoverVector(newCoords); - } - } - - private: - //! Atoms information. - Atoms atoms; - - //! Flag for support prune step. - bool isPrune; -}; // class UpdateSpan - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/gradient_descent.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/gradient_descent.hpp deleted file mode 100644 index fb74117a0..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/gradient_descent.hpp +++ /dev/null @@ -1,133 +0,0 @@ -/** - * @file gradient_descent.hpp - * @author Sumedh Ghaisas - * - * Simple Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_GRADIENT_DESCENT_GRADIENT_DESCENT_HPP -#define MLPACK_CORE_OPTIMIZERS_GRADIENT_DESCENT_GRADIENT_DESCENT_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Gradient Descent is a technique to minimize a function. To find a local - * minimum of a function using gradient descent, one takes steps proportional - * to the negative of the gradient of the function at the current point, - * producing the following update scheme: - * - * \f[ - * A_{j + 1} = A_j + \alpha \nabla F(A) - * \f] - * - * where \f$ \alpha \f$ is a parameter which specifies the step size. \f$ F \f$ - * is the function being optimized. The algorithm continues until \f$ j - * \f$ reaches the maximum number of iterations---or when an update produces - * an improvement within a certain tolerance \f$ \epsilon \f$. That is, - * - * \f[ - * | F(A_{j + 1}) - F(A_j) | < \epsilon. - * \f] - * - * The parameter \f$\epsilon\f$ is specified by the tolerance parameter to the - * constructor. - * - * For Gradient Descent to work, a FunctionType template parameter is required. - * This class must implement the following function: - * - * double Evaluate(const arma::mat& coordinates); - * void Gradient(const arma::mat& coordinates, - * arma::mat& gradient); - */ -class GradientDescent -{ - public: - /** - * Construct the Gradient Descent optimizer with the given function and - * parameters. The defaults here are not necessarily good for the given - * problem, so it is suggested that the values used be tailored to the task - * at hand. - * - * @param function Function to be optimized (minimized). - * @param stepSize Step size for each iteration. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - */ - GradientDescent(const double stepSize = 0.01, - const size_t maxIterations = 100000, - const double tolerance = 1e-5); - - /** - * Optimize the given function using gradient descent. The given starting - * point will be modified to store the finishing point of the algorithm, and - * the final objective value is returned. - * - * @tparam FunctionType Type of the function to optimize. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(FunctionType& function, arma::mat& iterate); - - /** - * Assert all dimensions are numeric and optimize the given function using - * gradient descent. The given starting point will be modified to store the - * finishing point of the algorithm, and the final objective value is - * returned. - * - * This overload is intended to be used primarily by the hyper-parameter - * tuning module. - * - * @tparam FunctionType Type of the function to optimize. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @param datasetInfo Type information for each dimension of the dataset. - * @return Objective value of the final point. - */ - template - double Optimize( - FunctionType& function, - arma::mat& iterate, - data::DatasetMapper& datasetInfo); - - //! Get the step size. - double StepSize() const { return stepSize; } - //! Modify the step size. - double& StepSize() { return stepSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - private: - //! The step size for each example. - double stepSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The tolerance for termination. - double tolerance; -}; - -} // namespace optimization -} // namespace mlpack - -#include "gradient_descent_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/gradient_descent_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/gradient_descent_impl.hpp deleted file mode 100644 index de8620c4e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/gradient_descent_impl.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @file gradient_descent_impl.hpp - * @author Sumedh Ghaisas - * - * Simple gradient descent implementation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_GRADIENT_DESCENT_GRADIENT_DESCENT_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_GRADIENT_DESCENT_GRADIENT_DESCENT_IMPL_HPP - -// In case it hasn't been included yet. -#include "gradient_descent.hpp" - -#include - -namespace mlpack { -namespace optimization { - -//! Optimize the function (minimize). -template -double GradientDescent::Optimize( - FunctionType& function, arma::mat& iterate) -{ - // Use the Function<> wrapper type to provide additional functionality. - typedef Function FullFunctionType; - FullFunctionType& f(static_cast(function)); - - // Make sure we have the methods that we need. - traits::CheckFunctionTypeAPI(); - - // To keep track of where we are and how things are going. - double overallObjective = std::numeric_limits::max(); - double lastObjective = std::numeric_limits::max(); - - // Now iterate! - arma::mat gradient(iterate.n_rows, iterate.n_cols); - for (size_t i = 1; i != maxIterations; ++i) - { - overallObjective = f.EvaluateWithGradient(iterate, gradient); - - // Output current objective function. - Log::Info << "Gradient Descent: iteration " << i << ", objective " - << overallObjective << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "Gradient Descent: converged to " << overallObjective - << "; terminating" << " with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "Gradient Descent: minimized within tolerance " - << tolerance << "; " << "terminating optimization." << std::endl; - return overallObjective; - } - - // Reset the counter variables. - lastObjective = overallObjective; - - // And update the iterate. - iterate -= stepSize * gradient; - } - - Log::Info << "Gradient Descent: maximum iterations (" << maxIterations - << ") reached; " << "terminating optimization." << std::endl; - return overallObjective; -} - -template -double GradientDescent::Optimize( - FunctionType& function, - arma::mat& iterate, - data::DatasetMapper& datasetInfo) -{ - if (datasetInfo.Dimensionality() != iterate.n_rows) - { - std::ostringstream oss; - oss << "GradientDescent::Optimize(): expected information about " - << iterate.n_rows << " dimensions in datasetInfo, but found about " - << datasetInfo.Dimensionality() << std::endl; - throw std::invalid_argument(oss.str()); - } - - for (size_t i = 0; i < datasetInfo.Dimensionality(); ++i) - { - if (datasetInfo.Type(i) != data::Datatype::numeric) - { - std::ostringstream oss; - oss << "GradientDescent::Optimize(): the dimension " << i - << "is not numeric" << std::endl; - throw std::invalid_argument(oss.str()); - } - } - - return Optimize(function, iterate); -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/test_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/test_function.hpp deleted file mode 100644 index 63d4a62e5..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/gradient_descent/test_function.hpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @file test_function.hpp - * @author Sumedh Ghaisas - * - * Very simple test function for SGD. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_GD_TEST_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_GD_TEST_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -//! Very, very simple test function which is the composite of three other -//! functions. The gradient is not very steep far away from the optimum, so a -//! larger step size may be required to optimize it in a reasonable number of -//! iterations. -class GDTestFunction -{ - public: - //! Nothing to do for the constructor. - GDTestFunction() { } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("1; 3; 2"); } - - //! Evaluate a function. - double Evaluate(const arma::mat& coordinates) const; - - //! Evaluate the gradient of a function. - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/grid_search/grid_search.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/grid_search/grid_search.hpp deleted file mode 100644 index a584237f6..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/grid_search/grid_search.hpp +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file grid_search.hpp - * @author Kirill Mishchenko - * - * Grid-search optimization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_GRID_SEARCH_GRID_SEARCH_HPP -#define MLPACK_CORE_OPTIMIZERS_GRID_SEARCH_GRID_SEARCH_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * An optimizer that finds the minimum of a given function by iterating through - * points on a multidimensional grid. - * - * For GridSearch to work, a FunctionType template parameter is required. This - * class must implement the following function: - * - * double Evaluate(const arma::mat& coordinates); - */ -class GridSearch -{ - public: - /** - * Optimize (minimize) the given function by iterating through the all - * possible combinations of values for the parameters specified in - * datasetInfo. - * - * @param function Function to optimize. - * @param bestParameters Variable for storing results. - * @param datasetInfo Type information for each dimension of the dataset. It - * should store possible values for each parameter. - * @return Objective value of the final point. - */ - template - double Optimize( - FunctionType& function, - arma::mat& bestParameters, - data::DatasetMapper& datasetInfo); - - private: - /** - * Iterate through the last (parameterValueCollections.size() - i) dimensions - * of the grid and change the arguments bestObjective and bestParameters if - * there is something better. The values for the first i dimensions - * (parameters) are specified in the first i rows of the currentParameters - * argument. - */ - template - void Optimize( - FunctionType& function, - double& bestObjective, - arma::mat& bestParameters, - arma::vec& currentParameters, - data::DatasetMapper& datasetInfo, - size_t i); -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation -#include "grid_search_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/grid_search/grid_search_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/grid_search/grid_search_impl.hpp deleted file mode 100644 index b0873b541..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/grid_search/grid_search_impl.hpp +++ /dev/null @@ -1,89 +0,0 @@ -/** - * @file grid_search_impl.hpp - * @author Kirill Mishchenko - * - * Implementation of the grid-search optimization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_GRID_SEARCH_GRID_SEARCH_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_GRID_SEARCH_GRID_SEARCH_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace optimization { - -template -double GridSearch::Optimize( - FunctionType& function, - arma::mat& bestParameters, - data::DatasetMapper& datasetInfo) -{ - for (size_t i = 0; i < datasetInfo.Dimensionality(); ++i) - { - if (datasetInfo.Type(i) != data::Datatype::categorical) - { - std::ostringstream oss; - oss << "GridSearch::Optimize(): the dimension " << i - << "is not categorical" << std::endl; - throw std::invalid_argument(oss.str()); - } - } - - double bestObjective = std::numeric_limits::max(); - bestParameters = arma::mat(datasetInfo.Dimensionality(), 1); - arma::vec currentParameters = arma::vec(datasetInfo.Dimensionality()); - - /* Initialize best parameters for the case (very unlikely though) when no set - * of parameters gives an objective value better than - * std::numeric_limits::max() */ - for (size_t i = 0; i < datasetInfo.Dimensionality(); ++i) - bestParameters(i, 0) = datasetInfo.UnmapString(0, i); - - Optimize(function, bestObjective, bestParameters, currentParameters, - datasetInfo, 0); - - return bestObjective; -} - -template -void GridSearch::Optimize( - FunctionType& function, - double& bestObjective, - arma::mat& bestParameters, - arma::vec& currentParameters, - data::DatasetMapper& datasetInfo, - size_t i) -{ - // Make sure we have the methods that we need. - traits::CheckNonDifferentiableFunctionTypeAPI(); - - if (i < datasetInfo.Dimensionality()) - { - for (size_t j = 0; j < datasetInfo.NumMappings(i); ++j) - { - currentParameters(i) = datasetInfo.UnmapString(j, i); - Optimize(function, bestObjective, bestParameters, currentParameters, - datasetInfo, i + 1); - } - } - else - { - double objective = function.Evaluate(currentParameters); - if (objective < bestObjective) - { - bestObjective = objective; - bestParameters = currentParameters; - } - } -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/iqn/iqn.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/iqn/iqn.hpp deleted file mode 100644 index c719852f4..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/iqn/iqn.hpp +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @file iqn.hpp - * @author Marcus Edel - * - * Definition of an incremental Quasi-Newton with local superlinear - * convergence rate as proposed by A. Mokhtari et al. in "IQN: An Incremental - * Quasi-Newton Method with Local Superlinear Convergence Rate". - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_IQN_IQN_HPP -#define MLPACK_CORE_OPTIMIZERS_IQN_IQN_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * IQN is a technique for minimizing a function which - * can be expressed as a sum of other functions. That is, suppose we have - * - * \f[ - * f(A) = \sum_{i = 0}^{n} f_i(A) - * \f] - * IQN is the first stochastic quasi- Newton method proven to converge - * superlinearly in a local neighborhood of the optimal solution. - * - * For more information, please refer to: - * - * @code - * @misc{1106.5730, - * author = {Mokhtari, Aryan and Eisen, Mark and Ribeiro, Alejandro}, - * title = {IQN: An Incremental Quasi-Newton Method with Local Superlinear - * Convergence Rate}, - * year = {2017}, - * eprint = {arXiv:1702.00709}, - * } - * @endcode - * - * This class is useful for data-dependent functions whose objective function - * can be expressed as a sum of objective functions operating on an individual - * point. Then, IQN considers the gradient of the objective function operating - * on an individual point in its update of \f$ A \f$. - * - * For IQN to work, the class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, const size_t i); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - */ -class IQN -{ - public: - /** - * Construct the IQN optimizer with the given function and parameters. The - * defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Size of each batch. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - */ - IQN(const double stepSize = 0.01, - const size_t batchSize = 10, - const size_t maxIterations = 100000, - const double tolerance = 1e-5); - - /** - * Optimize the given function using IQN. The given starting point will be - * modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the step size. - double StepSize() const { return stepSize; } - //! Modify the step size. - double& StepSize() { return stepSize; } - - //! Get the batch size. - size_t BatchSize() const { return batchSize; } - //! Modify the batch size. - size_t& BatchSize() { return batchSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - private: - //! The step size for each example. - double stepSize; - - //! The size of each batch. - size_t batchSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The tolerance for termination. - double tolerance; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "iqn_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/iqn/iqn_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/iqn/iqn_impl.hpp deleted file mode 100644 index 21b04ac46..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/iqn/iqn_impl.hpp +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @file iqn_impl.hpp - * @author Marcus Edel - * - * Implementation of an incremental Quasi-Newton with local superlinear - * convergence rate as proposed by A. Mokhtari et al. in "IQN: An Incremental - * Quasi-Newton Method with Local Superlinear Convergence Rate". - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_IQN_IQN_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_IQN_IQN_IMPL_HPP - -// In case it hasn't been included yet. -#include "iqn.hpp" - -#include - -namespace mlpack { -namespace optimization { - -IQN::IQN(const double stepSize, - const size_t batchSize, - const size_t maxIterations, - const double tolerance) : - stepSize(stepSize), - batchSize(batchSize), - maxIterations(maxIterations), - tolerance(tolerance) -{ /* Nothing to do. */ } - -//! Optimize the function (minimize). -template -double IQN::Optimize(DecomposableFunctionType& function, arma::mat& iterate) -{ - traits::CheckDecomposableFunctionTypeAPI(); - - // Find the number of functions. - const size_t numFunctions = function.NumFunctions(); - size_t numBatches = numFunctions / batchSize; - if (numFunctions % batchSize != 0) - ++numBatches; // Capture last few. - - // To keep track of where we are and how things are going. - double overallObjective = 0; - - arma::cube y(iterate.n_rows, iterate.n_cols, numBatches); - arma::cube t(iterate.n_elem, 1, numBatches); - arma::cube Q(iterate.n_elem, iterate.n_elem, numBatches); - arma::mat initialIterate = arma::randn(iterate.n_rows, iterate.n_cols); - arma::mat B = arma::eye(iterate.n_elem, iterate.n_elem); - - arma::mat g = arma::zeros(iterate.n_rows, iterate.n_cols); - for (size_t i = 0, f = 0; i < numFunctions; f++) - { - // Find the effective batch size (the last batch may be smaller). - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - i); - - t.slice(f) = arma::mat(initialIterate.memptr(), iterate.n_elem, - 1, false, false); - function.Gradient(initialIterate, i, y.slice(f), effectiveBatchSize); - - Q.slice(f).eye(); - g += y.slice(f); - y.slice(f) /= (double) effectiveBatchSize; - - i += effectiveBatchSize; - } - g /= numFunctions; - - arma::mat gradient(iterate.n_rows, iterate.n_cols); - arma::mat u = t.slice(0); - - // Convenience alias to avoid multiple use of arma::vectorise. - arma::mat iterateVec = arma::mat(iterate.memptr(), iterate.n_elem, - 1, false, false); - arma::mat gVec = arma::mat(g.memptr(), iterate.n_elem, 1, false, false); - - for (size_t i = 1; i != maxIterations; ++i) - { - for (size_t j = 0, f = 0; f < numFunctions; j++) - { - // Cyclicly iterating through the number of functions. - const size_t it = ((j + 1) % numBatches); - - // Find the effective batch size (the last batch may be smaller). - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - - it * batchSize); - - if (arma::norm(iterateVec - t.slice(it)) > 0) - { - function.Gradient(iterate, it * batchSize, gradient, - effectiveBatchSize); - gradient /= effectiveBatchSize; - - const arma::mat s = iterateVec - t.slice(it); - const arma::mat yy = arma::vectorise(gradient - y.slice(it)); - - const arma::mat stochasticHessian = Q.slice(it) + yy * yy.t() / - arma::as_scalar(yy.t() * s) - Q.slice(it) * s * s.t() * - Q.slice(it) / arma::as_scalar(s.t() * Q.slice(it) * s); - - // Update aggregate Hessian approximation. - B += (1.0 / numBatches) * (stochasticHessian - Q.slice(it)); - - // Update aggregate Hessian-variable product. - u += (1.0 / numBatches) * (stochasticHessian * iterateVec - - Q.slice(it) * t.slice(it)); - - // Update aggregate gradient. - g += (1.0 / numBatches) * (gradient - y.slice(it)); - - // Update the function information tables. - Q.slice(it) = stochasticHessian; - y.slice(it) = gradient; - t.slice(it) = iterateVec; - - iterateVec = stepSize * B.i() * (u - gVec) + (1 - stepSize) * - iterateVec; - } - - f += effectiveBatchSize; - } - - overallObjective = 0; - for (size_t f = 0; f < numFunctions; f += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - f); - overallObjective += function.Evaluate(iterate, f, effectiveBatchSize); - } - overallObjective /= numFunctions; - - // Output current objective function. - Log::Info << "IQN: iteration " << i << ", objective " << overallObjective - << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "IQN: converged to " << overallObjective << "; terminating" - << " with failure. Try a smaller step size?" << std::endl; - return overallObjective; - } - - if (overallObjective < tolerance) - { - Log::Info << "IQN: minimized within tolerance " << tolerance << "; " - << "terminating optimization." << std::endl; - return overallObjective; - } - } - - Log::Info << "IQN: maximum iterations (" << maxIterations << ") reached; " - << "terminating optimization." << std::endl; - - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/katyusha/katyusha.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/katyusha/katyusha.hpp deleted file mode 100644 index 2d2d68cc7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/katyusha/katyusha.hpp +++ /dev/null @@ -1,184 +0,0 @@ -/** - * @file katyusha.hpp - * @author Marcus Edel - * - * Katyusha a direct, primal-only stochastic gradient method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_KATYUSHA_KATYUSHA_HPP -#define MLPACK_CORE_OPTIMIZERS_KATYUSHA_KATYUSHA_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Katyusha is a direct, primal-only stochastic gradient method which uses a - * "negative momentum" on top of Nesterov’s momentum. - * - * For more information, see the following. - * - * @code - * @inproceedings{Allen-Zhu2016, - * author = {{Allen-Zhu}, Z.}, - * title = {Katyusha: The First Direct Acceleration of Stochastic Gradient - * Methods}, - * booktitle = {Proceedings of the 49th Annual ACM SIGACT Symposium on Theory - * of Computing}, - * pages = {1200--1205}, - * publisher = {ACM}, - * year = {2017}, - * series = {STOC 2017}, - * } - * @endcode - * - * For Katyusha to work, a DecomposableFunctionType template parameter - * is required. This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - * - * @tparam proximal Whether the proximal update should be used or not. - */ -template -class KatyushaType -{ - public: - /** - * Construct the Katyusha optimizer with the given function and parameters. - * The defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param convexity The regularization parameter. - * @param lipschitz The Lipschitz constant. - * @param batchSize Batch size to use for each step. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param innerIterations The number of inner iterations allowed (0 means - * n / batchSize). Note that the full gradient is only calculated in - * the outer iteration. - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - */ - KatyushaType(const double convexity = 1.0, - const double lipschitz = 10.0, - const size_t batchSize = 32, - const size_t maxIterations = 1000, - const size_t innerIterations = 0, - const double tolerance = 1e-5, - const bool shuffle = true); - - /** - * Optimize the given function using Katyusha. The given starting point will - * be modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the convexity parameter. - double Convexity() const { return convexity; } - //! Modify the convexity parameter. - double& Convexity() { return convexity; } - - //! Get the lipschitz parameter. - double Lipschitz() const { return lipschitz; } - //! Modify the lipschitz parameter. - double& Lipschitz() { return lipschitz; } - - //! Get the batch size. - size_t BatchSize() const { return batchSize; } - //! Modify the batch size. - size_t& BatchSize() { return batchSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the maximum number of iterations (0 indicates default n / b). - size_t InnerIterations() const { return innerIterations; } - //! Modify the maximum number of iterations (0 indicates default n / b). - size_t& InnerIterations() { return innerIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return shuffle; } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return shuffle; } - - private: - //! The convexity regularization term. - double convexity; - - //! The lipschitz constant. - double lipschitz; - - //! The batch size for processing. - size_t batchSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The maximum number of allowed inner iterations per epoch. - size_t innerIterations; - - //! The tolerance for termination. - double tolerance; - - //! Controls whether or not the individual functions are shuffled when - //! iterating. - bool shuffle; -}; - -// Convenience typedefs. - -/** - * Katyusha using the standard update step. - */ -using Katyusha = KatyushaType; - -/** - * Katyusha using the proximal update step. - */ -using KatyushaProximal = KatyushaType; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "katyusha_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/katyusha/katyusha_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/katyusha/katyusha_impl.hpp deleted file mode 100644 index 274c5b7c3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/katyusha/katyusha_impl.hpp +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @file katyusha_impl.hpp - * @author Marcus Edel - * - * Implementation of Katyusha a direct, primal-only stochastic gradient method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_KATYUSHA_KATYUSHA_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_KATYUSHA_KATYUSHA_IMPL_HPP - -// In case it hasn't been included yet. -#include "katyusha.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -KatyushaType::KatyushaType( - const double convexity, - const double lipschitz, - const size_t batchSize, - const size_t maxIterations, - const size_t innerIterations, - const double tolerance, - const bool shuffle) : - convexity(convexity), - lipschitz(lipschitz), - batchSize(batchSize), - maxIterations(maxIterations), - innerIterations(innerIterations), - tolerance(tolerance), - shuffle(shuffle) -{ /* Nothing to do. */ } - -//! Optimize the function (minimize). -template -template -double KatyushaType::Optimize( - DecomposableFunctionType& function, - arma::mat& iterate) -{ - traits::CheckDecomposableFunctionTypeAPI(); - - // Find the number of functions to use. - const size_t numFunctions = function.NumFunctions(); - - // Set epoch length to n / b if the user asked for. - if (innerIterations == 0) - innerIterations = numFunctions; - - // Find the number of batches. - size_t numBatches = innerIterations / batchSize; - if (numFunctions % batchSize != 0) - ++numBatches; // Capture last few. - - const double tau1 = std::min(0.5, - std::sqrt(batchSize * convexity / (3.0 * lipschitz))); - const double tau2 = 0.5; - const double alpha = 1.0 / (3.0 * tau1 * lipschitz); - const double r = 1.0 + std::min(alpha * convexity, 1.0 / - (4.0 / innerIterations)); - - // sum_{j=0}^{m-1} 1 + std::min(alpha * convexity, 1 / (4 * m)^j). - double normalizer = 1; - for (size_t i = 0; i < numBatches; i++) - { - normalizer = r * (normalizer + 1.0); - } - normalizer = 1.0 / normalizer; - - // To keep track of where we are and how things are going. - double overallObjective = 0; - double lastObjective = DBL_MAX; - - // Now iterate! - arma::mat gradient(iterate.n_rows, iterate.n_cols); - arma::mat fullGradient(iterate.n_rows, iterate.n_cols); - arma::mat gradient0(iterate.n_rows, iterate.n_cols); - - arma::mat iterate0 = iterate; - arma::mat y = iterate; - arma::mat z = iterate; - arma::mat w = arma::zeros(iterate.n_rows, iterate.n_cols); - - const size_t actualMaxIterations = (maxIterations == 0) ? - std::numeric_limits::max() : maxIterations; - for (size_t i = 0; i < actualMaxIterations; ++i) - { - // Calculate the objective function. - overallObjective = 0; - for (size_t f = 0; f < numFunctions; f += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - f); - overallObjective += function.Evaluate(iterate0, f, effectiveBatchSize); - } - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "Katyusha: converged to " << overallObjective - << "; terminating with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "Katyusha: minimized within tolerance " << tolerance - << "; terminating optimization." << std::endl; - return overallObjective; - } - - lastObjective = overallObjective; - - // Compute the full gradient. - size_t effectiveBatchSize = std::min(batchSize, numFunctions); - function.Gradient(iterate, 0, fullGradient, effectiveBatchSize); - for (size_t f = effectiveBatchSize; f < numFunctions; - /* incrementing done manually */) - { - // Find the effective batch size (the last batch may be smaller). - effectiveBatchSize = std::min(batchSize, numFunctions - f); - - function.Gradient(iterate0, f, gradient, effectiveBatchSize); - fullGradient += gradient; - - f += effectiveBatchSize; - } - fullGradient /= (double) numFunctions; - - // To keep track of where we are and how things are going. - double cw = 1; - w.zeros(); - - for (size_t f = 0, currentFunction = 0; f < innerIterations; - /* incrementing done manually */) - { - // Is this iteration the start of a sequence? - if ((currentFunction % numFunctions) == 0) - { - currentFunction = 0; - - // Determine order of visitation. - if (shuffle) - function.Shuffle(); - } - - // Find the effective batch size (the last batch may be smaller). - effectiveBatchSize = std::min(batchSize, numFunctions - currentFunction); - iterate = tau1 * z + tau2 * iterate0 + (1 - tau1 - tau2) * y; - - // Calculate variance reduced gradient. - function.Gradient(iterate, currentFunction, gradient, - effectiveBatchSize); - function.Gradient(iterate0, currentFunction, gradient0, - effectiveBatchSize); - - // By the minimality definition of z_{k + 1}, we have that: - // z_{k+1} − z_k + \alpha * \sigma_{k+1} + \alpha g = 0. - arma::mat zNew = z - alpha * (fullGradient + (gradient - gradient0) / - (double) batchSize); - - // Proximal update, choose between Option I and Option II. Shift relative - // to the Lipschitz constant or take a constant step using the given step - // size. - if (Proximal) - { - // yk = x0 − 1 / (3L) * \delta1, k = 1 - // yk = x0 − 1 / (3L) * \delta2 - ((1 - tau) / (3L)) + tau * alpha) - // * \delta1, k = 2 - // yk = x0 − 1 / (3L) * \delta3 - ((1 - tau) / (3L)) + tau * alpha) - // * \delta2 - ((1-tau)^2 / (3L) + (1 - (1 - tau)^2) * alpha) * \delta1, - // k = 3. - y = iterate + 1.0 / (3.0 * lipschitz) * w; - } - else - { - y = iterate + tau1 * (zNew - z); - } - - z = std::move(zNew); - - // sum_{j=0}^{m-1} 1 + std::min(alpha * convexity, 1 / (4 * m)^j * ys). - w += cw * iterate; - cw *= r; - - currentFunction += effectiveBatchSize; - f += effectiveBatchSize; - } - iterate0 = normalizer * w; - } - - Log::Info << "Katyusha: maximum iterations (" << maxIterations << ") reached" - << "; terminating optimization." << std::endl; - - // Calculate final objective. - overallObjective = 0; - for (size_t i = 0; i < numFunctions; i += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - i); - overallObjective += function.Evaluate(iterate, i, effectiveBatchSize); - } - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/lbfgs/lbfgs.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/lbfgs/lbfgs.hpp deleted file mode 100644 index 2eb586b48..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/lbfgs/lbfgs.hpp +++ /dev/null @@ -1,228 +0,0 @@ -/** - * @file lbfgs.hpp - * @author Dongryeol Lee - * @author Ryan Curtin - * - * The generic L-BFGS optimizer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_LBFGS_LBFGS_HPP -#define MLPACK_CORE_OPTIMIZERS_LBFGS_LBFGS_HPP - -#include -#include - -namespace mlpack { -namespace optimization { - -/** - * The generic L-BFGS optimizer, which uses a back-tracking line search - * algorithm to minimize a function. The parameters for the algorithm (number - * of memory points, maximum step size, and so forth) are all configurable via - * either the constructor or standalone modifier functions. A function which - * can be optimized by this class's Optimize() method must implement the - * following methods: - * - * - a default constructor - * - double Evaluate(const arma::mat& coordinates); - * - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - * - arma::mat& GetInitialPoint(); - */ -class L_BFGS -{ - public: - /** - * Initialize the L-BFGS object. There are many parameters that can be set - * for the optimization, but default values are given for each of them. - * - * @param numBasis Number of memory points to be stored (default 5). - * @param maxIterations Maximum number of iterations for the optimization - * (0 means no limit and may run indefinitely). - * @param armijoConstant Controls the accuracy of the line search routine for - * determining the Armijo condition. - * @param wolfe Parameter for detecting the Wolfe condition. - * @param minGradientNorm Minimum gradient norm required to continue the - * optimization. - * @param maxLineSearchTrials The maximum number of trials for the line search - * (before giving up). - * @param minStep The minimum step of the line search. - * @param maxStep The maximum step of the line search. - */ - L_BFGS(const size_t numBasis = 10, /* same default as scipy */ - const size_t maxIterations = 10000, /* many but not infinite */ - const double armijoConstant = 1e-4, - const double wolfe = 0.9, - const double minGradientNorm = 1e-6, - const double factr = 1e-15, - const size_t maxLineSearchTrials = 50, - const double minStep = 1e-20, - const double maxStep = 1e20); - - /** - * Return the point where the lowest function value has been found. - * - * @return arma::vec representing the point and a double with the function - * value at that point. - */ - const std::pair& MinPointIterate() const; - - /** - * Use L-BFGS to optimize the given function, starting at the given iterate - * point and finding the minimum. The maximum number of iterations is set in - * the constructor (or with MaxIterations()). Alternately, another overload - * is provided which takes a maximum number of iterations as a parameter. The - * given starting point will be modified to store the finishing point of the - * algorithm, and the final objective value is returned. - * - * @tparam FunctionType Type of the function to be optimized. - * @param function Function to optimize; must have Evaluate() and Gradient(). - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(FunctionType& function, arma::mat& iterate); - - //! Get the memory size. - size_t NumBasis() const { return numBasis; } - //! Modify the memory size. - size_t& NumBasis() { return numBasis; } - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - //! Get the Armijo condition constant. - double ArmijoConstant() const { return armijoConstant; } - //! Modify the Armijo condition constant. - double& ArmijoConstant() { return armijoConstant; } - - //! Get the Wolfe parameter. - double Wolfe() const { return wolfe; } - //! Modify the Wolfe parameter. - double& Wolfe() { return wolfe; } - - //! Get the minimum gradient norm. - double MinGradientNorm() const { return minGradientNorm; } - //! Modify the minimum gradient norm. - double& MinGradientNorm() { return minGradientNorm; } - - //! Get the factr value. - double Factr() const { return factr; } - //! Modify the factr value. - double& Factr() { return factr; } - - //! Get the maximum number of line search trials. - size_t MaxLineSearchTrials() const { return maxLineSearchTrials; } - //! Modify the maximum number of line search trials. - size_t& MaxLineSearchTrials() { return maxLineSearchTrials; } - - //! Return the minimum line search step size. - double MinStep() const { return minStep; } - //! Modify the minimum line search step size. - double& MinStep() { return minStep; } - - //! Return the maximum line search step size. - double MaxStep() const { return maxStep; } - //! Modify the maximum line search step size. - double& MaxStep() { return maxStep; } - - private: - //! Size of memory for this L-BFGS optimizer. - size_t numBasis; - //! Maximum number of iterations. - size_t maxIterations; - //! Parameter for determining the Armijo condition. - double armijoConstant; - //! Parameter for detecting the Wolfe condition. - double wolfe; - //! Minimum gradient norm required to continue the optimization. - double minGradientNorm; - //! Minimum relative function value decrease to continue the optimization. - double factr; - //! Maximum number of trials for the line search. - size_t maxLineSearchTrials; - //! Minimum step of the line search. - double minStep; - //! Maximum step of the line search. - double maxStep; - - /** - * Calculate the scaling factor, gamma, which is used to scale the Hessian - * approximation matrix. See method M3 in Section 4 of Liu and Nocedal - * (1989). - * - * @return The calculated scaling factor. - */ - double ChooseScalingFactor(const size_t iterationNum, - const arma::mat& gradient, - const arma::cube& s, - const arma::cube& y); - - /** - * Perform a back-tracking line search along the search direction to - * calculate a step size satisfying the Wolfe conditions. The parameter - * iterate will be modified if the method is successful. - * - * @param functionValue Value of the function at the initial point - * @param iterate The initial point to begin the line search from - * @param gradient The gradient at the initial point - * @param searchDirection A vector specifying the search direction - * @param stepSize Variable the calculated step size will be stored in - * - * @return false if no step size is suitable, true otherwise. - */ - template - bool LineSearch(FunctionType& function, - double& functionValue, - arma::mat& iterate, - arma::mat& gradient, - arma::mat& newIterateTmp, - const arma::mat& searchDirection); - - /** - * Find the L-BFGS search direction. - * - * @param gradient The gradient at the current point - * @param iteration_num The iteration number - * @param scaling_factor Scaling factor to use (see ChooseScalingFactor_()) - * @param search_direction Vector to store search direction in - */ - void SearchDirection(const arma::mat& gradient, - const size_t iterationNum, - const double scalingFactor, - const arma::cube& s, - const arma::cube& y, - arma::mat& searchDirection); - - /** - * Update the y and s matrices, which store the differences - * between the iterate and old iterate and the differences between the - * gradient and the old gradient, respectively. - * - * @param iterationNum Iteration number - * @param iterate Current point - * @param oldIterate Point at last iteration - * @param gradient Gradient at current point (iterate) - * @param oldGradient Gradient at last iteration point (oldIterate) - */ - void UpdateBasisSet(const size_t iterationNum, - const arma::mat& iterate, - const arma::mat& oldIterate, - const arma::mat& gradient, - const arma::mat& oldGradient, - arma::cube& s, - arma::cube& y); -}; - -} // namespace optimization -} // namespace mlpack - -#include "lbfgs_impl.hpp" - -#endif // MLPACK_CORE_OPTIMIZERS_LBFGS_LBFGS_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/lbfgs/lbfgs_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/lbfgs/lbfgs_impl.hpp deleted file mode 100644 index 48618bdae..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/lbfgs/lbfgs_impl.hpp +++ /dev/null @@ -1,271 +0,0 @@ -/** - * @file lbfgs_impl.hpp - * @author Dongryeol Lee (dongryel@cc.gatech.edu) - * @author Ryan Curtin - * - * The implementation of the L_BFGS optimizer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_LBFGS_LBFGS_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_LBFGS_LBFGS_IMPL_HPP - -// In case it hasn't been included yet. -#include "lbfgs.hpp" - -#include - -namespace mlpack { -namespace optimization { - -/** - * Perform a back-tracking line search along the search direction to calculate a - * step size satisfying the Wolfe conditions. - * - * @param functionValue Value of the function at the initial point - * @param iterate The initial point to begin the line search from - * @param gradient The gradient at the initial point - * @param searchDirection A vector specifying the search direction - * @param stepSize Variable the calculated step size will be stored in - * - * @return false if no step size is suitable, true otherwise. - */ -template -bool L_BFGS::LineSearch(FunctionType& function, - double& functionValue, - arma::mat& iterate, - arma::mat& gradient, - arma::mat& newIterateTmp, - const arma::mat& searchDirection) -{ - // Default first step size of 1.0. - double stepSize = 1.0; - - // The initial linear term approximation in the direction of the - // search direction. - double initialSearchDirectionDotGradient = - arma::dot(gradient, searchDirection); - - // If it is not a descent direction, just report failure. - if (initialSearchDirectionDotGradient > 0.0) - { - Log::Warn << "L-BFGS line search direction is not a descent direction " - << "(terminating)!" << std::endl; - return false; - } - - // Save the initial function value. - double initialFunctionValue = functionValue; - - // Unit linear approximation to the decrease in function value. - double linearApproxFunctionValueDecrease = armijoConstant * - initialSearchDirectionDotGradient; - - // The number of iteration in the search. - size_t numIterations = 0; - - // Armijo step size scaling factor for increase and decrease. - const double inc = 2.1; - const double dec = 0.5; - double width = 0; - double bestStepSize = 1.0; - double bestObjective = std::numeric_limits::max(); - - while (true) - { - // Perform a step and evaluate the gradient and the function values at that - // point. - newIterateTmp = iterate; - newIterateTmp += stepSize * searchDirection; - functionValue = function.EvaluateWithGradient(newIterateTmp, gradient); - if (functionValue < bestObjective) - { - bestStepSize = stepSize; - bestObjective = functionValue; - } - numIterations++; - - if (functionValue > initialFunctionValue + stepSize * - linearApproxFunctionValueDecrease) - { - width = dec; - } - else - { - // Check Wolfe's condition. - double searchDirectionDotGradient = arma::dot(gradient, searchDirection); - - if (searchDirectionDotGradient < wolfe * - initialSearchDirectionDotGradient) - { - width = inc; - } - else - { - if (searchDirectionDotGradient > -wolfe * - initialSearchDirectionDotGradient) - { - width = dec; - } - else - { - break; - } - } - } - - // Terminate when the step size gets too small or too big or it - // exceeds the max number of iterations. - const bool cond1 = (stepSize < minStep); - const bool cond2 = (stepSize > maxStep); - const bool cond3 = (numIterations >= maxLineSearchTrials); - if (cond1 || cond2 || cond3) - break; - - // Scale the step size. - stepSize *= width; - } - - // Move to the new iterate. - iterate += bestStepSize * searchDirection; - return true; -} - -/** - * Use L_BFGS to optimize the given function, starting at the given iterate - * point and performing no more than the specified number of maximum iterations. - * The given starting point will be modified to store the finishing point of the - * algorithm. - * - * @param numIterations Maximum number of iterations to perform - * @param iterate Starting point (will be modified) - */ -template -double L_BFGS::Optimize(FunctionType& function, arma::mat& iterate) -{ - // Use the Function<> wrapper to ensure the function has all of the functions - // that we need. - typedef Function FullFunctionType; - FullFunctionType& f = static_cast(function); - - // Check that we have all the functions we will need. - traits::CheckFunctionTypeAPI(); - - // Ensure that the cubes holding past iterations' information are the right - // size. Also set the current best point value to the maximum. - const size_t rows = iterate.n_rows; - const size_t cols = iterate.n_cols; - - arma::mat newIterateTmp(rows, cols); - arma::cube s(rows, cols, numBasis); - arma::cube y(rows, cols, numBasis); - - // The old iterate to be saved. - arma::mat oldIterate; - oldIterate.zeros(iterate.n_rows, iterate.n_cols); - - // Whether to optimize until convergence. - bool optimizeUntilConvergence = (maxIterations == 0); - - // The gradient: the current and the old. - arma::mat gradient(iterate.n_rows, iterate.n_cols, arma::fill::zeros); - arma::mat oldGradient(iterate.n_rows, iterate.n_cols, arma::fill::zeros); - - // The search direction. - arma::mat searchDirection(iterate.n_rows, iterate.n_cols, arma::fill::zeros); - - // The initial function value and gradient. - double functionValue = f.EvaluateWithGradient(iterate, gradient); - double prevFunctionValue = functionValue; - - // The main optimization loop. - for (size_t itNum = 0; optimizeUntilConvergence || (itNum != maxIterations); - ++itNum) - { -#ifdef DEBUG - Log::Debug << "L-BFGS iteration " << itNum << "; objective " - << functionValue << ", gradient norm " << arma::norm(gradient, 2) - << ", " << ((prevFunctionValue - functionValue) / - std::max(std::max(fabs(prevFunctionValue), - fabs(functionValue)), 1.0)) - << "." << std::endl; -#endif - - prevFunctionValue = functionValue; - - // Break when the norm of the gradient becomes too small. - // - // But don't do this on the first iteration to ensure we always take at - // least one descent step. - if (itNum > 0 && (arma::norm(gradient, 2) < minGradientNorm)) - { - Log::Debug << "L-BFGS gradient norm too small (terminating successfully)." - << std::endl; - break; - } - - // Break if the objective is not a number. - if (std::isnan(functionValue)) - { - Log::Warn << "L-BFGS terminated with objective " << functionValue << "; " - << "are the objective and gradient functions implemented correctly?" - << std::endl; - break; - } - - // Choose the scaling factor. - double scalingFactor = ChooseScalingFactor(itNum, gradient, s, y); - - // Build an approximation to the Hessian and choose the search - // direction for the current iteration. - SearchDirection(gradient, itNum, scalingFactor, s, y, searchDirection); - - // Save the old iterate and the gradient before stepping. - oldIterate = iterate; - oldGradient = gradient; - - // Do a line search and take a step. - Timer::Start("line_search"); - if (!LineSearch(f, functionValue, iterate, gradient, newIterateTmp, - searchDirection)) - { - Log::Debug << "Line search failed. Stopping optimization." << std::endl; - break; // The line search failed; nothing else to try. - } - Timer::Stop("line_search"); - - // It is possible that the difference between the two coordinates is zero. - // In this case we terminate successfully. - if (accu(iterate != oldIterate) == 0) - { - Log::Debug << "L-BFGS step size of 0 (terminating successfully)." - << std::endl; - break; - } - - // If we can't make progress on the gradient, then we'll also accept - // a stable function value. - const double denom = std::max( - std::max(fabs(prevFunctionValue), fabs(functionValue)), 1.0); - if ((prevFunctionValue - functionValue) / denom <= factr) - { - Log::Debug << "L-BFGS function value stable (terminating successfully)." - << std::endl; - break; - } - - // Overwrite an old basis set. - UpdateBasisSet(itNum, iterate, oldIterate, gradient, oldGradient, s, y); - } // End of the optimization loop. - - return functionValue; -} - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_LBFGS_LBFGS_IMPL_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/line_search/line_search.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/line_search/line_search.hpp deleted file mode 100644 index bab94c7af..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/line_search/line_search.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file line_search.hpp - * @author Chenzhe Diao - * - * Minimize a function using line search with secant method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_LINE_SEARCH_LINE_SEARCH_HPP -#define MLPACK_CORE_OPTIMIZERS_LINE_SEARCH_LINE_SEARCH_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Find the minimum of a function along the line between two points. - * The solver uses the secant method to find the zero of the derivative of the - * function along the search line. - * - * If the function is convex, the derivative of the function along the search - * line will be nondecreasing, so the minimum always exists. - * If the function is strongly convex, the derivative of the function along the - * search line will be strictly increasing, so the minimum is unique. - */ -class LineSearch -{ - public: - LineSearch(const size_t maxIterations = 100000, - const double tolerance = 1e-5) : - maxIterations(maxIterations), tolerance(tolerance) - {/* Do nothing */ } - - /** - * Line search to minimize function between two points with Secant method, - * that is, to find the zero of Derivative(gamma), where gamma is in [0,1]. - * - * The function is assumed to be convex here, otherwise might not converge. - * - * @param function function to be minimized. - * @param x1 Input one end point. - * @param x2 Input the other end point, also used as output, to store the - * coordinate of the optimal solution. - * @return Minimum solution function value. - */ - template - double Optimize(FunctionType& function, const arma::mat& x1, arma::mat& x2); - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - private: - //! Max number of iterations. - size_t maxIterations; - - //! Tolerance for convergence. - double tolerance; - - /** - * Derivative of the function along the search line. - * - * @param function original function. - * @param x0 starting point. - * @param deltaX distance between two end points. - * @param gamma position of the point in the search line, take in [0, 1]. - * - * @return Derivative of function(x0 + gamma * deltaX) with respect to gamma. - */ - template - double Derivative(FunctionType& function, - const arma::mat& x0, - const arma::mat& deltaX, - const double gamma); -}; // class LineSearch -} // namespace optimization -} // namespace mlpack - -#include "line_search_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/line_search/line_search_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/line_search/line_search_impl.hpp deleted file mode 100644 index c5dc17a7b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/line_search/line_search_impl.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file line_search_impl.hpp - * @author Chenzhe Diao - * - * Implementation of line search with secant method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_LINE_SEARCH_LINE_SEARCH_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_LINE_SEARCH_LINE_SEARCH_IMPL_HPP - -// In case it hasn't been included yet. -#include "line_search.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -double LineSearch::Optimize(FunctionType& function, - const arma::mat& x1, - arma::mat& x2) -{ - typedef Function FullFunctionType; - FullFunctionType& f = static_cast(function); - - // Check that we have all the functions we will need. - traits::CheckFunctionTypeAPI(); - - // Set up the search line, that is, - // find the zero of der(gamma) = Derivative(gamma). - arma::mat deltaX = x2 - x1; - double gamma = 0; - double derivative = Derivative(f, x1, deltaX, 0); - double derivativeNew = Derivative(f, x1, deltaX, 1); - double secant = derivativeNew - derivative; - - if (derivative >= 0.0) // Optimal solution at left endpoint. - { - x2 = x1; - return f.Evaluate(x1); - } - else if (derivativeNew <= 0.0) // Optimal solution at right endpoint. - { - return f.Evaluate(x2); - } - else if (secant < tolerance) // function too flat, just take left endpoint. - { - x2 = x1; - return f.Evaluate(x1); - } - - // Line search by Secant Method. - for (size_t k = 0; k < maxIterations; ++k) - { - // secant should always >=0 for convex function. - if (secant < 0.0) - { - Log::Fatal << "LineSearchSecant: Function is not convex!" << std::endl; - x2 = x1; - return function.Evaluate(x1); - } - - // Solve new gamma. - double gammaNew = gamma - derivative / secant; - gammaNew = std::max(gammaNew, 0.0); - gammaNew = std::min(gammaNew, 1.0); - - // Update secant, gamma and derivative - derivativeNew = Derivative(function, x1, deltaX, gammaNew); - secant = (derivativeNew - derivative) / (gammaNew - gamma); - gamma = gammaNew; - derivative = derivativeNew; - - if (std::fabs(derivative) < tolerance) - { - Log::Info << "LineSearchSecant: minimized within tolerance " - << tolerance << "; " << "terminating optimization." << std::endl; - x2 = (1 - gamma) * x1 + gamma * x2; - return f.Evaluate(x2); - } - } - - Log::Info << "LineSearchSecant: maximum iterations (" << maxIterations - << ") reached; " << "terminating optimization." << std::endl; - - x2 = (1 - gamma) * x1 + gamma * x2; - return f.Evaluate(x2); -} // Optimize - - -//! Derivative of the function along the search line. -template -double LineSearch::Derivative(FunctionType& function, - const arma::mat& x0, - const arma::mat& deltaX, - const double gamma) -{ - arma::mat gradient(x0.n_rows, x0.n_cols); - function.Gradient(x0 + gamma * deltaX, gradient); - return arma::dot(gradient, deltaX); -} - - -} // namespace optimization -} // namespace mlpack -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/decay_policies/constant_step.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/decay_policies/constant_step.hpp deleted file mode 100644 index d8ac6b39a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/decay_policies/constant_step.hpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @file constant_step.hpp - * @author Shikhar Bhardwaj - * - * Constant step size policy for parallel Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_CONSTANT_STEP_HPP -#define MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_CONSTANT_STEP_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Implementation of the ConstantStep stepsize decay policy for parallel SGD. - */ -class ConstantStep -{ - public: - /** - * Member initialization constructor. - * - * The defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. - * - * @param step The intial stepsize to use. - */ - ConstantStep(const double step = 0.01) : step(step) { /* Nothing to do */ } - - /** - * This function is called in each iteration before the gradient update. - * - * @param numEpoch The iteration number for which the stepsize is to be - * calculated. - * @return The step size for the current iteration. - */ - double StepSize(const size_t /* numEpoch */) - { - return step; - } - private: - //! The initial stepsize, which remains unchanged - double step; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/decay_policies/exponential_backoff.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/decay_policies/exponential_backoff.hpp deleted file mode 100644 index f159bb03b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/decay_policies/exponential_backoff.hpp +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @file exponential_backoff.hpp - * @author Shikhar Bhardwaj - * - * Exponential backoff step size decay policy for parallel Stochastic Gradient - * Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_EXP_BACKOFF_HPP -#define MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_EXP_BACKOFF_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Exponential backoff stepsize reduction policy for parallel SGD. - * - * For more information, see the following. - * - * @misc{1106.5730, - * Author = {Feng Niu and Benjamin Recht and Christopher Re and Stephen J. - * Wright}, - * Title = {HOGWILD!: A Lock-Free Approach to Parallelizing Stochastic - * Gradient Descent}, - * Year = {2011}, - * Eprint = {arXiv:1106.5730}, - * } - * - * This stepsize update scheme gives robust 1/k convergence rates to the - * implementation of parallel SGD. - */ -class ExponentialBackoff -{ - public: - /** - * Member initializer constructor to construct the exponential backoff policy - * with the required parameters. - * - * @param firstBackoffEpoch The number of updates to run before the first - * stepsize backoff. - * @param step The initial stepsize(gamma). - * @param beta The reduction factor. This should be a value in range (0, 1). - */ - ExponentialBackoff(const size_t firstBackoffEpoch, - const double step, - const double beta) : - firstBackoffEpoch(firstBackoffEpoch), - cutoffEpoch(firstBackoffEpoch), - step(step), - beta(beta) - { /* Nothing to do. */ } - - /** - * Get the step size for the current gradient update. - * - * @param numEpoch The iteration number of the current update. - * @return The stepsize for the current iteration. - */ - double StepSize(const size_t numEpoch) - { - if (numEpoch >= cutoffEpoch) - { - step *= beta; - cutoffEpoch += firstBackoffEpoch / beta; - } - return step; - } - - private: - //! The first iteration at which the stepsize should be reduced. - size_t firstBackoffEpoch; - - //! The iteration at which the next decay will be performed. - size_t cutoffEpoch; - - //! The initial stepsize. - double step; - - //! The reduction factor, should be in range (0, 1). - double beta; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/parallel_sgd.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/parallel_sgd.hpp deleted file mode 100644 index 7e789b847..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/parallel_sgd.hpp +++ /dev/null @@ -1,151 +0,0 @@ -/** - * @file parallel_sgd.hpp - * @author Shikhar Bhardwaj - * - * Parallel Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_HPP -#define MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_HPP - -#include -#include -#include "decay_policies/constant_step.hpp" - -namespace mlpack { -namespace optimization { - -/** - * An implementation of parallel stochastic gradient descent using the lock-free - * HOGWILD! approach. - * - * For more information, see the following. - * @misc{1106.5730, - * Author = {Feng Niu and Benjamin Recht and Christopher Re and Stephen J. - * Wright}, - * Title = {HOGWILD!: A Lock-Free Approach to Parallelizing Stochastic - * Gradient Descent}, - * Year = {2011}, - * Eprint = {arXiv:1106.5730}, - * } - * - * For Parallel SGD to work, a SparseFunctionType template parameter is - * required. This class must implement the following functions: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, const size_t i); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::sp_mat& gradient); - * - * In these functions the parameter id refers to which individual function (or - * gradient) is being evaluated. In case of a data-dependent function, the id - * would refer to the index of the datapoint(or training example). - * The data is distributed uniformly among the threads made available to the - * program by the OpenMP runtime. - * - * The Gradient function interface is slightly changed from the - * DecomposableFunctionType interface, it takes in a sparse matrix as the - * out-param for the gradient, as ParallelSGD is only expected to be relevant in - * situations where the computed gradient is sparse. - * - * @tparam DecayPolicyType Step size update policy used by parallel SGD - * to update the stepsize after each iteration. - */ -template -class ParallelSGD -{ - public: - /** - * Construct the parallel SGD optimizer to optimize the given function with - * the given parameters. One iteration means one batch of datapoints processed - * by each thread. - * - * The defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. - * - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param threadShareSize Number of datapoints to be processed in one - * iteration by each thread. - * @param tolerance Maximum absolute tolerance to terminate the algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - * @param decayPolicy The step size update policy to use. - */ - ParallelSGD(const size_t maxIterations, - const size_t threadShareSize, - const double tolerance = 1e-5, - const bool shuffle = true, - const DecayPolicyType& decayPolicy = DecayPolicyType()); - - /** - * Optimize the given function using the parallel SGD algorithm. The given - * starting point will be modified to store the finishing point of the - * algorithm, and the value of the loss function at the final point is - * returned. - * - * @tparam SparseFunctionType Type of function to be optimized. - * @param function Function to be optimized(minimized). - * @param iterate Starting point(will be modified). - * @return Objective value at the final point. - */ - template - double Optimize(SparseFunctionType& function, arma::mat& iterate); - - //! Get the maximum number of iterations (0 indicates no limits). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limits). - size_t& MaxIterations() { return maxIterations; } - - //! Get the number of datapoints to be processed in one iteration by each - //! thread. - size_t ThreadShareSize() const { return threadShareSize; } - //! Modify the number of datapoints to be processed in one iteration by each - //! thread. - size_t& ThreadShareSize() { return threadShareSize; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return shuffle; } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return shuffle; } - - //! Get the step size decay policy. - DecayPolicyType& DecayPolicy() const { return decayPolicy; } - //! Modify the step size decay policy. - DecayPolicyType& DecayPolicy() { return decayPolicy; } - - private: - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The number of datapoints to be processed in one iteration by each thread. - size_t threadShareSize; - - //! The tolerance for termination. - double tolerance; - - //! Controls whether or not the individual functions are shuffled when - //! iterating. - bool shuffle; - - //! The step size decay policy. - DecayPolicyType decayPolicy; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "parallel_sgd_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/parallel_sgd_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/parallel_sgd_impl.hpp deleted file mode 100644 index 430854648..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/parallel_sgd_impl.hpp +++ /dev/null @@ -1,137 +0,0 @@ -/** - * @file parallel_sgd_impl.hpp - * @author Shikhar Bhardwaj - * - * Implementation of Parallel Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_IMPL_HPP - -// In case it hasn't been included yet. -#include "parallel_sgd.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -ParallelSGD::ParallelSGD( - const size_t maxIterations, - const size_t threadShareSize, - const double tolerance, - const bool shuffle, - const DecayPolicyType& decayPolicy) : - maxIterations(maxIterations), - threadShareSize(threadShareSize), - tolerance(tolerance), - shuffle(shuffle), - decayPolicy(decayPolicy) -{ /* Nothing to do. */ } - -template -template -double ParallelSGD::Optimize( - SparseFunctionType& function, - arma::mat& iterate) -{ - // Check that we have all the functions that we need. - traits::CheckSparseFunctionTypeAPI(); - - double overallObjective = DBL_MAX; - double lastObjective; - - // The order in which the functions will be visited. - arma::Col visitationOrder = arma::linspace>(0, - (function.NumFunctions() - 1), function.NumFunctions()); - - // Iterate till the objective is within tolerance or the maximum number of - // allowed iterations is reached. If maxIterations is 0, this will iterate - // till convergence. - for (size_t i = 1; i != maxIterations; ++i) - { - // Calculate the overall objective. - lastObjective = overallObjective; - - overallObjective = function.Evaluate(iterate); - - // Output current objective function. - Log::Info << "Parallel SGD: iteration " << i << ", objective " - << overallObjective << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "Parallel SGD: converged to " << overallObjective - << "; terminating with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "SGD: minimized within tolerance " << tolerance << "; " - << "terminating optimization." << std::endl; - return overallObjective; - } - - // Get the stepsize for this iteration - double stepSize = decayPolicy.StepSize(i); - - // Shuffle for uniform sampling of functions by each thread. - if (shuffle) - { - // Determine order of visitation. - std::shuffle(visitationOrder.begin(), visitationOrder.end(), - mlpack::math::randGen); - } - - #pragma omp parallel - { - // Each processor gets a subset of the instances. - // Each subset is of size threadShareSize - size_t threadId = 0; - #ifdef HAS_OPENMP - threadId = omp_get_thread_num(); - #endif - - for (size_t j = threadId * threadShareSize; - j < (threadId + 1) * threadShareSize && j < visitationOrder.n_elem; - ++j) - { - // Each instance affects only some components of the decision variable. - // So the gradient is sparse. - arma::sp_mat gradient; - - // Evaluate the sparse gradient. - function.Gradient(iterate, visitationOrder[j], gradient, 1); - - // Update the decision variable with non-zero components of the - // gradient. - for (size_t i = 0; i < gradient.n_cols; ++i) - { - // Iterate over the non-zero elements. - for (arma::sp_mat::iterator cur = gradient.begin_col(i); - cur != gradient.end_col(i); ++cur) - { - #pragma omp atomic - iterate(cur.row(), i) -= stepSize * (*cur); - } - } - } - } - } - - Log::Info << "\n Parallel SGD terminated with objective : " - << overallObjective << std::endl; - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/sparse_test_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/sparse_test_function.hpp deleted file mode 100644 index 8b2831134..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/parallel_sgd/sparse_test_function.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @file sparse_test_function.hpp - * @author Shikhar Bhardwaj - * - * Sparse test function for Parallel SGD. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_SPARSE_TEST_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PARALLEL_SGD_SPARSE_TEST_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -// A simple test function. Each dimension has a parabola with a -// distinct minimum. Each update is guaranteed to be sparse(only a single -// dimension is updated in the decision variable by each thread). At the end of -// a reasonable number of iterations, each value in the decision variable should -// be at the vertex of the parabola in that dimension. -class SparseTestFunction -{ - public: - //! Set members in the default constructor. - SparseTestFunction() - { - intercepts = arma::vec("20 12 15 100"); - bi = arma::vec("-4 -2 -3 -8"); - } - - //! Return 4 (the number of functions). - size_t NumFunctions() const { return 4; } - - //! Return 4 (the number of features). - size_t NumFeatures() const { return 4; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("0 0 0 0;"); } - - //! Evaluate a function. - double Evaluate(const arma::mat& coordinates, - const size_t i, - const size_t batchSize = 1) const - { - double result = 0.0; - for (size_t j = i; j < i + batchSize; ++j) - { - result += coordinates[j] * coordinates[j] + bi[j] * coordinates[j] + - intercepts[j]; - } - - return result; - } - - //! Evaluate all the functions. - double Evaluate(const arma::mat& coordinates) const - { - double objective = 0.0; - for (size_t i = 0; i < NumFunctions(); ++i) - { - objective += coordinates[i] * coordinates[i] + bi[i] * coordinates[i] + - intercepts[i]; - } - - return objective; - } - - //! Evaluate the gradient of a function. - void Gradient(const arma::mat& coordinates, - const size_t i, - arma::sp_mat& gradient, - const size_t batchSize = 1) const - { - gradient.zeros(arma::size(coordinates)); - for (size_t j = i; j < i + batchSize; ++j) - gradient[j] = 2 * coordinates[j] + bi[j]; - } - - //! Evaluate the gradient of a feature function. - void PartialGradient(const arma::mat& coordinates, - const size_t j, - arma::sp_mat& gradient) const - { - gradient.zeros(arma::size(coordinates)); - gradient[j] = 2 * coordinates[j] + bi[j]; - } - - private: - // Each quadratic polynomial is monic. The intercept and coefficient of the - // first order term is stored. - - //! The vector storing the intercepts - arma::vec intercepts; - - //! The vector having coefficients of the first order term - arma::vec bi; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/booth_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/booth_function.hpp deleted file mode 100644 index 495099baa..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/booth_function.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file booth_function.hpp - * @author Marcus Edel - * - * Definition of the Booth function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_BOOTH_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_BOOTH_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Booth function, defined by - * - * \f[ - * f(x) = (x_1 + 2x_2 - 7)^2 + (2x_1 + x_2 - 5)^2 - * \f] - * - * This should optimize to f(x) = 0, at x = [1, 3]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class BoothFunction -{ - public: - //! Initialize the BoothFunction. - BoothFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-9; -9"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_BOOTH_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/bukin_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/bukin_function.hpp deleted file mode 100644 index 5c14ebd5e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/bukin_function.hpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @file bukin_function.hpp - * @author Marcus Edel - * - * Definition of the Booth function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_BUKIN_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_BUKIN_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Bukin function, defined by - * - * \f[ - * f(x) = 100 * \sqrt(\left|x_2 - 0.01 * x_1^2 \right|) + - * 0.01 * \left|x_1 + 10 \right| - * \f] - * - * This should optimize to f(x) = 0, at x = [-10, 1]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class BukinFunction -{ - public: - /* - * Initialize the BukinFunction. - * - * @param epsilon Coefficient to avoid division by zero (numerical stability). - */ - BukinFunction(const double epsilon = 1e-8); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-10; -2.0"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - - //! Get the value used for numerical stability. - double Epsilon() const { return epsilon; } - //! Modify the value used for numerical stability. - double& Epsilon() { return epsilon; } - - private: - //! The value used for numerical stability. - double epsilon; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_BUKIN_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/colville_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/colville_function.hpp deleted file mode 100644 index 01496f4fd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/colville_function.hpp +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @file colville_function.hpp - * @author Marcus Edel - * - * Definition of the Colville function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_COLVILLE_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_COLVILLE_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Colville function, defined by - * - * \f[ - * f(x) = 100(x_1^2 - x_2)^2 + (x_1 - 1)^2 + (x_3 - 1)^2 + 90 * (x_3^2 - x_4)^2 - * + 10.1 * ((x_2-1)^2 + (x_4 - 1)^2) + 19.8 * (x_2 - 1) * (x_4 - 1) - * \f] - * - * This should optimize to f(x) = 0, at x = [1, 1, 1, 1]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class ColvilleFunction -{ - public: - //! Initialize the ColvilleFunction. - ColvilleFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-5; 3; 1; -9"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_COLVILLE_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/drop_wave_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/drop_wave_function.hpp deleted file mode 100644 index dfa8f693a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/drop_wave_function.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file drop_wave_function.hpp - * @author Marcus Edel - * - * Definition of the Drop-Wave function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_DROP_WAVE_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_DROP_WAVE_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Drop-Wave function, defined by - * - * \f[ - * f(x) = - (1 + \cos(12 * \sqrt(x_1^2 + x_2^2))) / (0.5 * (x_1^2 + x_2^2) + 2) - * \f] - * - * This should optimize to f(x) = 0, at x = [0, 0]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class DropWaveFunction -{ - public: - //! Initialize the DropWaveFunction. - DropWaveFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("0.5; 0.5"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_DROP_WAVE_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/easom_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/easom_function.hpp deleted file mode 100644 index e3b97a8b6..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/easom_function.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file easom_function.hpp - * @author Marcus Edel - * - * Definition of the Booth function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_EASOM_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_EASOM_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Easom function, defined by - * - * \f[ - * f(x) = -1.0 * \cos(x_1) * \cos(x_2) * \exp(-(x_1 - \pi)^2 - (x_2 - \pi)^2) - * \f] - * - * This should optimize to f(x) = -1, at x = [3.14, 3.14]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class EasomFunction -{ - public: - //! Initialize the EasomFunction. - EasomFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-90.0; 90.0"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_EASOM_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/eggholder_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/eggholder_function.hpp deleted file mode 100644 index 093984a34..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/eggholder_function.hpp +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @file eggholder_function.hpp - * @author Marcus Edel - * - * Definition of the Eggholder function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_EGGHOLDER_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_EGGHOLDER_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Eggholder function, defined by - * - * \f[ - * f(x) = -(x_2 + 47) * \sin(\sqrt(\left|x_2 + x_1 / 2 + 47\right|)) - x_1 * - * \sin(\sqrt(\left|x_1-(x_2 + 47)\right|)) - * \f] - * - * This should optimize to f(x) = -959.6407, at x = [512, 404.2319]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class EggholderFunction -{ - public: - //! Initialize the EggholderFunction. - EggholderFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-333; -333"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_EGGHOLDER_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/generalized_rosenbrock_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/generalized_rosenbrock_function.hpp deleted file mode 100644 index dc7acc9ab..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/generalized_rosenbrock_function.hpp +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @file generalized_rosenbrock_function.hpp - * @author Ryan Curtin - * @author Marcus Edel - * - * Definition of the Generalized Rosenbrock function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_GENERALIZED_ROSENBROCK_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_GENERALIZED_ROSENBROCK_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Generalized Rosenbrock function in n dimensions, defined by - * f(x) = sum_i^{n - 1} (f(i)(x)) - * f_i(x) = 100 * (x_i^2 - x_{i + 1})^2 + (1 - x_i)^2 - * x_0 = [-1.2, 1, -1.2, 1, ...] - * - * This should optimize to f(x) = 0, at x = [1, 1, 1, 1, ...]. - * - * This function can also be used for stochastic gradient descent (SGD) as a - * decomposable function (DecomposableFunctionType), so there are other - * overloads of Evaluate() and Gradient() implemented, as well as - * NumFunctions(). - * - * For more information, please refer to: - * - * @code - * @phdthesis{Jong1975, - * title = {Analysis of the behavior of a class of genetic adaptive - * systems}, - * author = {De Jong, Kenneth Alan}, - * school = {Queensland University of Technology}, - * year = {1975}, - * type = {{PhD} dissertation}, - * } - * @endcode - */ -class GeneralizedRosenbrockFunction -{ - public: - /* - * Initialize the GeneralizedRosenbrockFunction. - * - * @param n Number of dimensions for the function. - */ - GeneralizedRosenbrockFunction(const size_t n); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return n - 1; } - - //! Get the starting point. - const arma::mat& GetInitialPoint() const { return initialPoint;} - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize = 1) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize = 1) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::sp_mat& gradient, - const size_t count) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const; - - private: - //! Locally-stored Initial point. - arma::mat initialPoint; - - //! //! Number of dimensions for the function. - size_t n; - - //! For shuffling. - arma::Row visitationOrder; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_GENERALIZED_ROSENBROCK_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/matyas_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/matyas_function.hpp deleted file mode 100644 index be5b5d35a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/matyas_function.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file matyas_function.hpp - * @author Marcus Edel - * - * Definition of the Matyas function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_MATYAS_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_MATYAS_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Matyas function, defined by - * - * \f[ - * f(x) = 0.26 * (x_1^2 + x_2^2) - 0.48 * x_1 * x_2 - * \f] - * - * This should optimize to f(x) = 0, at x = [0, 0]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class MatyasFunction -{ - public: - //! Initialize the MatyasFunction. - MatyasFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-3; 3"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_MATYAS_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/mc_cormick_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/mc_cormick_function.hpp deleted file mode 100644 index 0b91d22b7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/mc_cormick_function.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file mc_cormick_function.hpp - * @author Marcus Edel - * - * Definition of the McCormick function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_MC_CORMICK_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_MC_CORMICK_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The McCormick function, defined by - * - * \f[ - * f(x) = \sin(x_1 + x_2) + (x_1 - x_2)^2 - 1.5 * x_1 + 2.5 * x_2 + 1 - * \f] - * - * This should optimize to f(x) = -1.9133, at x = [-0.54719, -1.54719]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class McCormickFunction -{ - public: - //! Initialize the McCormickFunction. - McCormickFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-2; 4"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_MC_CORMICK_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rastrigin_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rastrigin_function.hpp deleted file mode 100644 index 522a10dd5..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rastrigin_function.hpp +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file rastrigin_function.hpp - * @author Marcus Edel - * - * Definition of the Rastrigin function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_RASTRIGIN_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_RASTRIGIN_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Rastrigin function, defined by - * - * \f[ - * f(x) = 10 * d * \sum_{i=1}^{d} x_i^2 - 10 * \cos(2 * \pi * x_i) - * \f] - * - * This should optimize to f(x) = 0 - * at x = [0, ..., 0]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {Systems of extremal control}, - * author = {Rastrigin, L. A.}, - * journal = {Mir}, - * year = {1974} - * } - * @endcode - */ -class RastriginFunction -{ - public: - /* - * Initialize the RastriginFunction. - * - * @param n Number of dimensions for the function. - */ - RastriginFunction(const size_t n); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return n; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return initialPoint; } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - private: - //! Number of dimensions for the function. - size_t n; - - //! For shuffling. - arma::Row visitationOrder; - - //! Initial starting point. - arma::mat initialPoint; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_RASTRIGIN_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rosenbrock_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rosenbrock_function.hpp deleted file mode 100644 index ac95a9a37..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rosenbrock_function.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @file rosenbrock_function.hpp - * @author Ryan Curtin - * @author Marcus Edel - * - * Definition of the Rosenbrock function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_ROSENBROCK_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_ROSENBROCK_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Rosenbrock function, defined by: - * - * f(x) = f1(x) + f2(x) - * f1(x) = 100 (x2 - x1^2)^2 - * f2(x) = (1 - x1)^2 - * x_0 = [-1.2, 1] - * - * This should optimize to f(x) = 0, at x = [1, 1]. - * - * For more information, please refer to: - * - * @code - * @article{Rosenbrock1960, - * title = {An Automatic Method for Finding the Greatest or Least Value of a - * Function}, - * author = {Rosenbrock, H. H.}, - * journal = {The Computer Journal}, - * number = {3}, - * pages = {175--184}, - * year = {1960}, - * } - * @endcode - */ -class RosenbrockFunction -{ - public: - //! Initialize the RosenbrockFunction. - RosenbrockFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-1.2; 1"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_ROSENBROCK_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rosenbrock_wood_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rosenbrock_wood_function.hpp deleted file mode 100644 index 4d2597f7e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/rosenbrock_wood_function.hpp +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @file rosenbrock_wood_function.hpp - * @author Ryan Curtin - * @author Marcus Edel - * - * Definition of the Rosenbrock-Wood function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_ROSENBROCK_WOOD_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_ROSENBROCK_WOOD_FUNCTION_HPP - -#include - -#include -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Generalized Rosenbrock function in 4 dimensions with the Wood Function in - * four dimensions. In this function we are actually optimizing a 2x4 matrix of - * coordinates, not a vector. - */ -class RosenbrockWoodFunction -{ - public: - //! Initialize the RosenbrockWoodFunction. - RosenbrockWoodFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - const arma::mat& GetInitialPoint() const { return initialPoint; } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const; - - private: - //! Locally-stored initial point. - arma::mat initialPoint; - - //! Locally-stored Generalized-Rosenbrock function. - GeneralizedRosenbrockFunction rf; - - //! Locally-stored Wood function. - WoodFunction wf; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_ROSENBROCK_WOOD_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/schwefel_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/schwefel_function.hpp deleted file mode 100644 index e1e0dfdee..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/schwefel_function.hpp +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file schwefel_function.hpp - * @author Marcus Edel - * - * Definition of the Schwefel function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_SCHWEFEL_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_SCHWEFEL_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Schwefel function, defined by - * - * \f[ - * f(x) = 418.9829 * d * \sum_{i=1}^{d} x_i * \sin(\sqrt(\left|x\right|)) - * \f] - * - * This should optimize to f(x) = 0 - * at x = [420.9687, ..., 420.9687]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {Systems of extremal control}, - * author = {Rastrigin, L. A.}, - * journal = {Mir}, - * year = {1974} - * } - * @endcode - */ -class SchwefelFunction -{ - public: - /* - * Initialize the SchwefelFunction. - * - * @param n Number of dimensions for the function. - */ - SchwefelFunction(const size_t n); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return n; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return initialPoint; } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - private: - //! Number of dimensions for the function. - size_t n; - - //! For shuffling. - arma::Row visitationOrder; - - //! Initial starting point. - arma::mat initialPoint; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_SCHWEFEL_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/sgd_test_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/sgd_test_function.hpp deleted file mode 100644 index bdfe7afdd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/sgd_test_function.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @file sgd_test_function.hpp - * @author Ryan Curtin - * - * Very simple test function for SGD. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_SGD_TEST_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_SGD_TEST_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -//! Very, very simple test function which is the composite of three other -//! functions. The gradient is not very steep far away from the optimum, so a -//! larger step size may be required to optimize it in a reasonable number of -//! iterations. -class SGDTestFunction -{ - private: - arma::Col visitationOrder; - - public: - //! Initialize the SGDTestFunction. - SGDTestFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the optimizer. - */ - void Shuffle(); - - //! Return 3 (the number of functions). - size_t NumFunctions() const { return 3; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("6; -45.6; 6.2"); } - - //! Evaluate a function. - double Evaluate(const arma::mat& coordinates, const size_t i) const; - - //! Evaluate a function for a particular batch-size. - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - //! Evaluate the gradient of a function. - void Gradient(const arma::mat& coordinates, - const size_t i, - arma::mat& gradient) const; - - //! Evaluate the gradient of a function for a particular batch-size - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/sphere_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/sphere_function.hpp deleted file mode 100644 index 80b88a77b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/sphere_function.hpp +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @file sphere_function.hpp - * @author Marcus Edel - * - * Definition of the Sphere function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_SPHERE_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_SPHERE_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Sphere function, defined by - * - * \f[ - * f(x) = \sum_{i=1}^{d} x_i^2 - * \f] - * - * This should optimize to f(x) = 0, at x = [0, ..., 0]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class SphereFunction -{ - public: - /* - * Initialize the SphereFunction. - * - * @param n Number of dimensions for the function. - */ - SphereFunction(const size_t n); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return n; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return initialPoint; } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - private: - //! Number of dimensions for the function. - size_t n; - - //! For shuffling. - arma::Row visitationOrder; - - //! Initial starting point. - arma::mat initialPoint; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_SPHERE_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/styblinski_tang_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/styblinski_tang_function.hpp deleted file mode 100644 index 4e52f266f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/styblinski_tang_function.hpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @file styblinski_tang_function.hpp - * @author Marcus Edel - * - * Definition of the Styblinski-Tang function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_STYBLINSKI_TANG_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_STYBLINSKI_TANG_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Styblinski-Tang function, defined by - * - * \f[ - * f(x) = 0.5 * \sum_{i=1}^{d} x_i^4 - 16_i^2+5x_i - * \f] - * - * This should optimize to f(x) = -39.16599 * d - * at x = [-2.903534, ..., -2.903534]. - * - * For more information, please refer to: - * - * @code - * @article{Jamil2013, - * title = {A Literature Survey of Benchmark Functions For Global - * Optimization Problems}, - * author = {Momin Jamil and Xin{-}She Yang}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1308.4008} - * } - * @endcode - */ -class StyblinskiTangFunction -{ - public: - /* - * Initialize the StyblinskiTangFunction. - * - * @param n Number of dimensions for the function. - */ - StyblinskiTangFunction(const size_t n); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return n; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return initialPoint; } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient); - private: - //! Number of dimensions for the function. - size_t n; - - //! For shuffling. - arma::Row visitationOrder; - - //! Initial starting point. - arma::mat initialPoint; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_STYBLINSKI_TANG_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/wood_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/problems/wood_function.hpp deleted file mode 100644 index c8fb443b1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/problems/wood_function.hpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @file wood_function.hpp - * @author Ryan Curtin - * @author Marcus Edel - * - * Definition of the Wood function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROBLEMS_WOOD_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_PROBLEMS_WOOD_FUNCTION_HPP - -#include - -namespace mlpack { -namespace optimization { -namespace test { - -/** - * The Wood function, defined by - * f(x) = f1(x) + f2(x) + f3(x) + f4(x) + f5(x) + f6(x) - * f1(x) = 100 (x2 - x1^2)^2 - * f2(x) = (1 - x1)^2 - * f3(x) = 90 (x4 - x3^2)^2 - * f4(x) = (1 - x3)^2 - * f5(x) = 10 (x2 + x4 - 2)^2 - * f6(x) = (1 / 10) (x2 - x4)^2 - * x_0 = [-3, -1, -3, -1] - * - * This should optimize to f(x) = 0, at x = [1, 1, 1, 1]. - * - * For more information, please refer to: - * - * @code - * @article{Grippo1989, - * title = {A truncated Newton method with nonmonotone line search for - * unconstrained optimization}, - * author = {Grippo, L. and Lampariello, F. and Lucidi, S.}, - * journal = {Journal of Optimization Theory and Applications}, - * year = {1989}, - * volume = {60}, - * number = {3}, - * pages = {401--419}, - * } - * @endcode - */ -class WoodFunction -{ - public: - //! Initialize the WoodFunction. - WoodFunction(); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - //! Return 1 (the number of functions). - size_t NumFunctions() const { return 1; } - - //! Get the starting point. - arma::mat GetInitialPoint() const { return arma::mat("-3; -1; -3; -1"); } - - /* - * Evaluate a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param batchSize Number of points to process. - */ - double Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) const; - - /* - * Evaluate a function with the given coordinates. - * - * @param coordinates The function coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /* - * Evaluate the gradient of a function for a particular batch-size. - * - * @param coordinates The function coordinates. - * @param begin The first function. - * @param gradient The function gradient. - * @param batchSize Number of points to process. - */ - void Gradient(const arma::mat& coordinates, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) const; - - /* - * Evaluate the gradient of a function with the given coordinates. - * - * @param coordinates The function coordinates. - * @param gradient The function gradient. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const; -}; - -} // namespace test -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_PROBLEMS_WOOD_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/proximal/proximal.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/proximal/proximal.hpp deleted file mode 100644 index 3112f6ab7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/proximal/proximal.hpp +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @file proximal.hpp - * @author Chenzhe Diao - * - * Approximate a vector with another vector on lp ball. Currently support l0 - * ball and l1 ball with specific norm. - * It can be used in projected gradient method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_PROXIMAL_PROXIMAL_HPP -#define MLPACK_CORE_OPTIMIZERS_PROXIMAL_PROXIMAL_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Approximate a vector with another vector on lp ball. Currently support l0 - * ball and l1 ball with specific norm. - * It can be used in projected gradient method. - */ -class Proximal -{ - public: - /** - * Project the vector onto the l1 ball with norm tau. That is, we will solve - * for: - * \f[ - * w = argmin_w ||w - v||_2, \qquad s.t. ~ ||w||_1 \leqslant tau - * \f] - * - * @param v Input vector to be approxmated, the output optimal vector is - * also saved in v. - * @param tau Norm of l1 ball. - */ - static void ProjectToL1Ball(arma::vec& v, double tau); - - /** - * Project the vector onto the l0 ball with norm tau. That is, we try to - * approximate v with sparse vector w: - * \f[ - * w = argmin_w ||w - v||_2, \qquad s.t. ~ ||w||_0 \leqslant tau - * \f] - * - * @param v Input vector to be approxmated, the output optimal vector is - * also saved in v. - * @param tau Norm of l0 ball. - */ - static void ProjectToL0Ball(arma::vec& v, int tau); -}; // class Proximal - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/rmsprop/rmsprop.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/rmsprop/rmsprop.hpp deleted file mode 100644 index a6cb06c4c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/rmsprop/rmsprop.hpp +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @file rmsprop.hpp - * @author Ryan Curtin - * @author Marcus Edel - * @author Vivek Pal - * - * RMSProp optimizer. RMSProp is an optimizer that utilizes the magnitude of - * recent gradients to normalize the gradients. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_RMSPROP_RMSPROP_HPP -#define MLPACK_CORE_OPTIMIZERS_RMSPROP_RMSPROP_HPP - -#include - -#include -#include "rmsprop_update.hpp" - -namespace mlpack { -namespace optimization { - -/** - * RMSProp is an optimizer that utilizes the magnitude of recent gradients to - * normalize the gradients. In its basic form, given a step rate \f$ \gamma \f$ - * and a decay term \f$ \alpha \f$ we perform the following updates: - * - * \f{eqnarray*}{ - * r_t &=& (1 - \gamma) f'(\Delta_t)^2 + \gamma r_{t - 1} \\ - * v_{t + 1} &=& \frac{\alpha}{\sqrt{r_t}}f'(\Delta_t) \\ - * \Delta_{t + 1} &=& \Delta_t - v_{t + 1} - * \f} - * - * For more information, see the following. - * - * @code - * @misc{tieleman2012, - * title = {Lecture 6.5 - rmsprop, COURSERA: Neural Networks for Machine - * Learning}, - * year = {2012} - * } - * @endcode - * - * For RMSProp to work, a DecomposableFunctionType template parameter is - * required. This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - */ -class RMSProp -{ - public: - /** - * Construct the RMSProp optimizer with the given function and parameters. The - * defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Number of points to process in each step. - * @param alpha Smoothing constant, similar to that used in AdaDelta and - * momentum methods. - * @param epsilon Value used to initialise the mean squared gradient parameter. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - */ - RMSProp(const double stepSize = 0.01, - const size_t batchSize = 32, - const double alpha = 0.99, - const double epsilon = 1e-8, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true); - - /** - * Optimize the given function using RMSProp. The given starting point will be - * modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate) - { - return optimizer.Optimize(function, iterate); - } - - //! Get the step size. - double StepSize() const { return optimizer.StepSize(); } - //! Modify the step size. - double& StepSize() { return optimizer.StepSize(); } - - //! Get the batch size. - size_t BatchSize() const { return optimizer.BatchSize(); } - //! Modify the batch size. - size_t& BatchSize() { return optimizer.BatchSize(); } - - //! Get the smoothing parameter. - double Alpha() const { return optimizer.UpdatePolicy().Alpha(); } - //! Modify the smoothing parameter. - double& Alpha() { return optimizer.UpdatePolicy().Alpha(); } - - //! Get the value used to initialise the mean squared gradient parameter. - double Epsilon() const { return optimizer.UpdatePolicy().Epsilon(); } - //! Modify the value used to initialise the mean squared gradient parameter. - double& Epsilon() { return optimizer.UpdatePolicy().Epsilon(); } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return optimizer.MaxIterations(); } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return optimizer.MaxIterations(); } - - //! Get the tolerance for termination. - double Tolerance() const { return optimizer.Tolerance(); } - //! Modify the tolerance for termination. - double& Tolerance() { return optimizer.Tolerance(); } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return optimizer.Shuffle(); } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return optimizer.Shuffle(); } - - private: - //! The Stochastic Gradient Descent object with RMSPropUpdate policy. - SGD optimizer; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/rmsprop/rmsprop_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/rmsprop/rmsprop_update.hpp deleted file mode 100644 index 4e8f7bd69..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/rmsprop/rmsprop_update.hpp +++ /dev/null @@ -1,116 +0,0 @@ -/** - * @file rmsprop_update.hpp - * @author Ryan Curtin - * @author Marcus Edel - * @author Vivek Pal - * - * RMSProp optimizer. RMSProp is an optimizer that utilizes the magnitude of - * recent gradients to normalize the gradients. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_RMSPROP_RMSPROP_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_RMSPROP_RMSPROP_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * RMSProp is an optimizer that utilizes the magnitude of recent gradients to - * normalize the gradients. In its basic form, given a step rate \f$ \gamma \f$ - * and a decay term \f$ \alpha \f$ we perform the following updates: - * - * \f{eqnarray*}{ - * r_t &=& (1 - \gamma) f'(\Delta_t)^2 + \gamma r_{t - 1} \\ - * v_{t + 1} &=& \frac{\alpha}{\sqrt{r_t}}f'(\Delta_t) \\ - * \Delta_{t + 1} &=& \Delta_t - v_{t + 1} - * \f} - * - * For more information, see the following. - * - * @code - * @misc{tieleman2012, - * title = {Lecture 6.5 - rmsprop, COURSERA: Neural Networks for Machine - * Learning}, - * year = {2012} - * } - * @endcode - */ -class RMSPropUpdate -{ - public: - /** - * Construct the RMSProp update policy with the given parameters. - * - * @param epsilon The epsilon value used to initialise the squared gradient - * parameter. - * @param alpha The smoothing parameter. - */ - RMSPropUpdate(const double epsilon = 1e-8, - const double alpha = 0.99) : - epsilon(epsilon), - alpha(alpha) - { - // Nothing to do. - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - // Leaky sum of squares of parameter gradient. - meanSquaredGradient = arma::zeros(rows, cols); - } - - /** - * Update step for RMSProp. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - meanSquaredGradient *= alpha; - meanSquaredGradient += (1 - alpha) * (gradient % gradient); - iterate -= stepSize * gradient / (arma::sqrt(meanSquaredGradient) + - epsilon); - } - - //! Get the value used to initialise the squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the squared gradient parameter. - double& Epsilon() { return epsilon; } - - //! Get the smoothing parameter. - double Alpha() const { return alpha; } - //! Modify the smoothing parameter. - double& Alpha() { return alpha; } - - private: - // The epsilon value used to initialise the squared gradient parameter. - double epsilon; - - // The smoothing parameter. - double alpha; - - // Leaky sum of squares of parameter gradient. - arma::mat meanSquaredGradient; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sa/exponential_schedule.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sa/exponential_schedule.hpp deleted file mode 100644 index bd1fa29ae..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sa/exponential_schedule.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @file exponential_schedule.hpp - * @author Zhihao Lou - * - * Exponential (geometric) cooling schedule used in SA. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SA_EXPONENTIAL_SCHEDULE_HPP -#define MLPACK_CORE_OPTIMIZERS_SA_EXPONENTIAL_SCHEDULE_HPP - -namespace mlpack { -namespace optimization { - -/** - * The exponential cooling schedule cools the temperature T at every step - * according to the equation - * - * \f[ - * T_{n+1} = (1-\lambda) T_{n} - * \f] - * - * where \f$ 0<\lambda<1 \f$ is the cooling speed. The smaller \f$ \lambda \f$ - * is, the slower the cooling speed, and better the final result will be. Some - * literature uses \f$ \alpha = (-1 \lambda) \f$ instead. In practice, - * \f$ \alpha \f$ is very close to 1 and will be awkward to input (e.g. - * alpha = 0.999999 vs lambda = 1e-6). - */ -class ExponentialSchedule -{ - public: - /* - * Construct the ExponentialSchedule with the given parameter. - * - * @param lambda Cooling speed. - */ - ExponentialSchedule(const double lambda = 0.001) : lambda(lambda) { } - - /** - * Returns the next temperature given current status. The current system's - * energy is not used in this calculation. - * - * @param currentTemperature Current temperature of system. - * @param currentEnergy Current energy of system (not used). - */ - double NextTemperature( - const double currentTemperature, - const double /* currentEnergy */) - { - return (1 - lambda) * currentTemperature; - } - - //! Get the cooling speed, lambda. - double Lambda() const { return lambda; } - //! Modify the cooling speed, lambda. - double& Lambda() { return lambda; } - - private: - //! The cooling speed. - double lambda; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sa/sa.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sa/sa.hpp deleted file mode 100644 index d08b8228c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sa/sa.hpp +++ /dev/null @@ -1,212 +0,0 @@ -/** - * @file sa.hpp - * @author Zhihao Lou - * - * Simulated Annealing (SA). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SA_SA_HPP -#define MLPACK_CORE_OPTIMIZERS_SA_SA_HPP - -#include - -#include "exponential_schedule.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Simulated Annealing is an stochastic optimization algorithm which is able to - * deliver near-optimal results quickly without knowing the gradient of the - * function being optimized. It has unique hill climbing capability that makes - * it less vulnerable to local minima. This implementation uses exponential - * cooling schedule and feedback move control by default, but the cooling - * schedule can be changed via a template parameter. - * - * The algorithm keeps the temperature at initial temperature for initMove - * steps to get rid of the dependency on the initial condition. After that, it - * cools every step until the system is considered frozen or maxIterations is - * reached. - * - * At each step, SA only perturbs one parameter at a time. When SA has perturbed - * all parameters in a problem, a sweep has been completed. Every moveCtrlSweep - * sweeps, the algorithm does feedback move control to change the average move - * size depending on the responsiveness of each parameter. Parameter gain - * controls the proportion of the feedback control. - * - * The system is considered "frozen" when its score fails to change more then - * tolerance for maxToleranceSweep consecutive sweeps. - * - * For SA to work, the FunctionType template class, used by the Optimize() - * method, must implement the following two methods: - * - * double Evaluate(const arma::mat& coordinates); - * arma::mat& GetInitialPoint(); - * - * and the CoolingScheduleType parameter must implement the following method: - * - * double NextTemperature(const double currentTemperature, - * const double currentValue); - * - * which returns the next temperature given current temperature and the value - * of the function being optimized. - * - * @tparam CoolingScheduleType type for cooling schedule - */ -template -class SA -{ - public: - /** - * Construct the SA optimizer with the given parameters. - * - * @param coolingSchedule Instantiated cooling schedule. - * @param maxIterations Maximum number of iterations allowed - * (0 indicates no limit). - * @param initT Initial temperature. - * @param initMoves Number of initial iterations without changing temperature. - * @param moveCtrlSweep Sweeps per feedback move control. - * @param tolerance Tolerance to consider system frozen. - * @param maxToleranceSweep Maximum sweeps below tolerance to consider system - * frozen. - * @param maxMoveCoef Maximum move size. - * @param initMoveCoef Initial move size. - * @param gain Proportional control in feedback move control. - */ - SA(CoolingScheduleType& coolingSchedule, - const size_t maxIterations = 1000000, - const double initT = 10000., - const size_t initMoves = 1000, - const size_t moveCtrlSweep = 100, - const double tolerance = 1e-5, - const size_t maxToleranceSweep = 3, - const double maxMoveCoef = 20, - const double initMoveCoef = 0.3, - const double gain = 0.3); - - /** - * Optimize the given function using simulated annealing. The given starting - * point will be modified to store the finishing point of the algorithm, and - * the final objective value is returned. - * - * @tparam FunctionType Type of function to optimize. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(FunctionType& function, arma::mat& iterate); - - //! Get the temperature. - double Temperature() const { return temperature; } - //! Modify the temperature. - double& Temperature() { return temperature; } - - //! Get the initial moves. - size_t InitMoves() const { return initMoves; } - //! Modify the initial moves. - size_t& InitMoves() { return initMoves; } - - //! Get sweeps per move control. - size_t MoveCtrlSweep() const { return moveCtrlSweep; } - //! Modify sweeps per move control. - size_t& MoveCtrlSweep() { return moveCtrlSweep; } - - //! Get the tolerance. - double Tolerance() const { return tolerance; } - //! Modify the tolerance. - double& Tolerance() { return tolerance; } - - //! Get the maxToleranceSweep. - size_t MaxToleranceSweep() const { return maxToleranceSweep; } - //! Modify the maxToleranceSweep. - size_t& MaxToleranceSweep() { return maxToleranceSweep; } - - //! Get the gain. - double Gain() const { return gain; } - //! Modify the gain. - double& Gain() { return gain; } - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - private: - //! The cooling schedule being used. - CoolingScheduleType& coolingSchedule; - //! The maximum number of iterations. - size_t maxIterations; - //! The current temperature. - double temperature; - //! The number of initial moves before reducing the temperature. - size_t initMoves; - //! The number of sweeps before a MoveControl() call. - size_t moveCtrlSweep; - //! Tolerance for convergence. - double tolerance; - //! Number of sweeps in tolerance before system is considered frozen. - size_t maxToleranceSweep; - //! Maximum move. - double maxMoveCoef; - //! Initial move size. - double initMoveCoef; - //! Proportional control in feedback move control. - double gain; - - /** - * GenerateMove proposes a move on element iterate(idx), and determines if - * that move is acceptable or not according to the Metropolis criterion. - * After that it increments idx so the next call will make a move on next - * parameters. When all elements of the state have been moved (a sweep), it - * resets idx and increments sweepCounter. When sweepCounter reaches - * moveCtrlSweep, it performs MoveControl() and resets sweepCounter. - * - * @param iterate Current optimization position. - * @param accept Matrix representing which parameters have had accepted moves. - * @param moveSize Strides for a move. - * @param energy Current energy of the system. - * @param idx Current parameter to modify. - * @param sweepCounter Current counter representing how many sweeps have been - * completed. - */ - template - void GenerateMove(FunctionType& function, - arma::mat& iterate, - arma::mat& accept, - arma::mat& moveSize, - double& energy, - size_t& idx, - size_t& sweepCounter); - - /** - * MoveControl() uses a proportional feedback control to determine the size - * parameter to pass to the move generation distribution. The target of such - * move control is to make the acceptance ratio, accept/nMoves, be as close to - * 0.44 as possible. Generally speaking, the larger the move size is, the - * larger the function value change of the move will be, and less likely such - * move will be accepted by the Metropolis criterion. Thus, the move size is - * controlled by - * - * log(moveSize) = log(moveSize) + gain * (accept/nMoves - target) - * - * For more theory and the mysterious 0.44 value, see Jimmy K.-C. Lam and - * Jean-Marc Delosme. `An efficient simulated annealing schedule: derivation'. - * Technical Report 8816, Yale University, 1988. - * - * @param nMoves Number of moves since last call. - * @param accept Matrix representing which parameters have had accepted moves. - */ - void MoveControl(const size_t nMoves, arma::mat& accept, arma::mat& moveSize); -}; - -} // namespace optimization -} // namespace mlpack - -#include "sa_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sa/sa_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sa/sa_impl.hpp deleted file mode 100644 index d65c0983c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sa/sa_impl.hpp +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @file sa_impl.hpp - * @auther Zhihao Lou - * - * The implementation of the SA optimizer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SA_SA_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SA_SA_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace optimization { - -template -SA::SA( - CoolingScheduleType& coolingSchedule, - const size_t maxIterations, - const double initT, - const size_t initMoves, - const size_t moveCtrlSweep, - const double tolerance, - const size_t maxToleranceSweep, - const double maxMoveCoef, - const double initMoveCoef, - const double gain) : - coolingSchedule(coolingSchedule), - maxIterations(maxIterations), - temperature(initT), - initMoves(initMoves), - moveCtrlSweep(moveCtrlSweep), - tolerance(tolerance), - maxToleranceSweep(maxToleranceSweep), - maxMoveCoef(maxMoveCoef), - initMoveCoef(initMoveCoef), - gain(gain) -{ - // Nothing to do. -} - -//! Optimize the function (minimize). -template -template -double SA::Optimize(FunctionType& function, - arma::mat& iterate) -{ - // Make sure we have the methods that we need. - traits::CheckNonDifferentiableFunctionTypeAPI(); - - const size_t rows = iterate.n_rows; - const size_t cols = iterate.n_cols; - - size_t frozenCount = 0; - double energy = function.Evaluate(iterate); - double oldEnergy = energy; - - size_t idx = 0; - size_t sweepCounter = 0; - - arma::mat accept(rows, cols, arma::fill::zeros); - arma::mat moveSize(rows, cols); - moveSize.fill(initMoveCoef); - - // Initial moves to get rid of dependency of initial states. - for (size_t i = 0; i < initMoves; ++i) - GenerateMove(function, iterate, accept, moveSize, energy, idx, - sweepCounter); - - // Iterating and cooling. - for (size_t i = 0; i != maxIterations; ++i) - { - oldEnergy = energy; - GenerateMove(function, iterate, accept, moveSize, energy, idx, - sweepCounter); - temperature = coolingSchedule.NextTemperature(temperature, energy); - - // Determine if the optimization has entered (or continues to be in) a - // frozen state. - if (std::abs(energy - oldEnergy) < tolerance) - ++frozenCount; - else - frozenCount = 0; - - // Terminate, if possible. - if (frozenCount >= maxToleranceSweep * moveCtrlSweep * iterate.n_elem) - { - Log::Debug << "SA: minimized within tolerance " << tolerance << " for " - << maxToleranceSweep << " sweeps after " << i << " iterations; " - << "terminating optimization." << std::endl; - return energy; - } - } - - Log::Debug << "SA: maximum iterations (" << maxIterations << ") reached; " - << "terminating optimization." << std::endl; - return energy; -} - -/** - * GenerateMove proposes a move on element iterate(idx), and determines - * it that move is acceptable or not according to the Metropolis criterion. - * After that it increments idx so next call will make a move on next - * parameters. When all elements of the state have been moved (a sweep), it - * resets idx and increments sweepCounter. When sweepCounter reaches - * moveCtrlSweep, it performs moveControl and resets sweepCounter. - */ -template -template -void SA::GenerateMove( - FunctionType& function, - arma::mat& iterate, - arma::mat& accept, - arma::mat& moveSize, - double& energy, - size_t& idx, - size_t& sweepCounter) -{ - const double prevEnergy = energy; - const double prevValue = iterate(idx); - - // It is possible to use a non-Laplace distribution here, but it is difficult - // because the acceptance ratio should be as close to 0.44 as possible, and - // MoveControl() is derived for the Laplace distribution. - - // Sample from a Laplace distribution with scale parameter moveSize(idx). - const double unif = 2.0 * math::Random() - 1.0; - const double move = (unif < 0) ? (moveSize(idx) * std::log(1 + unif)) : - (-moveSize(idx) * std::log(1 - unif)); - - iterate(idx) += move; - energy = function.Evaluate(iterate); - // According to the Metropolis criterion, accept the move with probability - // min{1, exp(-(E_new - E_old) / T)}. - const double xi = math::Random(); - const double delta = energy - prevEnergy; - const double criterion = std::exp(-delta / temperature); - if (delta <= 0. || criterion > xi) - { - accept(idx) += 1.; - } - else // Reject the move; restore previous state. - { - iterate(idx) = prevValue; - energy = prevEnergy; - } - - ++idx; - if (idx == iterate.n_elem) // Finished with a sweep. - { - idx = 0; - ++sweepCounter; - } - - if (sweepCounter == moveCtrlSweep) // Do MoveControl(). - { - MoveControl(moveCtrlSweep, accept, moveSize); - sweepCounter = 0; - } -} - -/** - * MoveControl() uses a proportional feedback control to determine the size - * parameter to pass to the move generation distribution. The target of such - * move control is to make the acceptance ratio, accept/nMoves, be as close to - * 0.44 as possible. Generally speaking, the larger the move size is, the larger - * the function value change of the move will be, and less likely such move will - * be accepted by the Metropolis criterion. Thus, the move size is controlled by - * - * log(moveSize) = log(moveSize) + gain * (accept/nMoves - target) - * - * For more theory and the mysterious 0.44 value, see Jimmy K.-C. Lam and - * Jean-Marc Delosme. `An efficient simulated annealing schedule: derivation'. - * Technical Report 8816, Yale University, 1988. - */ -template -inline void SA::MoveControl(const size_t nMoves, - arma::mat& accept, - arma::mat& moveSize) -{ - arma::mat target; - target.copy_size(accept); - target.fill(0.44); - moveSize = arma::log(moveSize); - moveSize += gain * (accept / (double) nMoves - target); - moveSize = arma::exp(moveSize); - - // To avoid the use of element-wise arma::min(), which is only available in - // Armadillo after v3.930, we use a for loop here instead. - for (size_t i = 0; i < accept.n_elem; ++i) - moveSize(i) = (moveSize(i) > maxMoveCoef) ? maxMoveCoef : moveSize(i); - - accept.zeros(); -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah.hpp deleted file mode 100644 index 3ead9e137..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah.hpp +++ /dev/null @@ -1,188 +0,0 @@ -/** - * @file sarah.hpp - * @author Marcus Edel - * - * StochAstic Recusive gRadient algoritHm (SARAH). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SARAH_SARAH_HPP -#define MLPACK_CORE_OPTIMIZERS_SARAH_SARAH_HPP - -#include - -#include "sarah_update.hpp" -#include "sarah_plus_update.hpp" - -namespace mlpack { -namespace optimization { - -/** - * StochAstic Recusive gRadient algoritHm (SARAH). is a variance reducing - * stochastic recursive gradient algorithm for minimizing a function - * which can be expressed as a sum of other functions. - * - * For more information, see the following. - * - * @code - * @article{Nguyen2017, - * author = {{Nguyen}, L.~M. and {Liu}, J. and {Scheinberg}, - * K. and {Tak{\'a}{\v c}}, M.}, - * title = {SARAH: A Novel Method for Machine Learning Problems Using - * Stochastic Recursive Gradient}, - * journal = {ArXiv e-prints}, - * url = {https://arxiv.org/abs/1703.00102} - * year = 2017, - * } - * @endcode - * - * For SARAH to work, a DecomposableFunctionType template parameter is required. - * This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset ( - * is held internally in the DecomposableFunctionType). - * - * @tparam UpdatePolicyType update policy used by SARAHType during the iterative - * update process. - */ -template -class SARAHType -{ - public: - /** - * Construct the SARAH optimizer with the given function and parameters. The - * defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Batch size to use for each step. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param innerIterations The number of inner iterations allowed (0 means - * n / batchSize). Note that the full gradient is only calculated in - * the outer iteration. - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - * @param updatePolicy Instantiated update policy used to adjust the given - * parameters. - */ - SARAHType(const double stepSize = 0.01, - const size_t batchSize = 32, - const size_t maxIterations = 1000, - const size_t innerIterations = 0, - const double tolerance = 1e-5, - const bool shuffle = true, - const UpdatePolicyType& updatePolicy = UpdatePolicyType()); - - /** - * Optimize the given function using SARAH. The given starting point will be - * modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the step size. - double StepSize() const { return stepSize; } - //! Modify the step size. - double& StepSize() { return stepSize; } - - //! Get the batch size. - size_t BatchSize() const { return batchSize; } - //! Modify the batch size. - size_t& BatchSize() { return batchSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the maximum number of iterations (0 indicates default n / b). - size_t InnerIterations() const { return innerIterations; } - //! Modify the maximum number of iterations (0 indicates default n / b). - size_t& InnerIterations() { return innerIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return shuffle; } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return shuffle; } - - //! Get the update policy. - const UpdatePolicyType& UpdatePolicy() const { return updatePolicy; } - //! Modify the update policy. - UpdatePolicyType& UpdatePolicy() { return updatePolicy; } - - private: - //! The step size for each example. - double stepSize; - - //! The batch size for processing. - size_t batchSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The maximum number of allowed inner iterations per epoch. - size_t innerIterations; - - //! The tolerance for termination. - double tolerance; - - //! Controls whether or not the individual functions are shuffled when - //! iterating. - bool shuffle; - - //! The update policy used to update the parameters in each iteration. - UpdatePolicyType updatePolicy; -}; - -// Convenience typedefs. - -/** - * Standard stochastic variance reduced gradient. - */ -using SARAH = SARAHType; - -/** - * Stochastic variance reduced gradient with Barzilai-Borwein. - */ -using SARAH_Plus = SARAHType; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "sarah_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_impl.hpp deleted file mode 100644 index c4d4545ba..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_impl.hpp +++ /dev/null @@ -1,193 +0,0 @@ -/** - * @file sarah_impl.hpp - * @author Marcus Edel - * - * Implementation of StochAstic Recusive gRadient algoritHm (SARAH). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SARAH_SARAH_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SARAH_SARAH_IMPL_HPP - -// In case it hasn't been included yet. -#include "sarah.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -SARAHType::SARAHType( - const double stepSize, - const size_t batchSize, - const size_t maxIterations, - const size_t innerIterations, - const double tolerance, - const bool shuffle, - const UpdatePolicyType& updatePolicy) : - stepSize(stepSize), - batchSize(batchSize), - maxIterations(maxIterations), - innerIterations(innerIterations), - tolerance(tolerance), - shuffle(shuffle), - updatePolicy(updatePolicy) -{ /* Nothing to do. */ } - -//! Optimize the function (minimize). -template -template -double SARAHType::Optimize( - DecomposableFunctionType& function, arma::mat& iterate) -{ - traits::CheckDecomposableFunctionTypeAPI(); - - // Find the number of functions to use. - const size_t numFunctions = function.NumFunctions(); - - // To keep track of where we are and how things are going. - double overallObjective = 0; - double lastObjective = DBL_MAX; - - // Set epoch length to n / b if the user asked for. - if (innerIterations == 0) - innerIterations = numFunctions; - - // Now iterate! - arma::mat gradient(iterate.n_rows, iterate.n_cols); - arma::mat v(iterate.n_rows, iterate.n_cols); - arma::mat gradient0(iterate.n_rows, iterate.n_cols); - arma::mat iterate0; - - // Find the number of batches. - size_t numBatches = numFunctions / batchSize; - if (numFunctions % batchSize != 0) - ++numBatches; // Capture last few. - - const size_t actualMaxIterations = (maxIterations == 0) ? - std::numeric_limits::max() : maxIterations; - for (size_t i = 0; i < actualMaxIterations; ++i) - { - // Calculate the objective function. - overallObjective = 0; - for (size_t f = 0; f < numFunctions; f += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - f); - overallObjective += function.Evaluate(iterate, f, effectiveBatchSize); - } - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "SARAH: converged to " << overallObjective - << "; terminating with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "SARAH: minimized within tolerance " << tolerance - << "; terminating optimization." << std::endl; - return overallObjective; - } - - lastObjective = overallObjective; - - // Compute the full gradient. - size_t effectiveBatchSize = std::min(batchSize, numFunctions); - function.Gradient(iterate, 0, v, effectiveBatchSize); - for (size_t f = effectiveBatchSize; f < numFunctions; - /* incrementing done manually */) - { - // Find the effective batch size (the last batch may be smaller). - effectiveBatchSize = std::min(batchSize, numFunctions - f); - - function.Gradient(iterate, f, gradient, effectiveBatchSize); - v += gradient; - - f += effectiveBatchSize; - } - v /= (double) numFunctions; - - // Update iterate with full gradient (v). - iterate -= stepSize * v; - - const double vNorm = arma::norm(v); - - for (size_t f = 0, currentFunction = 0; f < innerIterations; - /* incrementing done manually */) - { - // Is this iteration the start of a sequence? - if ((currentFunction % numFunctions) == 0) - { - currentFunction = 0; - - // Determine order of visitation. - if (shuffle) - function.Shuffle(); - } - - // Find the effective batch size (the last batch may be smaller). - effectiveBatchSize = std::min(batchSize, numFunctions - currentFunction); - - // Calculate variance reduced gradient. - function.Gradient(iterate, currentFunction, gradient, - effectiveBatchSize); - - // Avoid an unnecessary copy on the first iteration. - if (f > 0) - { - function.Gradient(iterate0, currentFunction, gradient0, - effectiveBatchSize); - - // Store current parameter for the calculation of the variance reduced - // gradient. - iterate0 = iterate; - - // Use the update policy to take a step. - if (updatePolicy.Update(iterate, v, gradient, gradient0, - effectiveBatchSize, stepSize, vNorm)) - { - break; - } - } - else - { - // Store current parameter for the calculation of the variance reduced - // gradient. - iterate0 = iterate; - - // Use the update policy to take a step. - if (updatePolicy.Update(iterate, v, gradient, gradient, - effectiveBatchSize, stepSize, vNorm)) - { - break; - } - } - - currentFunction += effectiveBatchSize; - f += effectiveBatchSize; - } - } - - Log::Info << "SARAH: maximum iterations (" << maxIterations << ") reached; " - << "terminating optimization." << std::endl; - - // Calculate final objective. - overallObjective = 0; - for (size_t i = 0; i < numFunctions; i += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - i); - overallObjective += function.Evaluate(iterate, i, effectiveBatchSize); - } - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_plus_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_plus_update.hpp deleted file mode 100644 index 9c19a990f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_plus_update.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file sarah_plus_update.hpp - * @author Marcus Edel - * - * Implementation of the SARAH+ update rule which provides an automatic and - * adaptive choice of the inner loop size. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SARAH_SARAH_PLUS_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_SARAH_SARAH_PLUS_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * SARAH+ provides an automatic and adaptive choice of the inner loop size. - */ -class SARAHPlusUpdate -{ - public: - /* - * Construct the SARAH+ update policy. - * - * @param gamma Adaptive parameter for the inner loop. - */ - SARAHPlusUpdate(const double gamma = 0.125) : gamma(gamma) - { - /* Nothing to do here. */ - } - - /** - * Update step for SARAH+. The function parameters are updated in the negative - * direction of the gradient. - * - * @param iterate Parameters that minimize the function. - * @param v Unbiased estimator of the gradient. - * @param gradient The current gradient matrix at time t. - * @param gradient0 The old gradient matrix at time t - 1. - * @param batchSize Batch size to be used for the given iteration. - * @param stepSize Step size to be used for the given iteration. - * @param vNorm The norm of the full gradient. - */ - bool Update(arma::mat& iterate, - arma::mat& v, - const arma::mat& gradient, - const arma::mat& gradient0, - const size_t batchSize, - const double stepSize, - const double vNorm) - { - v += (gradient - gradient0) / (double) batchSize; - iterate -= stepSize * v; - - if (arma::norm(v) <= gamma * vNorm) - return true; - - return false; - } - - private: - //! Adaptive parameter for the inner loop. - double gamma; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_update.hpp deleted file mode 100644 index f269ac56b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sarah/sarah_update.hpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @file svrg_update.hpp - * @author Marcus Edel - * - * Vanilla update for SARAH. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SARAH_SARAH_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_SARAH_SARAH_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Vanilla update policy for SARAH. - */ -class SARAHUpdate -{ - public: - /** - * Update step for SARAH. The function parameters are updated in the negative - * direction of the gradient. - * - * @param iterate Parameters that minimize the function. - * @param v Unbiased estimator of the gradient. - * @param gradient The current gradient matrix at time t. - * @param gradient0 The old gradient matrix at time t - 1. - * @param batchSize Batch size to be used for the given iteration. - * @param stepSize Step size to be used for the given iteration. - * @param vNorm The norm of the full gradient. - */ - bool Update(arma::mat& iterate, - arma::mat& v, - const arma::mat& gradient, - const arma::mat& gradient0, - const size_t batchSize, - const double stepSize, - const double /* vNorm */) - { - v += (gradient - gradient0) / (double) batchSize; - iterate -= stepSize * v; - return false; - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/cyclic_descent.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/cyclic_descent.hpp deleted file mode 100644 index 57db3b099..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/cyclic_descent.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @file cyclic_descent.hpp - * @author Shikhar Bhardwaj - * - * Cyclic descent policy for Stochastic Coordinate Descent (SCD). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SCD_DESCENT_POLICIES_CYCLIC_HPP -#define MLPACK_CORE_OPTIMIZERS_SCD_DESCENT_POLICIES_CYCLIC_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Cyclic descent policy for Stochastic Coordinate Descent(SCD). This - * descent scheme picks a the co-ordinate for the descent in a cyclic manner - * serially. - * - * For more information, see the following. - * @code - * @inproceedings{Shalev-Shwartz2009, - * author = {Shalev-Shwartz, Shai and Tewari, Ambuj}, - * title = {Stochastic Methods for L1 Regularized Loss Minimization}, - * booktitle = {Proceedings of the 26th Annual International Conference on - * Machine Learning}, - * series = {ICML '09}, - * year = {2009}, - * isbn = {978-1-60558-516-1} - * } - * @endcode - */ -class CyclicDescent -{ - public: - /** - * The DescentFeature method is used to get the descent coordinate for the - * current iteration. - * - * @tparam ResolvableFunctionType The type of the function to be optimized. - * @param iteration The iteration number for which the feature is to be - * obtained. - * @param iterate The current value of the decision variable. - * @param function The function to be optimized. - * @return The index of the coordinate to be descended. - */ - template - static size_t DescentFeature(const size_t iteration, - const arma::mat& /* iterate */, - const ResolvableFunctionType& function) - { - return iteration % function.NumFeatures(); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/greedy_descent.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/greedy_descent.hpp deleted file mode 100644 index 55ef4513b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/greedy_descent.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file greedy_descent.hpp - * @author Shikhar Bhardwaj - * - * Greedy descent policy for Stochastic Coordinate Descent (SCD). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SCD_DESCENT_POLICIES_GREEDY_HPP -#define MLPACK_CORE_OPTIMIZERS_SCD_DESCENT_POLICIES_GREEDY_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Greedy descent policy for Stochastic Co-ordinate Descent(SCD). This - * descent scheme picks a the co-ordinate for the descent with the maximum - * guaranteed descent, according to the Gauss-Southwell rule. This is a - * deterministic approach and is generally more expensive to calculate. - * - * For more information, refer to the following. - * @code - * @misc{Nutini2015, - * author = {Julie Nutini and Mark Schmidt and Issam H. - * Laradji and Michael Friedlander and Hoyt Koepke}, - * title = {Coordinate Descent Converges Faster with the Gauss-Southwell Rule - * Than Random Selection}, - * year = {2015}, - * eprint = {arXiv:1506.00552} - * } - * @endcode - */ -class GreedyDescent -{ - public: - /** - * The DescentFeature method is used to get the descent coordinate for the - * current iteration. - * - * @tparam ResolvableFunctionType The type of the function to be optimized. - * @param iteration The iteration number for which the feature is to be - * obtained. - * @param iterate The current value of the decision variable. - * @param function The function to be optimized. - * @return The index of the coordinate to be descended. - */ - template - static size_t DescentFeature(const size_t /* iteration */, - const arma::mat& iterate, - const ResolvableFunctionType& function) - { - size_t bestFeature = 0; - double bestDescent = 0; - for (size_t i = 0; i < function.NumFeatures(); ++i) - { - arma::sp_mat fGrad; - - function.PartialGradient(iterate, i, fGrad); - - double descent = arma::accu(fGrad); - if (descent > bestDescent) - { - bestFeature = i; - bestDescent = descent; - } - } - - return bestFeature; - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/random_descent.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/random_descent.hpp deleted file mode 100644 index ec780e133..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/descent_policies/random_descent.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file random_descent.hpp - * @author Shikhar Bhardwaj - * - * Random descent policy for Stochastic Coordinate Descent (SCD). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SCD_DESCENT_POLICIES_RANDOM_HPP -#define MLPACK_CORE_OPTIMIZERS_SCD_DESCENT_POLICIES_RANDOM_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Random descent policy for Stochastic Coordinate Descent(SCD). This - * descent scheme picks a the co-ordinate for the descent uniformly randomly. - * - * For more information, see the following. - * @code - * @inproceedings{ShalevShwartz2009, - * author = {Shalev-Shwartz, Shai and Tewari, Ambuj}, - * title = {Stochastic Methods for L1 Regularized Loss Minimization}, - * booktitle = {Proceedings of the 26th Annual International Conference on - * Machine Learning}, - * series = {ICML '09}, - * year = {2009}, - * isbn = {978-1-60558-516-1} - * } - * @endcode - */ -class RandomDescent -{ - public: - /** - * The DescentFeature method is used to get the descent coordinate for the - * current iteration of the SCD optimizer. For more information regarding the - * interface of this policy with the optimizer, have a look at the SCD - * implementation. - * - * @tparam ResolvableFunctionType The type of the function to be optimized. - * @param iteration The iteration number for which the feature is to be - * obtained. - * @param iterate The current value of the decision variable. - * @param function The function to be optimized. - * @return The index of the coordinate to be descended. - */ - template - static size_t DescentFeature(const size_t /* iteration */, - const arma::mat& /* iterate */, - const ResolvableFunctionType& function) - { - return mlpack::math::RandInt(function.NumFeatures()); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/scd.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/scd/scd.hpp deleted file mode 100644 index c4cd4e3c0..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/scd.hpp +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @file scd.hpp - * @author Shikhar Bhardwaj - * - * Stochastic Coordinate Descent (SCD). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SCD_SCD_HPP -#define MLPACK_CORE_OPTIMIZERS_SCD_SCD_HPP - -#include -#include "descent_policies/random_descent.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Stochastic Coordinate descent is a technique for minimizing a function by - * doing a line search along a single direction at the current point in the - * iteration. The direction (or "coordinate") can be chosen cyclically, randomly - * or in a greedy fashion(depending on the DescentPolicy). - * - * This optimizer is useful for problems with a smooth multivariate function - * where computing the entire gradient for an update is infeasable. CD method - * typically significantly outperform GD, especially on sparse problems with a - * very large number variables/coordinates. - * - * For more information, see the following. - * @code - * @inproceedings{Shalev-Shwartz2009, - * author = {Shalev-Shwartz, Shai and Tewari, Ambuj}, - * title = {Stochastic Methods for L1 Regularized Loss Minimization}, - * booktitle = {Proceedings of the 26th Annual International Conference on - * Machine Learning}, - * series = {ICML '09}, - * year = {2009}, - * isbn = {978-1-60558-516-1} - * } - * @endcode - * - * For SCD to work, the class must implement the following functions: - * - * size_t NumFeatures(); - * double Evaluate(const arma::mat& coordinates); - * void PartialGradient(const arma::mat& coordinates, - * const size_t j, - * arma::sp_mat& gradient); - * - * NumFeatures() should return the number of features in the decision variable. - * Evaluate gives the value of the loss function at the current decision - * variable and PartialGradient is used to evaluate the partial gradient with - * respect to the jth feature. - * - * @tparam DescentPolicy Descent policy to decide the order in which the - * coordinate for descent is selected. - */ -template -class SCD -{ - public: - /** - * Construct the SCD optimizer with the given function and parameters. The - * default value here are not necessarily good for every problem, so it is - * suggested that the values used are tailored for the task at hand. The - * maximum number of iterations refers to the maximum number of "descents" - * the algorithm does (in one iteration, the algorithm updates the - * decision variable numFeatures times). - * - * @param stepSize Step size for each iteration. - * @param maxIterations Maximum number of iterations allowed (0 means to - * limit). - * @param tolerance Maximum absolute tolerance to terminate the algorithm. - * @param updateInterval The interval at which the objective is to be - * reported and checked for convergence. - * @param descentPolicy The policy to use for picking up the coordinate to - * descend on. - */ - SCD(const double stepSize = 0.01, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const size_t updateInterval = 1e3, - const DescentPolicyType descentPolicy = DescentPolicyType()); - - /** - * Optimize the given function using stochastic coordinate descent. The - * given starting point will be modified to store the finishing point of - * the optimization, and the final objective value is returned. - * - * @tparam ResolvableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value at the final point. - */ - template - double Optimize(ResolvableFunctionType& function, arma::mat& iterate); - - //! Get the step size. - double StepSize() const { return stepSize; } - //! Modify the step size. - double& StepSize() { return stepSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get the update interval for reporting objective. - size_t UpdateInterval() const { return updateInterval; } - //! Modify the update interval for reporting objective. - size_t& UpdateInterval() { return updateInterval; } - - //! Get the descent policy. - DescentPolicyType DescentPolicy() const { return descentPolicy; } - //! Modify the descent policy. - DescentPolicyType& DescentPolicy() { return descentPolicy; } - - private: - //! The step size for each example. - double stepSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The tolerance for termination. - double tolerance; - - //! The update interval for reporting objective and testing for convergence. - size_t updateInterval; - - //! The descent policy used to pick the coordinates for the update. - DescentPolicyType descentPolicy; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "scd_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/scd_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/scd/scd_impl.hpp deleted file mode 100644 index a8d4877fe..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/scd/scd_impl.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @file scd_impl.hpp - * @author Shikhar Bhardwaj - * - * Implementation of stochastic coordinate descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SCD_SCD_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SCD_SCD_IMPL_HPP - -// In case it hasn't been included yet. -#include "scd.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -SCD::SCD( - const double stepSize, - const size_t maxIterations, - const double tolerance, - const size_t updateInterval, - const DescentPolicyType descentPolicy) : - stepSize(stepSize), - maxIterations(maxIterations), - tolerance(tolerance), - updateInterval(updateInterval), - descentPolicy(descentPolicy) -{ /* Nothing to do */ } - -//! Optimize the function (minimize). -template -template -double SCD::Optimize(ResolvableFunctionType& function, - arma::mat& iterate) -{ - // Make sure we have the methods that we need. - traits::CheckResolvableFunctionTypeAPI(); - - double overallObjective = 0; - double lastObjective = DBL_MAX; - - arma::sp_mat gradient; - - // Start iterating. - for (size_t i = 1; i != maxIterations; ++i) - { - // Get the coordinate to descend on. - size_t featureIdx = descentPolicy.DescentFeature(i, iterate, function); - - // Get the partial gradient with respect to this feature. - function.PartialGradient(iterate, featureIdx, gradient); - - // Update the decision variable with the partial gradient. - iterate.col(featureIdx) -= stepSize * gradient.col(featureIdx); - - // Check for convergence. - if (i % updateInterval == 0) - { - overallObjective = function.Evaluate(iterate); - - // Output current objective function. - Log::Info << "SCD: iteration " << i << ", objective " << overallObjective - << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "SCD: converged to " << overallObjective << "; terminating" - << " with failure. Try a smaller step size?" << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "SCD: minimized within tolerance " << tolerance << "; " - << "terminating optimization." << std::endl; - return overallObjective; - } - - lastObjective = overallObjective; - } - } - - Log::Info << "SCD: maximum iterations (" << maxIterations << ") reached; " - << "terminating optimization." << std::endl; - - // Calculate and return final objective. - return function.Evaluate(iterate); -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp.hpp deleted file mode 100644 index b8c329e62..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @file lrsdp.hpp - * @author Ryan Curtin - * - * An implementation of Monteiro and Burer's formulation of low-rank - * semidefinite programs (LR-SDP). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_HPP -#define MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_HPP - -#include -#include - -#include "lrsdp_function.hpp" - -namespace mlpack { -namespace optimization { - -/** - * LRSDP is the implementation of Monteiro and Burer's formulation of low-rank - * semidefinite programs (LR-SDP). This solver uses the augmented Lagrangian - * optimizer to solve low-rank semidefinite programs. - */ -template -class LRSDP -{ - public: - /** - * Create an LRSDP to be optimized. The solution will end up being a matrix - * of size (rows) x (rank). To construct each constraint and the objective - * function, use the function SDP() in order to access the SDPType object - * associated with this optimizer. - * - * @param numSparseConstraints Number of sparse constraints in the problem. - * @param numDenseConstraints Number of dense constraints in the problem. - * @param initialPoint Initial point of the optimization. - * @param maxIterations Maximum number of iterations. - */ - LRSDP(const size_t numSparseConstraints, - const size_t numDenseConstraints, - const arma::mat& initialPoint, - const size_t maxIterations = 1000); - - /** - * Create an LRSDP object with the given SDP problem to be solved, and the - * given initial point. Note that the SDP may be modified later by calling - * SDP() to access the object. - * - * TODO: this is currently not implemented. - * - * @param sdp SDP to be solved. - * @param initialPoint Initial point of the optimization. - * @param maxIterations Maximum number of iterations. - * - LRSDP(const SDPType& sdp, - const arma::mat& initialPoint, - const size_t maxIterations = 1000); - */ - - /** - * Optimize the LRSDP and return the final objective value. The given - * coordinates will be modified to contain the final solution. - * - * @param coordinates Starting coordinates for the optimization. - */ - double Optimize(arma::mat& coordinates); - - //! Return the SDP that will be solved. - const SDPType& SDP() const { return function.SDP(); } - //! Modify the SDP that will be solved. - SDPType& SDP() { return function.SDP(); } - - //! Return the function to be optimized. - const LRSDPFunction& Function() const { return function; } - //! Modify the function to be optimized. - LRSDPFunction& Function() { return function; } - - //! Return the augmented Lagrangian object. - const AugLagrangian& AugLag() const { return augLag; } - //! Modify the augmented Lagrangian object. - AugLagrangian& AugLag() { return augLag; } - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - private: - //! Augmented lagrangian optimizer. - AugLagrangian augLag; - //! Function to optimize, which the AugLagrangian object holds. - LRSDPFunction function; - //! The maximum number of iterations for optimization. - size_t maxIterations; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation -#include "lrsdp_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_function.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_function.hpp deleted file mode 100644 index 1ebb7369d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_function.hpp +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @file lrsdp_function.hpp - * @author Ryan Curtin - * @author Abhishek Laddha - * - * A class that represents the objective function which LRSDP optimizes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_FUNCTION_HPP -#define MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_FUNCTION_HPP - -#include -#include -#include - -namespace mlpack { -namespace optimization { - -/** - * The objective function that LRSDP is trying to optimize. - * - * Note: LRSDPfunction is designed and implemented to specifically work - * with a combination of AugLagrangian and L-BFGS optimizer. Implemenation - * of LRSDPFunction includes caching R * R^T matrix in order to avoid redundant - * computations(Specifically with above two optimizers) of R * R^T matrix - * through AugLagrangian optimizer call, as only L-BFGS takes part in updating - * R(coordinates) matrix. So, be careful while using LRSDP with some other - * optimizer. You may need to modify caching process of R * R^T matrix. - * See EvaluateImpl() in lrsdp_function_impl.hpp for more details. - */ -template -class LRSDPFunction -{ - public: - /** - * Construct the LRSDPFunction from the given SDP. - * - * @param sdp - * @param initialPoint - */ - LRSDPFunction(const SDPType& sdp, - const arma::mat& initialPoint); - - /** - * Construct the LRSDPFunction with the given initial point and number of - * constraints. Note n_cols of the initialPoint specifies the rank. - * - * Set the A_x, B_x, and C_x matrices for each constraint using the A_x(), - * B_x(), and C_x() functions, for x in {sparse, dense}. - * - * @param numSparseConstraints - * @param numDenseConstraints - * @param initialPoint - */ - LRSDPFunction(const size_t numSparseConstraints, - const size_t numDenseConstraints, - const arma::mat& initialPoint); - - /** - * Evaluate the objective function of the LRSDP (no constraints) at the given - * coordinates. - */ - double Evaluate(const arma::mat& coordinates) const; - - /** - * Evaluate the gradient of the LRSDP (no constraints) at the given - * coordinates. - */ - void Gradient(const arma::mat& coordinates, arma::mat& gradient) const; - - /** - * Evaluate a particular constraint of the LRSDP at the given coordinates. - */ - double EvaluateConstraint(const size_t index, - const arma::mat& coordinates) const; - /** - * Evaluate the gradient of a particular constraint of the LRSDP at the given - * coordinates. - */ - void GradientConstraint(const size_t index, - const arma::mat& coordinates, - arma::mat& gradient) const; - - //! Get the total number of constraints in the LRSDP. - size_t NumConstraints() const { return sdp.NumConstraints(); } - - //! Get the initial point of the LRSDP. - const arma::mat& GetInitialPoint() const { return initialPoint; } - - //! Return the SDP object representing the problem. - const SDPType& SDP() const { return sdp; } - - //! Modify the SDP object representing the problem. - SDPType& SDP() { return sdp; } - - //! Get R*R^T matrix. - const arma::mat& RRT() const { return rrt; } - - //! Modify R*R^T matrix. - arma::mat& RRT() { return rrt; } - - private: - //! SDP object representing the problem - SDPType sdp; - - //! Initial point. - arma::mat initialPoint; - - //! Cache R*R^T matrix. - arma::mat rrt; -}; - -// Declare specializations in lrsdp_function.cpp. -template <> -inline double AugLagrangianFunction>>::Evaluate( - const arma::mat& coordinates) const; - -template <> -inline double AugLagrangianFunction>>::Evaluate( - const arma::mat& coordinates) const; - -template <> -inline void AugLagrangianFunction>>::Gradient( - const arma::mat& coordinates, - arma::mat& gradient) const; - -template <> -inline void AugLagrangianFunction>>::Gradient( - const arma::mat& coordinates, - arma::mat& gradient) const; - -} // namespace optimization -} // namespace mlpack - -// Include implementation -#include "lrsdp_function_impl.hpp" - -#endif // MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_function_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_function_impl.hpp deleted file mode 100644 index f27c3d458..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_function_impl.hpp +++ /dev/null @@ -1,275 +0,0 @@ -/** - * @file lrsdp_function.cpp - * @author Ryan Curtin - * @author Abhishek Laddha - * - * Implementation of the LRSDPFunction class, and also template specializations - * for faster execution with the AugLagrangian optimizer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_FUNCTION_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_FUNCTION_IMPL_HPP - -#include "lrsdp_function.hpp" - -namespace mlpack { -namespace optimization { - -template -LRSDPFunction::LRSDPFunction(const SDPType& sdp, - const arma::mat& initialPoint): - sdp(sdp), - initialPoint(initialPoint) -{ - if (initialPoint.n_rows < initialPoint.n_cols) - Log::Warn << "LRSDPFunction::LRSDPFunction(): solution matrix will have " - << "more columns than rows. It may be more efficient to find the " - << "transposed solution." << std::endl; - - // Initialize R*R^T matrix. - rrt = initialPoint * trans(initialPoint); -} - -template -LRSDPFunction::LRSDPFunction(const size_t numSparseConstraints, - const size_t numDenseConstraints, - const arma::mat& initialPoint): - sdp(initialPoint.n_rows, numSparseConstraints, numDenseConstraints), - initialPoint(initialPoint) -{ - if (initialPoint.n_rows < initialPoint.n_cols) - Log::Warn << "LRSDPFunction::LRSDPFunction(): solution matrix will have " - << "more columns than rows. It may be more efficient to find the " - << "transposed solution." << std::endl; - - // Initialize R*R^T matrix. - rrt = initialPoint * trans(initialPoint); -} - -template -double LRSDPFunction::Evaluate(const arma::mat& /* coordinates */) - const -{ - // Note: We don't require to update the R*R^T matrix here as the current - // function is only used by AugLagrangian, which do not update the coordinates - // matrix. - return accu(SDP().C() % rrt); -} - -template -void LRSDPFunction::Gradient(const arma::mat& /* coordinates */, - arma::mat& /* gradient */) const -{ - Log::Fatal << "LRSDPFunction::Gradient() not implemented for arbitrary " - << "optimizers!" << std::endl; -} - -template -double LRSDPFunction::EvaluateConstraint( - const size_t index, - const arma::mat& coordinates) const -{ - // Note: We don't require to update the R*R^T matrix here as the current - // function is only used by AugLagrangian, which do not update the coordinates - // matrix. - - // Using cached R*R^T gives better optimization for sparse matrices. - if (index < SDP().NumSparseConstraints()) - return accu(SDP().SparseA()[index] % rrt) - SDP().SparseB()[index]; - const size_t index1 = index - SDP().NumSparseConstraints(); - - // For computation optimization we will be taking R^T * A first. - return trace((trans(coordinates) * SDP().DenseA()[index1]) * coordinates) - - SDP().DenseB()[index1]; -} - -template -void LRSDPFunction::GradientConstraint( - const size_t /* index */, - const arma::mat& /* coordinates */, - arma::mat& /* gradient */) const -{ - Log::Fatal << "LRSDPFunction::GradientConstraint() not implemented " - << "for arbitrary optimizers!" << std::endl; -} - -//! Utility function for updating R*R^T matrix. -//! Note: Caching R*R^T provide significant computation optimization -//! by reducing redundant R*R^T calculations in case of functions are not used -//! updating coordinates matrix, hence leaving R*R^T unchanged. -template -void UpdateRRT(LRSDPFunction& function, - const arma::mat& newrrt) -{ - function.RRT() = newrrt; -} - -//! Utility function for calculating part of the objective when AugLagrangian is -//! used with an LRSDPFunction. -template -static inline void -UpdateObjective(double& objective, - const arma::mat& rrt, - const std::vector& ais, - const arma::vec& bis, - const arma::vec& lambda, - const size_t lambdaOffset, - const double sigma) -{ - for (size_t i = 0; i < ais.size(); ++i) - { - // Take the trace subtracted by the b_i. - // Here taking R^T * A first is not recommended as we are already - // using pre-computed R * R^T. Taking R^T * A first will result in increase - // in number of computations. - const double constraint = accu(ais[i] % rrt) - bis[i]; - objective -= (lambda[lambdaOffset + i] * constraint); - objective += (sigma / 2.) * constraint * constraint; - } -} - -//! Utility function for calculating part of the gradient when AugLagrangian is -//! used with an LRSDPFunction. -template -static inline void -UpdateGradient(arma::mat& s, - const arma::mat& rrt, - const std::vector& ais, - const arma::vec& bis, - const arma::vec& lambda, - const size_t lambdaOffset, - const double sigma) -{ - for (size_t i = 0; i < ais.size(); ++i) - { - // Here taking R^T * A first is not recommended as we are already - // using pre-computed R * R^T. Taking R^T * A first will result in increase - // in number of computations. - const double constraint = accu(ais[i] % rrt) - bis[i]; - const double y = lambda[lambdaOffset + i] - sigma * constraint; - s -= y * ais[i]; - } -} - -template -static inline double -EvaluateImpl(LRSDPFunction& function, - const arma::mat& coordinates, - const arma::vec& lambda, - const double sigma) -{ - // We can calculate the entire objective in a smart way. - // L(R, y, s) = Tr(C * (R R^T)) - - // sum_{i = 1}^{m} (y_i (Tr(A_i * (R R^T)) - b_i)) + - // (sigma / 2) * sum_{i = 1}^{m} (Tr(A_i * (R R^T)) - b_i)^2 - - // Let's start with the objective: Tr(C * (R R^T)). - // Simple, possibly slow solution-- see below for optimization opportunity - // - // Note that Tr(C^T * (R R^T)) = Tr( (CR)^T * R ), so - // multiplying C * R first, and then taking the trace dot should be more - // memory efficient. - // - // Similarly for the constraints, taking R^T * A first should be - // more efficient. - // - // For computation optimization we will be taking R^T * C first. - // Objective function = Tr((R^T * C) * R) - - // Calculate R*R^T for updating cache. - const arma::mat rrt = coordinates * trans(coordinates); - - // Update R*R^T matrix. - // Note that we can only use this optimization in case of L-BFGS optimizer - // or any other similar optimizer which calls Evaluate() before Gradient() - // with same coordinates matrix and uses only Evaluate() to update - // coordinates matrix. - - // Note: In case optimizer also uses Gradient() for updating coordinates - // matrix than the same line of code can be used to update R*R^T through - // Gradient(). - UpdateRRT(function, rrt); - - // Optimized objective function. - double objective = trace((trans(coordinates) * function.SDP().C()) - * coordinates); - - // Now each constraint. - UpdateObjective(objective, rrt, function.SDP().SparseA(), - function.SDP().SparseB(), lambda, 0, sigma); - UpdateObjective(objective, rrt, function.SDP().DenseA(), - function.SDP().DenseB(), lambda, function.SDP().NumSparseConstraints(), - sigma); - - return objective; -} - -template -static inline void -GradientImpl(const LRSDPFunction& function, - const arma::mat& coordinates, - const arma::vec& lambda, - const double sigma, - arma::mat& gradient) -{ - // We can calculate the gradient in a smart way. - // L'(R, y, s) = 2 * S' * R - // with - // S' = C - sum_{i = 1}^{m} y'_i A_i - // y'_i = y_i - sigma * (Trace(A_i * (R R^T)) - b_i) - - // Directly reterive R*R^T from cache. - const arma::mat rrt = function.RRT(); - arma::mat s(function.SDP().C()); - - UpdateGradient( - s, rrt, function.SDP().SparseA(), function.SDP().SparseB(), - lambda, 0, sigma); - UpdateGradient( - s, rrt, function.SDP().DenseA(), function.SDP().DenseB(), - lambda, function.SDP().NumSparseConstraints(), sigma); - - gradient = 2 * s * coordinates; -} - -// Template specializations for function and gradient evaluation. -// Note that C++ does not allow partial specialization of class members, -// so we have to go about this in a somewhat round-about way. -template <> -inline double AugLagrangianFunction>>::Evaluate( - const arma::mat& coordinates) const -{ - return EvaluateImpl(function, coordinates, lambda, sigma); -} - -template <> -inline double AugLagrangianFunction>>::Evaluate( - const arma::mat& coordinates) const -{ - return EvaluateImpl(function, coordinates, lambda, sigma); -} - -template <> -inline void AugLagrangianFunction>>::Gradient( - const arma::mat& coordinates, - arma::mat& gradient) const -{ - GradientImpl(function, coordinates, lambda, sigma, gradient); -} - -template <> -inline void AugLagrangianFunction>>::Gradient( - const arma::mat& coordinates, - arma::mat& gradient) const -{ - GradientImpl(function, coordinates, lambda, sigma, gradient); -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_impl.hpp deleted file mode 100644 index c33c39984..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/lrsdp_impl.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @file lrsdp.cpp - * @author Ryan Curtin - * - * An implementation of Monteiro and Burer's formulation of low-rank - * semidefinite programs (LR-SDP). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_IMPL_HPP - -#include "lrsdp.hpp" - -namespace mlpack { -namespace optimization { - -template -LRSDP::LRSDP(const size_t numSparseConstraints, - const size_t numDenseConstraints, - const arma::mat& initialPoint, - const size_t maxIterations) : - function(numSparseConstraints, numDenseConstraints, initialPoint), - maxIterations(maxIterations) -{ } - -template -double LRSDP::Optimize(arma::mat& coordinates) -{ - augLag.Sigma() = 10; - augLag.Optimize(function, coordinates, maxIterations); - - return function.Evaluate(coordinates); -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/primal_dual.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/primal_dual.hpp deleted file mode 100644 index 6b2096bc1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/primal_dual.hpp +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @file primal_dual.hpp - * @author Stephen Tu - * - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SDP_PRIMAL_DUAL_HPP -#define MLPACK_CORE_OPTIMIZERS_SDP_PRIMAL_DUAL_HPP - -#include -#include - -namespace mlpack { -namespace optimization { - -/** - * Interface to a primal dual interior point solver. - * - * @tparam SDPType - */ -template -class PrimalDualSolver -{ - public: - /** - * Construct a new solver instance from a given SDP instance. - * Uses a random, positive initialization point. - * - * @param sdp Initialized SDP to be solved. - */ - PrimalDualSolver(const SDPType& sdp); - - /** - * Construct a new solver instance from a given SDP instance. Uses a random, - * positive initialization point. Both initialX and initialZ need to be - * positive definite matrices. - * - * @param sdp Initialized SDP to be solved. - * @param initialX - * @param initialYSparse - * @param initialYDense - * @param initialZ - */ - PrimalDualSolver(const SDPType& sdp, - const arma::mat& initialX, - const arma::vec& initialYSparse, - const arma::vec& initialYDense, - const arma::mat& initialZ); - - /** - * Invoke the optimization procedure, returning the converged values for the - * primal and dual variables. - * - * @param X - * @param ySparse - * @param yDense - * @param Z - */ - double Optimize(arma::mat& X, - arma::vec& ySparse, - arma::vec& yDense, - arma::mat& Z); - - /** - * Invoke the optimization procedure, and only return the primal variable. - * - * @param X - */ - double Optimize(arma::mat& X) - { - arma::vec ysparse, ydense; - arma::mat Z; - return Optimize(X, ysparse, ydense, Z); - } - - //! Return the underlying SDP instance. - const SDPType& SDP() const { return sdp; } - - //! Modify tau. Typical values are 0.99. - double& Tau() { return tau; } - - //! Modify the XZ tolerance. - double& NormXzTol() { return normXzTol; } - - //! Modify the primal infeasibility tolerance. - double& PrimalInfeasTol() { return primalInfeasTol; } - - //! Modify the dual infeasibility tolerance. - double& DualInfeasTol() { return dualInfeasTol; } - - //! Modify the maximum number of iterations to run before converging. - size_t& MaxIterations() { return maxIterations; } - - private: - //! The SDP problem instance to optimize. - SDPType sdp; - - //! Starting point for X. Needs to be positive definite. - arma::mat initialX; - - //! Starting lagrange multiplier for the sparse constraints. - arma::vec initialYsparse; - - //! Starting lagrange multiplier for the dense constraints. - arma::vec initialYdense; - - //! Starting point for Z, the complementary slack variable. Needs to be - //! positive definite. - arma::mat initialZ; - - //! The step size modulating factor. Needs to be a scalar in (0, 1). - double tau; - - //! The tolerance on the norm of XZ required before terminating. - double normXzTol; - - //! The tolerance required on the primal constraints required before - //! terminating. - double primalInfeasTol; - - //! The tolerance required on the dual constraint required before terminating. - double dualInfeasTol; - - //! Maximum number of iterations to run. Set to 0 for no limit. - size_t maxIterations; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "primal_dual_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/primal_dual_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/primal_dual_impl.hpp deleted file mode 100644 index 00fc31b7b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/primal_dual_impl.hpp +++ /dev/null @@ -1,484 +0,0 @@ -/** - * @file primal_dual_impl.hpp - * @author Stephen Tu - * - * Contains an implementation of the "XZ+ZX" primal-dual infeasible interior - * point method with a Mehrotra predictor-corrector update step presented and - * analyzed in: - * - * Primal-dual interior-point methods for semidefinite programming: - * Convergence rates, stability and numerical results. - * Farid Alizadeh, Jean-Pierre Haeberly, and Michael Overton. - * SIAM J. Optim. 1998. - * https://www.cs.nyu.edu/overton/papers/pdffiles/pdsdp.pdf - * - * We will refer to this paper as [AHO98] in this file. - * - * Note there are many optimizations that still need to be implemented. See the - * code comments for more details. - * - * Also note the current implementation assumes the SDP problem has a strictly - * feasible primal/dual point (and therefore the duality gap is zero), and - * that the constraint matrices are linearly independent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SDP_PRIMAL_DUAL_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SDP_PRIMAL_DUAL_IMPL_HPP - -#include "primal_dual.hpp" - -namespace mlpack { -namespace optimization { - -template -PrimalDualSolver::PrimalDualSolver(const SDPType& sdp) - : sdp(sdp), - initialX(arma::eye(sdp.N(), sdp.N())), - initialYsparse(arma::ones(sdp.NumSparseConstraints())), - initialYdense(arma::ones(sdp.NumDenseConstraints())), - initialZ(arma::eye(sdp.N(), sdp.N())), - tau(0.99), - normXzTol(1e-7), - primalInfeasTol(1e-7), - dualInfeasTol(1e-7), - maxIterations(1000) -{ /* Nothing to do. */ } - -template -PrimalDualSolver::PrimalDualSolver(const SDPType& sdp, - const arma::mat& initialX, - const arma::vec& initialYsparse, - const arma::vec& initialYdense, - const arma::mat& initialZ) - : sdp(sdp), - initialX(initialX), - initialYsparse(initialYsparse), - initialYdense(initialYdense), - initialZ(initialZ), - tau(0.99), - normXzTol(1e-7), - primalInfeasTol(1e-7), - dualInfeasTol(1e-7), - maxIterations(1000) -{ - arma::mat tmp; - - // Note that the algorithm we implement requires primal iterate X and - // dual multiplier Z to be positive definite (but not feasible). - - if (initialX.n_rows != sdp.N() || initialX.n_cols != sdp.N()) - Log::Fatal << "PrimalDualSolver::PrimalDualSolver(): " - << "initialX needs to be square n x n matrix." << std::endl; - - if (!arma::chol(tmp, initialX)) - Log::Fatal << "PrimalDualSolver::PrimalDualSolver(): " - << "initialX needs to be symmetric positive definite." << std::endl; - - if (initialYsparse.n_elem != sdp.NumSparseConstraints()) - Log::Fatal << "PrimalDualSolver::PrimalDualSolver(): " - << "initialYsparse needs to have the same length as the number of sparse " - << "constraints." << std::endl; - - if (initialYdense.n_elem != sdp.NumDenseConstraints()) - Log::Fatal << "PrimalDualSolver::PrimalDualSolver(): " - << "initialYdense needs to have the same length as the number of dense " - << "constraints." << std::endl; - - if (initialZ.n_rows != sdp.N() || initialZ.n_cols != sdp.N()) - Log::Fatal << "PrimalDualSolver::PrimalDualSolver(): " - << "initialZ needs to be square n x n matrix." << std::endl; - - if (!arma::chol(tmp, initialZ)) - Log::Fatal << "PrimalDualSolver::PrimalDualSolver(): " - << "initialZ needs to be symmetric positive definite." << std::endl; -} - -/** - * Compute - * - * alpha = min(1, tau * alphahat(A, dA)) - * - * where - * - * alphahat = sup{ alphahat : A + dA is psd } - * - * See (2.18) of [AHO98] for more details. - */ -static inline bool -Alpha(const arma::mat& A, const arma::mat& dA, double tau, double& alpha) -{ - arma::mat L; - if (!arma::chol(L, A, "lower")) - return false; - - arma::mat Linv; - if (!arma::inv(Linv, arma::trimatl(L))) - return false; - // TODO(stephentu): We only want the top eigenvalue, we should - // be able to do better than full eigen-decomposition. - const arma::vec evals = arma::eig_sym(-Linv * dA * Linv.t()); - const double alphahatinv = evals(evals.n_elem - 1); - double alphahat = 1. / alphahatinv; - if (alphahat < 0.) - // dA is PSD already - alphahat = 1.; - alpha = std::min(1., tau * alphahat); - return true; -} - -/** - * Solve the following Lyapunov equation (for X) - * - * AX + XA = H - * - * where A, H are symmetric matrices. - * - * TODO(stephentu): Note this method current uses arma's builtin arma::syl - * method, which is overkill for this situation. See Lemma 7.2 of [AHO98] for - * how to solve this Lyapunov equation using an eigenvalue decomposition of A. - * - */ -static inline void -SolveLyapunov(arma::mat& X, const arma::mat& A, const arma::mat& H) -{ - arma::syl(X, A, A, -H); -} - -/** - * Solve the following KKT system (2.10) of [AHO98]: - * - * [ 0 A^T I ] [ dsx ] = [ rd ] - * [ A 0 0 ] [ dy ] = [ rp ] - * [ E 0 F ] [ dsz ] = [ rc ] - * \---- M ----/ - * - * where - * - * A = [ Asparse ] - * [ Adense ] - * dy = [ dysparse dydense ] - * E = Z sym I - * F = X sym I - * - */ -static inline void -SolveKKTSystem(const arma::sp_mat& Asparse, - const arma::mat& Adense, - const arma::mat& Z, - const arma::mat& M, - const arma::mat& F, - const arma::vec& rp, - const arma::vec& rd, - const arma::vec& rc, - arma::vec& dsx, - arma::vec& dysparse, - arma::vec& dydense, - arma::vec& dsz) -{ - arma::mat Frd_rc_Mat, Einv_Frd_rc_Mat, - Einv_Frd_ATdy_rc_Mat, Frd_ATdy_rc_Mat; - arma::vec Einv_Frd_rc, Einv_Frd_ATdy_rc, dy; - - // Note: Whenever a formula calls for E^(-1) v for some v, we solve Lyapunov - // equations instead of forming an explicit inverse. - - // Compute the RHS of (2.12) - math::Smat(F * rd - rc, Frd_rc_Mat); - SolveLyapunov(Einv_Frd_rc_Mat, Z, 2. * Frd_rc_Mat); - math::Svec(Einv_Frd_rc_Mat, Einv_Frd_rc); - - arma::vec rhs = rp; - const size_t numConstraints = Asparse.n_rows + Adense.n_rows; - if (Asparse.n_rows) - rhs(arma::span(0, Asparse.n_rows - 1)) += Asparse * Einv_Frd_rc; - if (Adense.n_rows) - rhs(arma::span(Asparse.n_rows, numConstraints - 1)) += Adense * Einv_Frd_rc; - - // TODO(stephentu): use a more efficient method (e.g. LU decomposition) - if (!arma::solve(dy, M, rhs)) - Log::Fatal << "PrimalDualSolver::SolveKKTSystem(): Could not solve KKT " - << "system." << std::endl; - - if (Asparse.n_rows) - dysparse = dy(arma::span(0, Asparse.n_rows - 1)); - if (Adense.n_rows) - dydense = dy(arma::span(Asparse.n_rows, numConstraints - 1)); - - // Compute dx from (2.13) - math::Smat(F * (rd - Asparse.t() * dysparse - Adense.t() * dydense) - rc, - Frd_ATdy_rc_Mat); - SolveLyapunov(Einv_Frd_ATdy_rc_Mat, Z, 2. * Frd_ATdy_rc_Mat); - math::Svec(Einv_Frd_ATdy_rc_Mat, Einv_Frd_ATdy_rc); - dsx = -Einv_Frd_ATdy_rc; - - // Compute dz from (2.14) - dsz = rd - Asparse.t() * dysparse - Adense.t() * dydense; -} - -namespace private_ { - -// TODO(stephentu): should we move this somewhere more general? -template struct vectype { }; -template struct vectype> -{ typedef arma::Col type; }; -template struct vectype> -{ typedef arma::SpCol type; }; - -} // namespace private_ - -template -double -PrimalDualSolver::Optimize(arma::mat& X, - arma::vec& ysparse, - arma::vec& ydense, - arma::mat& Z) -{ - // TODO(stephentu): We need a method which deals with the case when the Ais - // are not linearly independent. - - const size_t n = sdp.N(); - const size_t n2bar = sdp.N2bar(); - - // Form the A matrix in (2.7). Note we explicitly handle - // sparse and dense constraints separately. - - arma::sp_mat Asparse(sdp.NumSparseConstraints(), n2bar); - arma::sp_vec Aisparse; - - for (size_t i = 0; i < sdp.NumSparseConstraints(); i++) - { - math::Svec(sdp.SparseA()[i], Aisparse); - Asparse.row(i) = Aisparse.t(); - } - - arma::mat Adense(sdp.NumDenseConstraints(), n2bar); - arma::vec Aidense; - for (size_t i = 0; i < sdp.NumDenseConstraints(); i++) - { - math::Svec(sdp.DenseA()[i], Aidense); - Adense.row(i) = Aidense.t(); - } - - typename private_::vectype::type sc; - math::Svec(sdp.C(), sc); - - X = initialX; - ysparse = initialYsparse; - ydense = initialYdense; - Z = initialZ; - - arma::vec sx, sz, dysparse, dydense, dsx, dsz; - arma::mat dX, dZ; - - math::Svec(X, sx); - math::Svec(Z, sz); - - arma::vec rp, rd, rc, gk; - - arma::mat Rc, F, Einv_F_AsparseT, Einv_F_AdenseT, Gk, - M, DualCheck; - - rp.set_size(sdp.NumConstraints()); - - Einv_F_AsparseT.set_size(n2bar, sdp.NumSparseConstraints()); - Einv_F_AdenseT.set_size(n2bar, sdp.NumDenseConstraints()); - M.set_size(sdp.NumConstraints(), sdp.NumConstraints()); - - double primalObj = 0., alpha, beta; - for (size_t iteration = 1; iteration != maxIterations; iteration++) - { - // Note: The Mehrotra PC algorithm works like this at a high level. - // We first solve a KKT system with mu=0. Then, we use the results - // of this KKT system to get a better estimate of mu and solve - // the KKT system again. Empirically, this PC step has been shown to - // significantly reduce the number of required iterations (and is used - // by most practical solver implementations). - - if (sdp.NumSparseConstraints()) - rp(arma::span(0, sdp.NumSparseConstraints() - 1)) = - sdp.SparseB() - Asparse * sx; - if (sdp.NumDenseConstraints()) - rp(arma::span(sdp.NumSparseConstraints(), sdp.NumConstraints() - 1)) = - sdp.DenseB() - Adense * sx; - - // Rd = C - Z - smat A^T y - rd = sc - sz - Asparse.t() * ysparse - Adense.t() * ydense; - - math::SymKronId(X, F); - - // We compute E^(-1) F A^T by solving Lyapunov equations. - // See (2.16). - for (size_t i = 0; i < sdp.NumSparseConstraints(); i++) - { - SolveLyapunov(Gk, Z, X * sdp.SparseA()[i] + sdp.SparseA()[i] * X); - math::Svec(Gk, gk); - Einv_F_AsparseT.col(i) = gk; - } - - for (size_t i = 0; i < sdp.NumDenseConstraints(); i++) - { - SolveLyapunov(Gk, Z, X * sdp.DenseA()[i] + sdp.DenseA()[i] * X); - math::Svec(Gk, gk); - Einv_F_AdenseT.col(i) = gk; - } - - // Form the M = A E^(-1) F A^T matrix (2.15) - // - // Since we split A up into its sparse and dense components, - // we have to handle each block separately. - if (sdp.NumSparseConstraints()) - { - M.submat(arma::span(0, sdp.NumSparseConstraints() - 1), - arma::span(0, sdp.NumSparseConstraints() - 1)) = - Asparse * Einv_F_AsparseT; - if (sdp.NumDenseConstraints()) - { - M.submat(arma::span(0, sdp.NumSparseConstraints() - 1), - arma::span(sdp.NumSparseConstraints(), - sdp.NumConstraints() - 1)) = - Asparse * Einv_F_AdenseT; - } - } - if (sdp.NumDenseConstraints()) - { - if (sdp.NumSparseConstraints()) - { - M.submat(arma::span(sdp.NumSparseConstraints(), - sdp.NumConstraints() - 1), - arma::span(0, - sdp.NumSparseConstraints() - 1)) = - Adense * Einv_F_AsparseT; - } - M.submat(arma::span(sdp.NumSparseConstraints(), - sdp.NumConstraints() - 1), - arma::span(sdp.NumSparseConstraints(), - sdp.NumConstraints() - 1)) = - Adense * Einv_F_AdenseT; - } - - const double sxdotsz = arma::dot(sx, sz); - - // TODO(stephentu): computing these alphahats should take advantage of - // the cholesky decomposition of X and Z which we should have available - // when we use more efficient methods above. - - // This solves step (1) of Section 7, the "predictor" step. - Rc = -0.5*(X*Z + Z*X); - math::Svec(Rc, rc); - SolveKKTSystem(Asparse, Adense, Z, M, F, rp, rd, rc, dsx, dysparse, dydense, - dsz); - math::Smat(dsx, dX); - math::Smat(dsz, dZ); - - // Step (2), determine step size lengths (alpha, beta) - bool success = Alpha(X, dX, tau, alpha); - if (!success) - { - Log::Warn << "PrimalDualSolver::Optimize(): cholesky decomposition of X " - << "failed! Terminating optimization."; - return primalObj; - } - - success = Alpha(Z, dZ, tau, beta); - if (!success) - { - Log::Warn << "PrimalDualSolver::Optimize(): cholesky decomposition of Z " - << "failed! Terminating optimization."; - return primalObj; - } - - // See (7.1) - const double sigma = - std::pow(arma::dot(X + alpha * dX, Z + beta * dZ) / sxdotsz, 3); - const double mu = sigma * sxdotsz / n; - - // Step (3), the "corrector" step. - Rc = mu*arma::eye(n, n) - 0.5*(X*Z + Z*X + dX*dZ + dZ*dX); - math::Svec(Rc, rc); - SolveKKTSystem(Asparse, Adense, Z, M, F, rp, rd, rc, dsx, dysparse, dydense, - dsz); - math::Smat(dsx, dX); - math::Smat(dsz, dZ); - if (!Alpha(X, dX, tau, alpha)) - { - Log::Warn << "PrimalDualSolver::Optimize(): cholesky decomposition of Z " - << "failed! Terminating optimization."; - return primalObj; - } - if (!Alpha(Z, dZ, tau, beta)) - { - Log::Warn << "PrimalDualSolver::Optimize(): cholesky decomposition of Z " - << "failed! Terminating optimization."; - return primalObj; - } - - // Iterate update - X += alpha * dX; - math::Svec(X, sx); - ysparse += beta * dysparse; - ydense += beta * dydense; - Z += beta * dZ; - math::Svec(Z, sz); - - // Below, we check the KKT conditions. Recall the KKT conditions are - // - // (1) Primal feasibility - // (2) Dual feasibility - // (3) XZ = 0 (slackness condition) - // - // If the KKT conditions are satisfied to a certain degree of precision, - // then we consider this a valid certificate of optimality and terminate. - // Otherwise, we proceed onwards. - - const double normXZ = arma::norm(X * Z, "fro"); - - const double sparsePrimalInfeas = arma::norm(sdp.SparseB() - Asparse * sx, - 2); - const double densePrimalInfeas = arma::norm(sdp.DenseB() - Adense * sx, 2); - const double primalInfeas = sqrt(sparsePrimalInfeas * sparsePrimalInfeas + - densePrimalInfeas * densePrimalInfeas); - - primalObj = arma::dot(sdp.C(), X); - - const double dualObj = arma::dot(sdp.SparseB(), ysparse) + - arma::dot(sdp.DenseB(), ydense); - const double dualityGap = primalObj - dualObj; - - // TODO(stephentu): this dual check is quite expensive, - // maybe make it optional? - DualCheck = Z - sdp.C(); - for (size_t i = 0; i < sdp.NumSparseConstraints(); i++) - DualCheck += ysparse(i) * sdp.SparseA()[i]; - for (size_t i = 0; i < sdp.NumDenseConstraints(); i++) - DualCheck += ydense(i) * sdp.DenseA()[i]; - const double dualInfeas = arma::norm(DualCheck, "fro"); - - Log::Debug - << "iter=" << iteration << ", " - << "primal=" << primalObj << ", " - << "dual=" << dualObj << ", " - << "gap=" << dualityGap << ", " - << "||XZ||=" << normXZ << ", " - << "primalInfeas=" << primalInfeas << ", " - << "dualInfeas=" << dualInfeas << ", " - << "mu=" << mu - << std::endl; - - if (normXZ <= normXzTol && primalInfeas <= primalInfeasTol && - dualInfeas <= dualInfeasTol) - return primalObj; - } - - Log::Warn << "PrimalDualSolver::Optimizer(): Did not converge after " - << maxIterations << " iterations!" << std::endl; - return primalObj; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/sdp.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/sdp.hpp deleted file mode 100644 index 4e25043cf..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/sdp.hpp +++ /dev/null @@ -1,143 +0,0 @@ -/** - * @file sdp.hpp - * @author Stephen Tu - * - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SDP_SDP_HPP -#define MLPACK_CORE_OPTIMIZERS_SDP_SDP_HPP - -#include -#include - -namespace mlpack { -namespace optimization { - -/** - * Specify an SDP in primal form - * - * min dot(C, X) - * s.t. dot(Ai, X) = bi, i=1,...,m, X >= 0 - * - * This representation allows the constraint matrices Ai to be specified as - * either dense matrices (arma::mat) or sparse matrices (arma::sp_mat). After - * initializing the SDP object, you will need to set the constraints yourself, - * via the SparseA(), SparseB(), DenseA(), DenseB(), and C() functions. Note - * that for each matrix you add to either SparseA() or DenseA(), you must add - * the corresponding b value to the corresponding vector SparseB() or DenseB(). - * - * The objective matrix (C) may be stored as either dense or sparse depending on - * the ObjectiveMatrixType parameter. - * - * @tparam ObjectiveMatrixType Should be either arma::mat or arma::sp_mat. - */ -template -class SDP -{ - public: - typedef ObjectiveMatrixType objective_matrix_type; - - /** - * Initialize this SDP to an empty state. To add constraints, you will have - * to modify the constraints via the SparseA(), DenseA(), SparseB(), DenseB(), - * and C() functions. For the sake of speed, there is no error checking, so - * if you specify an invalid SDP, whatever solver you use will gladly try to - * solve it! (And it will probably crash horribly.) - */ - SDP(); - - /** - * Initialize this SDP to one which structurally has size n. To set the - * constraints you will still need to access through SparseA(), DenseA(), - * SparseB(), DenseB(), and C(). Consider using move semantics to keep things - * fast. As with the previous constructor, there is no error checking for the - * sake of speed, so if you build an invalid SDP, whatever solver you use will - * gladly try to solve it! (And it will probably crash horribly.) - * - * @param n Number of rows (and columns) in the objective matrix C. - * @param numSparseConstraints Number of sparse constraints. - * @param numDenseConstraints Number of dense constraints. - */ - SDP(const size_t n, - const size_t numSparseConstraints, - const size_t numDenseConstraints); - - //! Return number of rows and columns in the objective matrix C. - size_t N() const { return c.n_rows; } - - size_t N2bar() const { return N() * (N() + 1) / 2; } - - //! Return the number of sparse constraints (constraints with sparse Ai) in - //! the SDP. - size_t NumSparseConstraints() const { return sparseB.n_elem; } - //! Return the number of dense constraints (constraints with dense Ai) in the - //! SDP. - size_t NumDenseConstraints() const { return denseB.n_elem; } - - //! Return the total number of constraints in the SDP. - size_t NumConstraints() const { return sparseB.n_elem + denseB.n_elem; } - - //! Modify the sparse objective function matrix (sparseC). - ObjectiveMatrixType& C() { return c; } - //! Return the sparse objective function matrix (sparseC). - const ObjectiveMatrixType& C() const { return c; } - - //! Return the vector of sparse A matrices (which correspond to the sparse - //! constraints). - const std::vector& SparseA() const { return sparseA; } - - //! Modify the vector of sparse A matrices (which correspond to the sparse - //! constraints). - std::vector& SparseA() { return sparseA; } - - //! Return the vector of dense A matrices (which correspond to the dense - //! constraints). - const std::vector& DenseA() const { return denseA; } - - //! Modify the vector of dense A matrices (which correspond to the dense - //! constraints). - std::vector& DenseA() { return denseA; } - - //! Return the vector of sparse B values. - const arma::vec& SparseB() const { return sparseB; } - //! Modify the vector of sparse B values. - arma::vec& SparseB() { return sparseB; } - - //! Return the vector of dense B values. - const arma::vec& DenseB() const { return denseB; } - //! Modify the vector of dense B values. - arma::vec& DenseB() { return denseB; } - - /** - * Check whether or not the constraint matrices are linearly independent. - * - * Warning: possibly very expensive check. - */ - bool HasLinearlyIndependentConstraints() const; - - private: - //! Objective function matrix c. - ObjectiveMatrixType c; - - //! A_i for each sparse constraint. - std::vector sparseA; - //! b_i for each sparse constraint. - arma::vec sparseB; - - //! A_i for each dense constraint. - std::vector denseA; - //! b_i for each dense constraint. - arma::vec denseB; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "sdp_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/sdp_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/sdp_impl.hpp deleted file mode 100644 index 88ec79d0a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sdp/sdp_impl.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file sdp_impl.hpp - * @author Stephen Tu - * - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SDP_SDP_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SDP_SDP_IMPL_HPP - -#include "sdp.hpp" - -namespace mlpack { -namespace optimization { - -template -SDP::SDP() : - c(), - sparseA(), - sparseB(), - denseA(), - denseB() -{ /* Nothing to do. */ } - -template -SDP::SDP(const size_t n, - const size_t numSparseConstraints, - const size_t numDenseConstraints) : - c(n, n), - sparseA(numSparseConstraints), - sparseB(numSparseConstraints), - denseA(numDenseConstraints), - denseB(numDenseConstraints) -{ - for (size_t i = 0; i < numSparseConstraints; i++) - sparseA[i].zeros(n, n); - for (size_t i = 0; i < numDenseConstraints; i++) - denseA[i].zeros(n, n); -} - -template -bool SDP::HasLinearlyIndependentConstraints() const -{ - // Very inefficient, should only be used for testing/debugging - - const size_t n2bar = N2bar(); - arma::mat A(NumConstraints(), n2bar); - if (A.n_rows > n2bar) - return false; - - for (size_t i = 0; i < NumSparseConstraints(); i++) - { - arma::vec sa; - math::Svec(arma::mat(SparseA()[i]), sa); - A.row(i) = sa.t(); - } - for (size_t i = 0; i < NumDenseConstraints(); i++) - { - arma::vec sa; - math::Svec(DenseA()[i], sa); - A.row(NumSparseConstraints() + i) = sa.t(); - } - - const arma::vec s = arma::svd(A); - return s(s.n_elem - 1) > 1e-5; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/decay_policies/no_decay.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/decay_policies/no_decay.hpp deleted file mode 100644 index fcb4a156a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/decay_policies/no_decay.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @file no_decay.hpp - * @author Marcus Edel - * - * Definition of the policy type for the decay class. - * - * You should define your own decay update that looks like NoDecay. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_OPTIMIZERS_MINIBATCH_SGD_DECAY_POLICIES_NO_DECAY_HPP -#define MLPACK_CORE_OPTIMIZERS_MINIBATCH_SGD_DECAY_POLICIES_NO_DECAY_HPP - -namespace mlpack { -namespace optimization { - -/** - * Definition of the NoDecay class. Use this as a template for your own. - */ -class NoDecay -{ - public: - /** - * This constructor is called before the first iteration. - */ - NoDecay() { } - - /** - * This function is called in each iteration after the policy update. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& /* iterate */, - double& /* stepSize */, - const arma::mat& /* gradient */) - { - // Nothing to do here. - } - - /** - * This function is called in each iteration after the SVRG update step. - * - * @param iterate Parameters that minimize the function. - * @param iterate0 The last function parameters at time t - 1. - * @param gradient The current gradient matrix at time t. - * @param fullGradient The computed full gradient. - * @param stepSize Step size to be used for the given iteration. - */ - void Update(const arma::mat& /* iterate */, - const arma::mat& /*iterate0 */, - const arma::mat& /* gradient */, - const arma::mat& /* fullGradient */, - const size_t /* numBatches */, - double& /* stepSize */) - { - // Nothing to do here. - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_MINIBATCH_SGD_DECAY_POLICIES_NO_DECAY_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/sgd.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/sgd.hpp deleted file mode 100644 index 523539ec7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/sgd.hpp +++ /dev/null @@ -1,215 +0,0 @@ -/** - * @file sgd.hpp - * @author Ryan Curtin - * @author Arun Reddy - * @author Abhinav Moudgil - * @author Sourabh Varshney - * - * Stochastic Gradient Descent (SGD). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGD_SGD_HPP -#define MLPACK_CORE_OPTIMIZERS_SGD_SGD_HPP - -#include -#include "update_policies/vanilla_update.hpp" -#include "update_policies/momentum_update.hpp" -#include "update_policies/nesterov_momentum_update.hpp" -#include "decay_policies/no_decay.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Stochastic Gradient Descent is a technique for minimizing a function which - * can be expressed as a sum of other functions. That is, suppose we have - * - * \f[ - * f(A) = \sum_{i = 0}^{n} f_i(A) - * \f] - * - * and our task is to minimize \f$ A \f$. Stochastic gradient descent iterates - * over each function \f$ f_i(A) \f$, based on the specified update policy. By - * default vanilla update policy (see mlpack::optimization::VanillaUpdate) is - * used. The SGD class supports either scanning through each of the \f$ n \f$ - * functions \f$ f_i(A)\f$ linearly, or in a random sequence. The algorithm - * continues until \f$ j\f$ reaches the maximum number of iterations---or when a - * full sequence of updates through each of the \f$ n \f$ functions \f$ f_i(A) - * \f$ produces an improvement within a certain tolerance \f$ \epsilon \f$. - * That is, - * - * \f[ - * | f(A_{j + n}) - f(A_j) | < \epsilon. - * \f] - * - * The parameter \f$\epsilon\f$ is specified by the tolerance parameter to the - * constructor; \f$n\f$ is specified by the maxIterations parameter. - * - * This class is useful for data-dependent functions whose objective function - * can be expressed as a sum of objective functions operating on an individual - * point. Then, SGD considers the gradient of the objective function operating - * on an individual point in its update of \f$ A \f$. - * - * For SGD to work, a DecomposableFunctionType template parameter is required. - * This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - * - * @tparam UpdatePolicyType update policy used by SGD during the iterative update - * process. By default vanilla update policy (see - * mlpack::optimization::VanillaUpdate) is used. - * @tparam DecayPolicyType Decay policy used during the iterative update - * process to adjust the step size. By default the step size isn't going to - * be adjusted (i.e. NoDecay is used). - */ -template -class SGD -{ - public: - /** - * Construct the SGD optimizer with the given function and parameters. The - * defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Batch size to use for each step. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - * @param updatePolicy Instantiated update policy used to adjust the given - * parameters. - * @param decayPolicy Instantiated decay policy used to adjust the step size. - * @param resetPolicy Flag that determines whether update policy parameters - * are reset before every Optimize call. - */ - SGD(const double stepSize = 0.01, - const size_t batchSize = 32, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true, - const UpdatePolicyType& updatePolicy = UpdatePolicyType(), - const DecayPolicyType& decayPolicy = DecayPolicyType(), - const bool resetPolicy = true); - - /** - * Optimize the given function using stochastic gradient descent. The given - * starting point will be modified to store the finishing point of the - * algorithm, and the final objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, - arma::mat& iterate); - - //! Get the step size. - double StepSize() const { return stepSize; } - //! Modify the step size. - double& StepSize() { return stepSize; } - - //! Get the batch size. - size_t BatchSize() const { return batchSize; } - //! Modify the batch size. - size_t& BatchSize() { return batchSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return shuffle; } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return shuffle; } - - //! Get whether or not the update policy parameters - //! are reset before Optimize call. - bool ResetPolicy() const { return resetPolicy; } - //! Modify whether or not the update policy parameters - //! are reset before Optimize call. - bool& ResetPolicy() { return resetPolicy; } - - //! Get the update policy. - const UpdatePolicyType& UpdatePolicy() const { return updatePolicy; } - //! Modify the update policy. - UpdatePolicyType& UpdatePolicy() { return updatePolicy; } - - //! Get the step size decay policy. - const DecayPolicyType& DecayPolicy() const { return decayPolicy; } - //! Modify the step size decay policy. - DecayPolicyType& DecayPolicy() { return decayPolicy; } - - private: - //! The step size for each example. - double stepSize; - - //! The batch size for processing. - size_t batchSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The tolerance for termination. - double tolerance; - - //! Controls whether or not the individual functions are shuffled when - //! iterating. - bool shuffle; - - //! The update policy used to update the parameters in each iteration. - UpdatePolicyType updatePolicy; - - //! The decay policy used to update the step size. - DecayPolicyType decayPolicy; - - //! Flag indicating whether update policy - //! should be reset before running optimization. - bool resetPolicy; -}; - -using StandardSGD = SGD; - -using MomentumSGD = SGD; - -using NesterovMomentumSGD = SGD; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "sgd_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/sgd_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/sgd_impl.hpp deleted file mode 100644 index c9ef5ae1f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/sgd_impl.hpp +++ /dev/null @@ -1,147 +0,0 @@ -/** - * @file sgd_impl.hpp - * @author Ryan Curtin - * @author Arun Reddy - * @author Abhinav Moudgil - * - * Implementation of stochastic gradient descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGD_SGD_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SGD_SGD_IMPL_HPP - -// In case it hasn't been included yet. -#include "sgd.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -SGD::SGD( - const double stepSize, - const size_t batchSize, - const size_t maxIterations, - const double tolerance, - const bool shuffle, - const UpdatePolicyType& updatePolicy, - const DecayPolicyType& decayPolicy, - const bool resetPolicy) : - stepSize(stepSize), - batchSize(batchSize), - maxIterations(maxIterations), - tolerance(tolerance), - shuffle(shuffle), - updatePolicy(updatePolicy), - decayPolicy(decayPolicy), - resetPolicy(resetPolicy) -{ /* Nothing to do. */ } - -//! Optimize the function (minimize). -template -template -double SGD::Optimize( - DecomposableFunctionType& function, - arma::mat& iterate) -{ - typedef Function FullFunctionType; - FullFunctionType& f(static_cast(function)); - - // Make sure we have all the methods that we need. - traits::CheckDecomposableFunctionTypeAPI(); - - // Find the number of functions to use. - const size_t numFunctions = f.NumFunctions(); - - // To keep track of where we are and how things are going. - size_t currentFunction = 0; - double overallObjective = 0; - double lastObjective = DBL_MAX; - - // Initialize the update policy. - if (resetPolicy) - updatePolicy.Initialize(iterate.n_rows, iterate.n_cols); - - // Now iterate! - arma::mat gradient(iterate.n_rows, iterate.n_cols); - const size_t actualMaxIterations = (maxIterations == 0) ? - std::numeric_limits::max() : maxIterations; - for (size_t i = 0; i < actualMaxIterations; /* incrementing done manually */) - { - // Is this iteration the start of a sequence? - if ((currentFunction % numFunctions) == 0 && i > 0) - { - // Output current objective function. - Log::Info << "SGD: iteration " << i << ", objective " << overallObjective - << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "SGD: converged to " << overallObjective << "; terminating" - << " with failure. Try a smaller step size?" << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "SGD: minimized within tolerance " << tolerance << "; " - << "terminating optimization." << std::endl; - return overallObjective; - } - - // Reset the counter variables. - lastObjective = overallObjective; - overallObjective = 0; - currentFunction = 0; - - if (shuffle) // Determine order of visitation. - f.Shuffle(); - } - - // Find the effective batch size; we have to take the minimum of three - // things: - // - the batch size can't be larger than the user-specified batch size; - // - the batch size can't be larger than the number of iterations left - // before actualMaxIterations is hit; - // - the batch size can't be larger than the number of functions left. - const size_t effectiveBatchSize = std::min( - std::min(batchSize, actualMaxIterations - i), - numFunctions - currentFunction); - - // Technically we are computing the objective before we take the step, but - // for many FunctionTypes it may be much quicker to do it like this. - overallObjective += f.EvaluateWithGradient(iterate, currentFunction, - gradient, effectiveBatchSize); - - // Use the update policy to take a step. - updatePolicy.Update(iterate, stepSize, gradient); - - // Now update the learning rate if requested by the user. - decayPolicy.Update(iterate, stepSize, gradient); - - i += effectiveBatchSize; - currentFunction += effectiveBatchSize; - } - - Log::Info << "SGD: maximum iterations (" << maxIterations << ") reached; " - << "terminating optimization." << std::endl; - - // Calculate final objective. - overallObjective = 0; - for (size_t i = 0; i < numFunctions; i += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - i); - overallObjective += f.Evaluate(iterate, i, effectiveBatchSize); - } - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/gradient_clipping.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/gradient_clipping.hpp deleted file mode 100644 index fbdb8b7d8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/gradient_clipping.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file gradient_clipping.hpp - * @author Konstantin Sidorov - * - * Gradient clipping update wrapper. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGD_GRADIENT_CLIPPING_HPP -#define MLPACK_CORE_OPTIMIZERS_SGD_GRADIENT_CLIPPING_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Interface for wrapping around update policies (e.g., VanillaUpdate) - * and feeding a clipped gradient to them instead of the normal one. - * (Clipping here is implemented as - * \f$ g_{\text{clipped}} = \max(g_{\text{min}}, \min(g_{\text{min}}, g))) \f$.) - * - * @tparam UpdatePolicy A type of UpdatePolicy that sould be wrapped around. - */ -template -class GradientClipping -{ - public: - /** - * Constructor for creating a GradientClipping instance. - * - * @param minGradient Minimum possible value of gradient element. - * @param maxGradient Maximum possible value of gradient element. - * @param updatePolicy An instance of the UpdatePolicyType - * used for actual optimization. - */ - GradientClipping(const double minGradient, - const double maxGradient, - UpdatePolicyType& updatePolicy) : - minGradient(minGradient), - maxGradient(maxGradient), - updatePolicy(updatePolicy) - { - // Nothing to do here - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. Here we just do whatever initialization - * is needed for the actual update policy. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - updatePolicy.Initialize(rows, cols); - } - - /** - * Update step. First, the gradient is clipped, and then the actual update - * policy does whatever update it needs to do. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // First, clip the gradient. - arma::mat clippedGradient = arma::clamp(gradient, minGradient, maxGradient); - // And only then do the update. - updatePolicy.Update(iterate, stepSize, clippedGradient); - } - - //! Get the update policy. - UpdatePolicyType& UpdatePolicy() const { return updatePolicy; } - //! Modify the update policy. - UpdatePolicyType& UpdatePolicy() { return updatePolicy; } - - //! Get the minimum gradient value. - double MinGradient() const { return minGradient; } - //! Modify the minimum gradient value. - double& MinGradient() { return minGradient; } - - //! Get the maximum gradient value. - double MaxGradient() const { return maxGradient; } - //! Modify the maximum gradient value. - double& MaxGradient() { return maxGradient; } - - private: - //! Minimum possible value of gradient element. - double minGradient; - - //! Maximum possible value of gradient element. - double maxGradient; - - //! An instance of the UpdatePolicy used for actual optimization. - UpdatePolicyType updatePolicy; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/momentum_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/momentum_update.hpp deleted file mode 100644 index f9960d8e7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/momentum_update.hpp +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file momentum_update.hpp - * @author Arun Reddy - * - * Momentum update for Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGD_MOMENTUM_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_SGD_MOMENTUM_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Momentum update policy for Stochastic Gradient Descent (SGD). - * - * Learning with SGD can sometimes be slow. Using momentum update for parameter - * learning can accelerate the rate of convergence, specifically in the cases - * where the surface curves much more steeply(a steep hilly terrain with high - * curvature). The momentum algorithm introduces a new velocity vector \f$ v - * \f$ with the same dimension as the parameter \f$ A \f$. Also it introduces a - * new decay hyperparameter momentum \f$ mu \in (0,1] \f$. The following update - * scheme is used to update SGD in every iteration: - * - * \f[ - * v = mu*v - \alpha \nabla f_i(A) - * A_{j + 1} = A_j + v - * \f] - * - * where \f$ \alpha \f$ is a parameter which specifies the step size. \f$ i \f$ - * is chosen according to \f$ j \f$ (the iteration number). Common values of - * \f$ mu \f$ include 0.5, 0.9 and 0.99. Typically it begins with a small value - * and later raised. - * - * For more information, please refer to the Section 8.3.2 of the following book - * - * @code - * @article{rumelhart1988learning, - * title = {Learning representations by back-propagating errors}, - * author = {Rumelhart, David E. and Hinton, Geoffrey E. and - * Williams, Ronald J.}, - * journal = {Cognitive Modeling}, - * volume = {5}, - * number = {3}, - * pages = {1}, - * year = {1988} - * } - * - * @code - * @book{Goodfellow-et-al-2016, - * title = {Deep Learning}, - * author = {Ian Goodfellow and Yoshua Bengio and Aaron Courville}, - * publisher = {MIT Press}, - * note = {\url{http://www.deeplearningbook.org}}, - * year = {2016} - * } - */ -class MomentumUpdate -{ - public: - /** - * Construct the momentum update policy with given momentum decay parameter. - * - * @param momentum The momentum decay hyperparameter - */ - MomentumUpdate(const double momentum = 0.5) : momentum(momentum) - { /* Do nothing. */ }; - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. In the momentum update policy the velocity - * matrix is initialized to the zeros matrix with the same size as the - * gradient matrix (see mlpack::optimization::SGD::Optimizer ) - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - // Initialize am empty velocity matrix. - velocity = arma::zeros(rows, cols); - } - - /** - * Update step for SGD. The momentum term makes the convergence faster on the - * way as momentum term increases for dimensions pointing in the same and - * reduces updates for dimensions whose gradients change directions. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - velocity = momentum * velocity - stepSize * gradient; - iterate += velocity; - } - - private: - // The momentum hyperparamter - double momentum; - // The velocity matrix. - arma::mat velocity; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/nesterov_momentum_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/nesterov_momentum_update.hpp deleted file mode 100644 index befb97491..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/nesterov_momentum_update.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @file nesterov_momentum_update.hpp - * @author Sourabh Varshney - * - * Nesterov Momentum Update for Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGD_NESTEROV_MOMENTUM_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_SGD_NESTEROV_MOMENTUM_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Nesterov Momentum update policy for Stochastic Gradient Descent (SGD). - * - * Learning with SGD can be slow. Applying Standard momentum can accelerate - * the rate of convergence. Nesterov Momentum application can accelerate the - * rate of convergence to O(1/k^2). - * - * @code - * @techreport{Nesterov1983, - * title = {A Method Of Solving A Convex Programming Problem With - * Convergence Rate O(1/K^2)}, - * author = {Yuri Nesterov}, - * institution = {Soviet Math. Dokl.}, - * volume = {27}, - * year = {1983}, - * } - * @endcode - */ -class NesterovMomentumUpdate -{ - public: - /** - * Construct the Nesterov Momentum update policy with the given parameters. - * - */ - NesterovMomentumUpdate(const double momentum = 0.5) : - momentum(momentum) - { - // Nothing to do. - } - - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. In the momentum update policy the velocity - * matrix is initialized to the zeros matrix with the same size as the - * gradient matrix (see mlpack::optimization::SGD::Optimizer ) - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - // Initialize an empty velocity matrix. - velocity = arma::zeros(rows, cols); - } - - /** - * Update step for SGD. The momentum term makes the convergence faster on the - * way as momentum term increases for dimensions pointing in the same direction - * and reduces updates for dimensions whose gradients change directions. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - velocity = momentum * velocity - stepSize * gradient; - - iterate += momentum * velocity - stepSize * gradient; - } - - //! Get the value used to initialize the momentum coefficient. - double Momentum() const { return momentum; } - //! Modify the value used to initialize the momentum coefficient. - double& Momentum() { return momentum; } - - private: - // The velocity matrix. - arma::mat velocity; - - // The Momentum coefficient. - double momentum; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/vanilla_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/vanilla_update.hpp deleted file mode 100644 index d76264864..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgd/update_policies/vanilla_update.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file vanilla_update.hpp - * @author Arun Reddy - * - * Vanilla update for Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGD_EMPTY_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_SGD_EMPTY_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Vanilla update policy for Stochastic Gradient Descent (SGD). The following - * update scheme is used to update SGD in every iteration: - * - * \f[ - * A_{j + 1} = A_j + \alpha \nabla f_i(A) - * \f] - * - * where \f$ \alpha \f$ is a parameter which specifies the step size. \f$ i \f$ - * is chosen according to \f$ j \f$ (the iteration number). - */ -class VanillaUpdate -{ - public: - /** - * The Initialize method is called by SGD Optimizer method before the start of - * the iteration update process. The vanilla update doesn't initialize - * anything. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t /* rows */, const size_t /* cols */) - { /* Do nothing. */ } - - /** - * Update step for SGD. The function parameters are updated in the negative - * direction of the gradient. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Perform the vanilla SGD update. - iterate -= stepSize * gradient; - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/cyclical_decay.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/cyclical_decay.hpp deleted file mode 100644 index afa3f9517..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/cyclical_decay.hpp +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @file cyclical_decay.hpp - * @author Marcus Edel - * - * Definition of the warm restart technique (SGDR) described in: - * "SGDR: Stochastic Gradient Descent with Warm Restarts" by - * I. Loshchilov et al. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_OPTIMIZERS_SGDR_CYCLICAL_DECAY_HPP -#define MLPACK_CORE_OPTIMIZERS_SGDR_CYCLICAL_DECAY_HPP - -namespace mlpack { -namespace optimization { - -/** - * Simulate a new warm-started run/restart once a number of epochs are - * performed. Importantly, the restarts are not performed from scratch but - * emulated by increasing the step size while the old step size value of as an - * initial parameter. - * - * For more information, please refer to: - * - * @code - * @article{Loshchilov2016, - * title = {Learning representations by back-propagating errors}, - * author = {Ilya Loshchilov and Frank Hutter}, - * title = {{SGDR:} Stochastic Gradient Descent with Restarts}, - * journal = {CoRR}, - * year = {2016}, - * url = {https://arxiv.org/abs/1608.03983} - * } - * @endcode - */ -class CyclicalDecay -{ - public: - /** - * Construct the CyclicalDecay technique a restart method, where the - * step size decays after each batch and peridically resets to its initial - * value. - * - * @param epochRestart Initial epoch where decay is applied. - * @param multFactor Factor to increase the number of epochs before a restart. - * @param stepSize Initial step size for each restart. - * @param batchSize Size of each mini-batch. - * @param numFunctions The number of separable functions (the number of - * predictor points). - */ - CyclicalDecay(const size_t epochRestart, - const double multFactor, - const double stepSize) : - epochRestart(epochRestart), - multFactor(multFactor), - constStepSize(stepSize), - nextRestart(epochRestart), - batchRestart(0), - epochBatches(0), - epoch(0) - { /* Nothing to do here */ } - - /** - * This function is called in each iteration after the policy update. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& /* iterate */, - double& stepSize, - const arma::mat& /* gradient */) - { - // Time to adjust the step size. - if (epoch >= epochRestart) - { - // n_t = n_min^i + 0.5(n_max^i - n_min^i)(1 + cos(T_cur/T_i * pi)). - stepSize = 0.5 * constStepSize * (1 + cos((batchRestart / epochBatches) - * M_PI)); - - // Keep track of the number of batches since the last restart. - batchRestart++; - } - - // Time to restart. - if (epoch > nextRestart) - { - batchRestart = 0; - - // Adjust the period of restarts. - epochRestart *= multFactor; - - // Update the time for the next restart. - nextRestart += epochRestart; - } - - epoch++; - } - - //! Get the step size. - double StepSize() const { return constStepSize; } - //! Modify the step size. - double& StepSize() { return constStepSize; } - - //! Get the restart fraction. - double EpochBatches() const { return epochBatches; } - //! Modify the restart fraction. - double& EpochBatches() { return epochBatches; } - - private: - //! Epoch where decay is applied. - size_t epochRestart; - - //! Parameter to increase the number of epochs before a restart. - double multFactor; - - //! The step size for each example. - double constStepSize; - - //! Locally-stored restart time. - size_t nextRestart; - - //! Locally-stored number of batches since the last restart. - size_t batchRestart; - - //! Locally-stored restart fraction. - double epochBatches; - - //! Locally-stored epoch. - size_t epoch; -}; - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_SGDR_CYCLICAL_DECAY_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/sgdr.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/sgdr.hpp deleted file mode 100644 index 15eddbb6e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/sgdr.hpp +++ /dev/null @@ -1,144 +0,0 @@ -/** - * @file sgdr.hpp - * @author Marcus Edel - * - * Definition of the Stochastic Gradient Descent with Restarts (SGDR) as - * described in: "SGDR: Stochastic Gradient Descent with Warm Restarts" by - * I. Loshchilov et al. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGDR_SGDR_HPP -#define MLPACK_CORE_OPTIMIZERS_SGDR_SGDR_HPP - -#include - -#include -#include -#include "cyclical_decay.hpp" - -namespace mlpack { -namespace optimization { - -/** - * This class is based on Mini-batch Stochastic Gradient Descent class and - * simulates a new warm-started run/restart once a number of epochs are - * performed. - * - * For more information, please refer to: - * - * @code - * @article{Loshchilov2016, - * title = {{SGDR:} Stochastic Gradient Descent with Restarts}, - * author = {Ilya Loshchilov and Frank Hutter}, - * journal = {CoRR}, - * year = {2016}, - * url = {https://arxiv.org/abs/1608.03983} - * } - * @endcode - * - * @tparam UpdatePolicyType Update policy used during the iterative update - * process. By default the momentum update policy - * (see mlpack::optimization::MomentumUpdate) is used. - */ -template -class SGDR -{ - public: - //! Convenience typedef for the internal optimizer construction. - using OptimizerType = SGD; - - /** - * Construct the SGDR optimizer with the given function and - * parameters. The defaults here are not necessarily good for the given - * problem, so it is suggested that the values used be tailored for the task - * at hand. The maximum number of iterations refers to the maximum number of - * mini-batches that are processed. - * - * @param epochRestart Initial epoch where decay is applied. - * @param batchSize Size of each mini-batch. - * @param stepSize Step size for each iteration. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the mini-batch order is shuffled; otherwise, each - * mini-batch is visited in linear order. - * @param updatePolicy Instantiated update policy used to adjust the given - * parameters. - */ - SGDR(const size_t epochRestart = 50, - const double multFactor = 2.0, - const size_t batchSize = 1000, - const double stepSize = 0.01, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true, - const UpdatePolicyType& updatePolicy = UpdatePolicyType()); - - /** - * Optimize the given function using SGDR. The given starting point - * will be modified to store the finishing point of the algorithm, and the - * final objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to be optimized. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the batch size. - size_t BatchSize() const { return optimizer.BatchSize(); } - //! Modify the batch size. - size_t& BatchSize() { return optimizer.BatchSize(); } - - //! Get the step size. - double StepSize() const { return optimizer.StepSize(); } - //! Modify the step size. - double& StepSize() { return optimizer.StepSize(); } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return optimizer.MaxIterations(); } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return optimizer.MaxIterations(); } - - //! Get the tolerance for termination. - double Tolerance() const { return optimizer.Tolerance(); } - //! Modify the tolerance for termination. - double& Tolerance() { return optimizer.Tolerance(); } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return optimizer.Shuffle(); } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return optimizer.Shuffle(); } - - //! Get the update policy. - const UpdatePolicyType& UpdatePolicy() const - { - return optimizer.UpdatePolicy(); - } - //! Modify the update policy. - UpdatePolicyType& UpdatePolicy() - { - return optimizer.UpdatePolicy(); - } - - private: - //! The size of each mini-batch. - size_t batchSize; - - //! Locally-stored optimizer instance. - OptimizerType optimizer; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "sgdr_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/sgdr_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/sgdr_impl.hpp deleted file mode 100644 index aa917634e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/sgdr_impl.hpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file sgdr_impl.hpp - * @author Marcus Edel - * - * Implementation of SGDR method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGDR_SGDR_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SGDR_SGDR_IMPL_HPP - -// In case it hasn't been included yet. -#include "sgdr.hpp" - -namespace mlpack { -namespace optimization { - -template -SGDR::SGDR( - const size_t epochRestart, - const double multFactor, - const size_t batchSize, - const double stepSize, - const size_t maxIterations, - const double tolerance, - const bool shuffle, - const UpdatePolicyType& updatePolicy) : - batchSize(batchSize), - optimizer(OptimizerType(stepSize, - batchSize, - maxIterations, - tolerance, - shuffle, - updatePolicy, - CyclicalDecay( - epochRestart, - multFactor, - stepSize))) -{ - /* Nothing to do here */ -} - -template -template -double SGDR::Optimize( - DecomposableFunctionType& function, - arma::mat& iterate) -{ - // If a user changed the step size he hasn't update the step size of the - // cyclical decay instantiation, so we have to do it here. - if (optimizer.StepSize() != optimizer.DecayPolicy().StepSize()) - { - optimizer.DecayPolicy().StepSize() = optimizer.StepSize(); - } - - optimizer.DecayPolicy().EpochBatches() = function.NumFunctions() / - double(optimizer.BatchSize()); - - // If a user changed the batch size we have to update the restart fraction - // of the cyclical decay instantiation. - if (optimizer.BatchSize() != batchSize) - { - batchSize = optimizer.BatchSize(); - } - - return optimizer.Optimize(function, iterate); -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_ensembles.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_ensembles.hpp deleted file mode 100644 index 66f264881..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_ensembles.hpp +++ /dev/null @@ -1,176 +0,0 @@ -/** - * @file snapshot_ensembles.hpp - * @author Marcus Edel - * - * Definition of the Snapshot ensembles technique described in: - * "Snapshot ensembles: Train 1, get m for free" by G. Huang et al. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_OPTIMIZERS_SGDR_SNAPSHOT_ENSEMBLES_HPP -#define MLPACK_CORE_OPTIMIZERS_SGDR_SNAPSHOT_ENSEMBLES_HPP - -namespace mlpack { -namespace optimization { - -/** - * Simulate a new warm-started run/restart once a number of epochs are - * performed. Importantly, the restarts are not performed from scratch but - * emulated by increasing the step size while the old step size value of as an - * initial parameter. - * - * For more information, please refer to: - * - * @code - * @inproceedings{Huang2017, - * title = {Snapshot ensembles: Train 1, get m for free}, - * author = {Gao Huang, Yixuan Li, Geoff Pleiss, Zhuang Liu, - * John E. Hopcroft, and Kilian Q. Weinberger}, - * booktitle = {Proceedings of the International Conference on Learning - * Representations (ICLR)}, - * year = {2017}, - * url = {https://arxiv.org/abs/1704.00109} - * } - * @endcode - */ -class SnapshotEnsembles -{ - public: - /** - * Construct the CyclicalDecay technique a restart method, where the - * step size decays after each batch and peridically resets to its initial - * value. - * - * @param epochRestart Initial epoch where decay is applied. - * @param multFactor Factor to increase the number of epochs before a restart. - * @param stepSize Initial step size for each restart. - * @param batchSize Size of each mini-batch. - * @param numFunctions The number of separable functions (the number of - * predictor points). - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param snapshots Maximum number of snapshots. - */ - SnapshotEnsembles(const size_t epochRestart, - const double multFactor, - const double stepSize, - const size_t maxIterations, - const size_t snapshots) : - epochRestart(epochRestart), - multFactor(multFactor), - constStepSize(stepSize), - nextRestart(epochRestart), - batchRestart(0), - epoch(0) - { - snapshotEpochs = 0; - for (size_t i = 0, er = epochRestart, nr = nextRestart; - i < maxIterations; ++i) - { - if (i > nr) - { - er *= multFactor; - nr += er; - snapshotEpochs++; - } - } - - snapshotEpochs = epochRestart * std::pow(multFactor, - snapshotEpochs - snapshots + 1); - } - - /** - * This function is called in each iteration after the policy update. - * - * @param iterate Parameters that minimize the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - double& stepSize, - const arma::mat& /* gradient */) - { - // Time to adjust the step size. - if (epoch >= epochRestart) - { - // n_t = n_min^i + 0.5(n_max^i - n_min^i)(1 + cos(T_cur/T_i * pi)). - stepSize = 0.5 * constStepSize * (1 + cos((batchRestart / epochBatches) - * M_PI)); - - // Keep track of the number of batches since the last restart. - batchRestart++; - } - - // Time to restart. - if (epoch > nextRestart) - { - batchRestart = 0; - - // Adjust the period of restarts. - epochRestart *= multFactor; - - // Create a new snapshot. - if (epochRestart >= snapshotEpochs) - { - snapshots.push_back(iterate); - } - - // Update the time for the next restart. - nextRestart += epochRestart; - } - - epoch++; - } - - //! Get the step size. - double StepSize() const { return constStepSize; } - //! Modify the step size. - double& StepSize() { return constStepSize; } - - //! Get the restart fraction. - double EpochBatches() const { return epochBatches; } - //! Modify the restart fraction. - double& EpochBatches() { return epochBatches; } - - //! Get the snapshots. - std::vector Snapshots() const { return snapshots; } - //! Modify the snapshots. - std::vector& Snapshots() { return snapshots; } - - private: - //! Epoch where decay is applied. - size_t epochRestart; - - //! Parameter to increase the number of epochs before a restart. - double multFactor; - - //! The step size for each example. - double constStepSize; - - //! Locally-stored restart time. - size_t nextRestart; - - //! Locally-stored number of batches since the last restart. - size_t batchRestart; - - //! Locally-stored restart fraction. - double epochBatches; - - //! Locally-stored epoch. - size_t epoch; - - //! Epochs where a new snapshot is created. - size_t snapshotEpochs; - - //! Locally-stored parameter snapshots. - std::vector snapshots; -}; - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_SGDR_CYCLICAL_DECAY_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_sgdr.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_sgdr.hpp deleted file mode 100644 index 1847db26f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_sgdr.hpp +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @file snapshots_sgdr.hpp - * @author Marcus Edel - * - * Definition of the Stochastic Gradient Descent with Restarts (SGDR) as - * described in: "SGDR: Stochastic Gradient Descent with Warm Restarts" by - * I. Loshchilov et al and the Snapshot ensembles technique described in: - * "Snapshot ensembles: Train 1, get m for free" by G. Huang et al. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGDR_SNAPSHOT_SGDR_HPP -#define MLPACK_CORE_OPTIMIZERS_SGDR_SNAPSHOT_SGDR_HPP - -#include - -#include -#include -#include "snapshot_ensembles.hpp" - -namespace mlpack { -namespace optimization { - -/** - * This class is based on Mini-batch Stochastic Gradient Descent class and - * simulates a new warm-started run/restart once a number of epochs are - * performed using the Snapshot ensembles technique. - * - * For more information, please refer to: - * - * @code - * @article{Loshchilov2016, - * title = {{SGDR:} Stochastic Gradient Descent with Restarts}, - * author = {Ilya Loshchilov and Frank Hutter}, - * journal = {CoRR}, - * year = {2016}, - * url = {https://arxiv.org/abs/1608.03983} - * } - * @endcode - * - * @code - * @inproceedings{Huang2017, - * title = {Snapshot ensembles: Train 1, get m for free}, - * author = {Gao Huang, Yixuan Li, Geoff Pleiss, Zhuang Liu, - * John E. Hopcroft, and Kilian Q. Weinberger}, - * booktitle = {Proceedings of the International Conference on Learning - * Representations (ICLR)}, - * year = {2017}, - * url = {https://arxiv.org/abs/1704.00109} - * } - * @endcode - * - * @tparam UpdatePolicyType Update policy used during the iterative update - * process. By default the momentum update policy - * (see mlpack::optimization::MomentumUpdate) is used. - */ -template -class SnapshotSGDR -{ - public: - //! Convenience typedef for the internal optimizer construction. - using OptimizerType = SGD; - - /** - * Construct the SnapshotSGDR optimizer with snapshot ensembles with the given - * function and parameters. The defaults here are not necessarily good for - * the given problem, so it is suggested that the values used be tailored for - * the task at hand. The maximum number of iterations refers to the maximum - * number of mini-batches that are processed. - * - * @param epochRestart Initial epoch where decay is applied. - * @param batchSize Size of each mini-batch. - * @param stepSize Step size for each iteration. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the mini-batch order is shuffled; otherwise, each - * mini-batch is visited in linear order. - * @param snapshots Maximum number of snapshots. - * @param accumulate Accumulate the snapshot parameter (default true). - * @param updatePolicy Instantiated update policy used to adjust the given - * parameters. - */ - SnapshotSGDR(const size_t epochRestart = 50, - const double multFactor = 2.0, - const size_t batchSize = 1000, - const double stepSize = 0.01, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true, - const size_t snapshots = 5, - const bool accumulate = true, - const UpdatePolicyType& updatePolicy = UpdatePolicyType()); - - /** - * Optimize the given function using SGDR. The given starting point - * will be modified to store the finishing point of the algorithm, and the - * final objective value is returned. - * - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the batch size. - size_t BatchSize() const { return optimizer.BatchSize(); } - //! Modify the batch size. - size_t& BatchSize() { return optimizer.BatchSize(); } - - //! Get the step size. - double StepSize() const { return optimizer.StepSize(); } - //! Modify the step size. - double& StepSize() { return optimizer.StepSize(); } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return optimizer.MaxIterations(); } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return optimizer.MaxIterations(); } - - //! Get the tolerance for termination. - double Tolerance() const { return optimizer.Tolerance(); } - //! Modify the tolerance for termination. - double& Tolerance() { return optimizer.Tolerance(); } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return optimizer.Shuffle(); } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return optimizer.Shuffle(); } - - //! Get the snapshots. - std::vector Snapshots() const - { - return optimizer.DecayPolicy().Snapshots(); - } - //! Modify the snapshots. - std::vector& Snapshots() - { - return optimizer.DecayPolicy().Snapshots(); - } - - //! Get the update policy. - const UpdatePolicyType& UpdatePolicy() const - { - return optimizer.UpdatePolicy(); - } - //! Modify the update policy. - UpdatePolicyType& UpdatePolicy() - { - return optimizer.UpdatePolicy(); - } - - private: - //! The size of each mini-batch. - size_t batchSize; - - //! Whether or not to accumulate the snapshots. - bool accumulate; - - //! Locally-stored optimizer instance. - OptimizerType optimizer; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "snapshot_sgdr_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_sgdr_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_sgdr_impl.hpp deleted file mode 100644 index 17c4d3e12..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/sgdr/snapshot_sgdr_impl.hpp +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @file snapshots_sgdr_impl.hpp - * @author Marcus Edel - * - * Implementation of SGDR method using snapshots ensembles. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SGDR_SNAPSHOT_SGDR_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SGDR_SNAPSHOT_SGDR_IMPL_HPP - -// In case it hasn't been included yet. -#include "snapshot_sgdr.hpp" - -namespace mlpack { -namespace optimization { - -template -SnapshotSGDR::SnapshotSGDR( - const size_t epochRestart, - const double multFactor, - const size_t batchSize, - const double stepSize, - const size_t maxIterations, - const double tolerance, - const bool shuffle, - const size_t snapshots, - const bool accumulate, - const UpdatePolicyType& updatePolicy) : - batchSize(batchSize), - accumulate(accumulate), - optimizer(OptimizerType(stepSize, - batchSize, - maxIterations, - tolerance, - shuffle, - updatePolicy, - SnapshotEnsembles( - epochRestart, - multFactor, - stepSize, - maxIterations, - snapshots))) -{ - /* Nothing to do here */ -} - -template -template -double SnapshotSGDR::Optimize( - DecomposableFunctionType& function, - arma::mat& iterate) -{ - // If a user changed the step size he hasn't update the step size of the - // cyclical decay instantiation, so we have to do here. - if (optimizer.StepSize() != optimizer.DecayPolicy().StepSize()) - { - optimizer.DecayPolicy().StepSize() = optimizer.StepSize(); - } - - optimizer.DecayPolicy().EpochBatches() = function.NumFunctions() / - double(batchSize); - - // If a user changed the batch size we have to update the restart fraction - // of the cyclical decay instantiation. - if (optimizer.BatchSize() != batchSize) - { - batchSize = optimizer.BatchSize(); - } - - double overallObjective = optimizer.Optimize(function, iterate); - - // Accumulate snapshots. - if (accumulate) - { - for (size_t i = 0; i < optimizer.DecayPolicy().Snapshots().size(); ++i) - { - iterate += optimizer.DecayPolicy().Snapshots()[i]; - } - iterate /= (optimizer.DecayPolicy().Snapshots().size() + 1); - - // Calculate final objective. - overallObjective = 0; - for (size_t i = 0; i < function.NumFunctions(); ++i) - overallObjective += function.Evaluate(iterate, i, 1); - } - - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/smorms3/smorms3.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/smorms3/smorms3.hpp deleted file mode 100644 index 5d4448c15..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/smorms3/smorms3.hpp +++ /dev/null @@ -1,144 +0,0 @@ -/** - * @file smorms3.hpp - * @author Vivek Pal - * - * SMORMS3 i.e. squared mean over root mean squared cubed optimizer. It is a - * hybrid of RMSprop, which estimates a safe and optimal distance based on - * curvature and Yann LeCun’s method in "No more pesky learning rates". - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SMORMS3_SMORMS3_HPP -#define MLPACK_CORE_OPTIMIZERS_SMORMS3_SMORMS3_HPP - -#include -#include - -#include "smorms3_update.hpp" - -namespace mlpack { -namespace optimization { - -/** - * SMORMS3 is an optimizer that estimates a safe and optimal distance based on - * curvature and normalizing the stepsize in the parameter space. It is a hybrid - * of RMSprop and Yann LeCun’s method in "No more pesky learning rates". - * - * For more information, see the following. - * - * @code - * @misc{Funk2015, - * author = {Simon Funk}, - * title = {RMSprop loses to SMORMS3 - Beware the Epsilon!}, - * year = {2015} - * url = {http://sifter.org/~simon/journal/20150420.html} - * } - * @endcode - * - * - * For SMORMS3 to work, a DecomposableFunctionType template parameter is - * required. This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - */ -class SMORMS3 -{ - public: - /** - * Construct the SMORMS3 optimizer with the given function and parameters. The - * defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Number of points to process at each step. - * @param epsilon Value used to initialise the mean squared gradient - * parameter. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - */ - SMORMS3(const double stepSize = 0.001, - const size_t batchSize = 32, - const double epsilon = 1e-16, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const bool shuffle = true); - - /** - * Optimize the given function using SMORMS3. The given starting point will - * be modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate) - { - return optimizer.Optimize(function, iterate); - } - - //! Get the step size. - double StepSize() const { return optimizer.StepSize(); } - //! Modify the step size. - double& StepSize() { return optimizer.StepSize(); } - - //! Get the batch size. - size_t BatchSize() const { return optimizer.BatchSize(); } - //! Modify the batch size. - size_t& BatchSize() { return optimizer.BatchSize(); } - - //! Get the value used to initialise the mean squared gradient parameter. - double Epsilon() const { return optimizer.UpdatePolicy().Epsilon(); } - //! Modify the value used to initialise the mean squared gradient parameter. - double& Epsilon() { return optimizer.UpdatePolicy().Epsilon(); } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return optimizer.MaxIterations(); } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return optimizer.MaxIterations(); } - - //! Get the tolerance for termination. - double Tolerance() const { return optimizer.Tolerance(); } - //! Modify the tolerance for termination. - double& Tolerance() { return optimizer.Tolerance(); } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return optimizer.Shuffle(); } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return optimizer.Shuffle(); } - - private: - //! The Stochastic Gradient Descent object with SMORMS3Update update policy. - SGD optimizer; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/smorms3/smorms3_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/smorms3/smorms3_update.hpp deleted file mode 100644 index bffe47293..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/smorms3/smorms3_update.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file smorms3_update.hpp - * @author Vivek Pal - * - * SMORMS3 update for Stochastic Gradient Descent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SMORMS3_SMORMS3_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_SMORMS3_SMORMS3_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * SMORMS3 is an optimizer that estimates a safe and optimal distance based on - * curvature and normalizing the stepsize in the parameter space. It is a hybrid - * of RMSprop and Yann LeCun’s method in "No more pesky learning rates". - * - * For more information, see the following. - * - * @code - * @misc{Funk2015, - * author = {Simon Funk}, - * title = {RMSprop loses to SMORMS3 - Beware the Epsilon!}, - * year = {2015} - * url = {http://sifter.org/~simon/journal/20150420.html} - * } - * @endcode - */ - -class SMORMS3Update -{ - public: - /** - * Construct the SMORMS3 update policy with given epsilon parameter. - * - * @param epsilon Value used to initialise the mean squared gradient - * parameter. - */ - SMORMS3Update(const double epsilon = 1e-16) : epsilon(epsilon) - { /* Do nothing. */ } - - /** - * The Initialize method is called by SGD::Optimize method with UpdatePolicy - * SMORMS3Update before the start of the iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t rows, const size_t cols) - { - // Initialise the parameters mem, g and g2. - mem = arma::ones(rows, cols); - g = arma::zeros(rows, cols); - g2 = arma::zeros(rows, cols); - } - - /** - * Update step for SMORMS3. - * - * @param iterate Parameter that minimizes the function. - * @param stepSize Step size to be used for the given iteration. - * @param gradient The gradient matrix. - */ - void Update(arma::mat& iterate, - const double stepSize, - const arma::mat& gradient) - { - // Update the iterate. - arma::mat r = 1 / (mem + 1); - - g = (1 - r) % g; - g += r % gradient; - - g2 = (1 - r) % g2; - g2 += r % (gradient % gradient); - - arma::mat x = (g % g) / (g2 + epsilon); - - x.transform( [stepSize](double &v) { return std::min(v, stepSize); } ); - - iterate -= gradient % x / (arma::sqrt(g2) + epsilon); - - mem %= (1 - x); - mem += 1; - } - - //! Get the value used to initialise the mean squared gradient parameter. - double Epsilon() const { return epsilon; } - //! Modify the value used to initialise the mean squared gradient parameter. - double& Epsilon() { return epsilon; } - - private: - //! The value used to initialise the mean squared gradient parameter. - double epsilon; - - // The parameters mem, g and g2. - arma::mat mem, g, g2; -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_sgd.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_sgd.hpp deleted file mode 100644 index 5a5cb454f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_sgd.hpp +++ /dev/null @@ -1,228 +0,0 @@ -/** - * @file spalera_sgd.hpp - * @author Marcus Edel - * - * SPALeRA Stochastic Gradient Descent (SPALeRASGD). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SPALERA_SGD_SPALERA_SGD_HPP -#define MLPACK_CORE_OPTIMIZERS_SPALERA_SGD_SPALERA_SGD_HPP - -#include -#include -#include - -namespace mlpack { -namespace optimization { - -/** - * SPALeRA Stochastic Gradient Descent is a technique for minimizing a - * function which can be expressed as a sum of other functions. That is, - * suppose we have - * - * \f[ - * f(A) = \sum_{i = 0}^{n} f_i(A) - * \f] - * - * and our task is to minimize \f$ A \f$. SPALeRA SGD iterates over batches - * of functions \f$ \{ f_{i0}(A), f_{i1}(A), \ldots, f_{i(m - 1)}(A) \f$ for - * some batch size \f$ m \f$, producing the following update scheme: - * - * \f[ - * A_{j + 1} = A_j + \alpha \left(\sum_{k = 0}^{m - 1} \nabla f_{ik}(A) \right) - * \f] - * - * where \f$ \alpha \f$ is a parameter which specifies the step size. Each - * batch is passed through either sequentially or randomly. The algorithm - * continues until \f$ j \f$ reaches the maximum number of iterations---or when - * a full sequence of updates through each of the batches produces an - * improvement within a certain tolerance \f$ \epsilon \f$. - * - * The parameter \f$ \epsilon \f$ is specified by the tolerance parameter tot he - * constructor, as is the maximum number of iterations specified by the - * maxIterations parameter. - * - * This class is useful for data-dependent functions whose objective function - * can be expressed as a sum of objective functions operating on an individual - * point. Then, SPALeRA SGD considers the gradient of the objective function - * operation on an individual batches in its update of \f$ A \f$. - * - * For more information, please refer to: - * - * @code - * @misc{Schoenauer2017, - * title = {Stochastic Gradient Descent: - * Going As Fast As Possible But Not Faster}, - * author = {Schoenauer-Sebag, Alice; Schoenauer, Marc; Sebag, Michele}, - * journal = {CoRR}, - * year = {2017}, - * url = {https://arxiv.org/abs/1709.01427}, - * } - * @endcode - * - * For SPALeRA SGD to work, the lass must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, const size_t i); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient); - * - * NumFunctions() should return the number of functions, and in the other two - * functions, the parameter i refers to which individual function (or gradient) - * is being evaluated. So, for the case of a data-dependent function, such as - * NCA (see mlpack::nca::NCA), NumFunctions() should return the number of points - * in the dataset, and Evaluate(coordinates, 0) will evaluate the objective - * function on the first point in the dataset (presumably, the dataset is held - * internally in the DecomposableFunctionType). - * - * @tparam DecayPolicyType Decay policy used during the iterative update - * process to adjust the step size. By default the step size isn't going to - * be adjusted. - */ -template -class SPALeRASGD -{ - public: - /** - * Construct the SPALeRASGD optimizer with the given function and parameters. - * The defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Batch size to use for each step. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param lambda Page-Hinkley update parameter. - * @param alpha Memory parameter of the Agnostic Learning Rate adaptation. - * @param epsilon Numerical stability parameter. - * @param adaptRate Agnostic learning rate update rate. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - * @param decayPolicy Instantiated decay policy used to adjust the step size. - * @param resetPolicy Flag that determines whether update policy parameters - * are reset before every Optimize call. - */ - SPALeRASGD(const double stepSize = 0.01, - const size_t batchSize = 32, - const size_t maxIterations = 100000, - const double tolerance = 1e-5, - const double lambda = 0.01, - const double alpha = 0.001, - const double epsilon = 1e-6, - const double adaptRate = 3.10e-8, - const bool shuffle = true, - const DecayPolicyType& decayPolicy = DecayPolicyType(), - const bool resetPolicy = true); - - /** - * Optimize the given function using SPALeRA SGD. The given starting point - * will be modified to store the finishing point of the algorithm, and the - * final objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the batch size. - size_t BatchSize() const { return batchSize; } - //! Modify the batch size. - size_t& BatchSize() { return batchSize; } - - //! Get the step size. - double StepSize() const { return stepSize; } - //! Modify the step size. - double& StepSize() { return stepSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get the tolerance for termination. - double Alpha() const { return updatePolicy.Alpha(); } - //! Modify the tolerance for termination. - double& Alpha() { return updatePolicy.Alpha(); } - - //! Get the agnostic learning rate update rate. - double AdaptRate() const { return updatePolicy.AdaptRate(); } - //! Modify the agnostic learning rate update rate. - double& AdaptRate() { return updatePolicy.AdaptRate(); } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return shuffle; } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return shuffle; } - - //! Get whether or not the update policy parameters - //! are reset before Optimize call. - bool ResetPolicy() const { return resetPolicy; } - //! Modify whether or not the update policy parameters - //! are reset before Optimize call. - bool& ResetPolicy() { return resetPolicy; } - - //! Get the update policy. - SPALeRAStepsize UpdatePolicy() const { return updatePolicy; } - //! Modify the update policy. - SPALeRAStepsize& UpdatePolicy() { return updatePolicy; } - - //! Get the decay policy. - DecayPolicyType DecayPolicy() const { return decayPolicy; } - //! Modify the decay policy. - DecayPolicyType& DecayPolicy() { return decayPolicy; } - - private: - //! The step size for each example. - double stepSize; - - //! The batch size for processing. - size_t batchSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The tolerance for termination. - double tolerance; - - //! Page-Hinkley update parameter. - double lambda; - - //! Controls whether or not the individual functions are shuffled when - //! iterating. - bool shuffle; - - //! The update policy used to update the parameters in each iteration. - SPALeRAStepsize updatePolicy; - - //! The decay policy used to update the parameters in each iteration. - DecayPolicyType decayPolicy; - - //! Flag that determines whether update policy parameters - //! are reset before every Optimize call. - bool resetPolicy; -}; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "spalera_sgd_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_sgd_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_sgd_impl.hpp deleted file mode 100644 index c8368f8a3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_sgd_impl.hpp +++ /dev/null @@ -1,168 +0,0 @@ -/** - * @file spalera_sgd_impl.hpp - * @author Marcus Edel - * - * Implementation of SPALeRA SGD. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SPALERA_SGD_SPALERA_SGD_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SPALERA_SGD_SPALERA_SGD_IMPL_HPP - -// In case it hasn't been included yet. -#include "spalera_sgd.hpp" - -#include - -namespace mlpack { -namespace optimization { - -template -SPALeRASGD::SPALeRASGD(const double stepSize, - const size_t batchSize, - const size_t maxIterations, - const double tolerance, - const double lambda, - const double alpha, - const double epsilon, - const double adaptRate, - const bool shuffle, - const DecayPolicyType& decayPolicy, - const bool resetPolicy) : - stepSize(stepSize), - batchSize(batchSize), - maxIterations(maxIterations), - tolerance(tolerance), - lambda(lambda), - shuffle(shuffle), - updatePolicy(SPALeRAStepsize(alpha, epsilon, adaptRate)), - decayPolicy(decayPolicy), - resetPolicy(resetPolicy) -{ /* Nothing to do. */ } - -//! Optimize the function (minimize). -template -template -double SPALeRASGD::Optimize(DecomposableFunctionType& function, - arma::mat& iterate) -{ - typedef Function FullFunctionType; - FullFunctionType& f(static_cast(function)); - - traits::CheckDecomposableFunctionTypeAPI(); - - // Find the number of functions to use. - const size_t numFunctions = f.NumFunctions(); - - // To keep track of where we are and how things are going. - size_t currentFunction = 0; - double overallObjective = 0; - double lastObjective = DBL_MAX; - - // Calculate the first objective function. - for (size_t i = 0; i < numFunctions; i += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - i); - overallObjective += f.Evaluate(iterate, i, effectiveBatchSize); - } - - double currentObjective = overallObjective / numFunctions; - - // Initialize the update policy. - if (resetPolicy) - { - updatePolicy.Initialize(iterate.n_rows, iterate.n_cols, - currentObjective * lambda); - } - - // Now iterate! - arma::mat gradient(iterate.n_rows, iterate.n_cols); - const size_t actualMaxIterations = (maxIterations == 0) ? - std::numeric_limits::max() : maxIterations; - for (size_t i = 0; i < actualMaxIterations; /* incrementing done manually */) - { - // Is this iteration the start of a sequence? - if ((currentFunction % numFunctions) == 0) - { - // Output current objective function. - Log::Info << "SPALeRA SGD: iteration " << i << ", objective " - << overallObjective << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "SPALeRA SGD: converged to " << overallObjective - << "; terminating with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "SPALeRA SGD: minimized within tolerance " << tolerance - << "; terminating optimization." << std::endl; - return overallObjective; - } - - // Reset the counter variables. - lastObjective = overallObjective; - overallObjective = 0; - currentFunction = 0; - - if (shuffle) // Determine order of visitation. - f.Shuffle(); - } - - // Calculate gradient and objective. - // Find the effective batch size; we have to take the minimum of three - // things: - // - the batch size can't be larger than the user-specified batch size; - // - the batch size can't be larger than the number of iterations left - // before actualMaxIterations is hit; - // - the batch size can't be larger than the number of functions left. - const size_t effectiveBatchSize = std::min( - std::min(batchSize, actualMaxIterations - i), - numFunctions - currentFunction); - - currentObjective = f.EvaluateWithGradient(iterate, currentFunction, - gradient, effectiveBatchSize); - - // Use the update policy to take a step. - if (!updatePolicy.Update(stepSize, currentObjective, effectiveBatchSize, - numFunctions, iterate, gradient)) - { - Log::Warn << "SPALeRA SGD: converged to " << overallObjective << "; " - << "terminating with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - // Now update the learning rate if requested by the user. - decayPolicy.Update(iterate, stepSize, gradient); - - i += effectiveBatchSize; - currentFunction += effectiveBatchSize; - overallObjective += currentObjective; - currentObjective /= effectiveBatchSize; - } - - Log::Info << "SPALeRA SGD: maximum iterations (" << maxIterations - << ") reached; terminating optimization." << std::endl; - - // Calculate final objective. - overallObjective = 0; - for (size_t i = 0; i < numFunctions; i += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - i); - overallObjective += f.Evaluate(iterate, i, effectiveBatchSize); - } - - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_stepsize.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_stepsize.hpp deleted file mode 100644 index d5bfc527b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/spalera_sgd/spalera_stepsize.hpp +++ /dev/null @@ -1,227 +0,0 @@ -/** - * @file spalera_stepsize.hpp - * @author Marcus Edel - * - * Definition of the SPALeRA stepsize technique as described in: - * "Stochastic Gradient Descent: Going As Fast As Possible But Not Faster" by - * A. Schoenauer Sebag et al. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_OPTIMIZERS_SPALERA_SGD_SPALERA_STEPSIZE_HPP -#define MLPACK_CORE_OPTIMIZERS_SPALERA_SGD_SPALERA_STEPSIZE_HPP - -namespace mlpack { -namespace optimization { - -/** - * Definition of the SPALeRA stepize technique, which implementes a change - * detection mechanism with an agnostic adaptation scheme. - * - * For more information, please refer to: - * - * @code - * @misc{Schoenauer2017, - * title = {Stochastic Gradient Descent: - * Going As Fast As Possible But Not Faster}, - * author = {Schoenauer-Sebag, Alice; Schoenauer, Marc; Sebag, Michele}, - * journal = {CoRR}, - * year = {2017}, - * url = {https://arxiv.org/abs/1709.01427}, - * } - * @endcode - */ -class SPALeRAStepsize -{ - public: - /** - * Construct the SPALeRAStepsize object with the given parameters. - * The defaults here are not necessarily good for the given - * problem, so it is suggested that the values used be tailored to the task at - * hand. - * - * @param alpha Memory parameter of the agnostic learning rate adaptation. - * @param epsilon Numerical stability parameter. - * @param adaptRate Agnostic learning rate update rate. - */ - SPALeRAStepsize(const double alpha = 0.001, - const double epsilon = 1e-6, - const double adaptRate = 3.10e-8) : - alpha(alpha), - epsilon(epsilon), - adaptRate(adaptRate) - { - /* Nothing to do here. */ - } - - /** - * The Initialize method is called by SPALeRASGD Optimizer method before the - * start of the iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - * @param lambda Page-Hinkley update parameter. - */ - void Initialize(const size_t rows, const size_t cols, const double lambda) - { - learningRates = arma::ones(rows, cols); - relaxedSums = arma::zeros(rows, cols); - - this->lambda = lambda; - - mu0 = un = mn = relaxedObjective = phCounter = eveCounter = 0; - } - - /** - * This function is called in each iteration. - * - * @param stepSize Step size to be used for the given iteration. - * @param objective The current function loss. - * @param batchSize Batch size to be used for the given iteration. - * @param numFunctions The number of functions. - * @param iterate Parameters that minimize the function. - * @param gradient The gradient matrix. - * - * @return Stop or continue the learning process. - */ - bool Update(const double stepSize, - const double objective, - const size_t batchSize, - const size_t numFunctions, - arma::mat& iterate, - const arma::mat& gradient) - { - // The ratio of mini-batch size to training set size; needed for the - // Page-Hinkley relaxed objective computations. - const double mbRatio = batchSize / (double) numFunctions; - - // Page-Hinkley iteration, check if we have to reset the parameter and - // adjust the step size. - if (phCounter > (1 / mbRatio)) - { - relaxedObjective = (1 - mbRatio) * relaxedObjective + mbRatio * objective; - } - else - { - relaxedObjective = phCounter * relaxedObjective + objective; - relaxedObjective /= (phCounter + 1); - } - - // Update the mu0 parameter. - mu0 = phCounter * mu0 + relaxedObjective; - mu0 = mu0 / (phCounter + 1); - - // Update the un parameter. - un += relaxedObjective - mu0; - - // Updating the mn parameter. - if (un < mn) - mn = un; - - // If the condition is true we reset the parameter and update parameter. - if ((un - mn) > lambda) - { - // Backtracking, reset the parameter. - iterate = previousIterate; - - // Dividing learning rates by 2 as proposed in: - // Stochastic Gradient Descent: Going As Fast As Possible But Not Faster. - learningRates /= 2; - - if (arma::any(arma::vectorise(learningRates) <= 1e-15)) - { - // Stop because learning rate too low. - return false; - } - - // Reset evaluation and Page-Hinkley counter parameter. - mu0 = un = mn = relaxedObjective = phCounter = eveCounter = 0; - } - else - { - const double paramMean = (alpha / (2 - alpha) * - (1 - std::pow(1 - alpha, 2 * (eveCounter + 1)))) / iterate.n_elem; - - const double paramStd = (alpha / std::sqrt(iterate.n_elem)) / - std::sqrt(iterate.n_elem); - - const double normGradient = std::sqrt(arma::accu(arma::pow(gradient, 2))); - - relaxedSums *= (1 - alpha); - if (normGradient > epsilon) - relaxedSums += gradient * (alpha / normGradient); - - learningRates %= arma::exp((arma::pow(relaxedSums, 2) - paramMean) * - (adaptRate / paramStd)); - - previousIterate = iterate; - - iterate -= stepSize * (learningRates % gradient); - - // Keep track of the the number of evaluations and Page-Hinkley steps. - eveCounter++; - phCounter++; - } - - return true; - } - - //! Get the agnostic learning rate adaptation parameter. - double Alpha() const { return alpha; } - //! Modify the agnostic learning rate adaptation parameter. - double& Alpha() { return alpha; } - - //! Get the agnostic learning rate update rate. - double AdaptRate() const { return adaptRate; } - //! Modify the agnostic learning rate update rate. - double& AdaptRate() { return adaptRate; } - - private: - //! Page-Hinkley update parameter. - double mu0; - - //! Page-Hinkley update parameter. - double un; - - //! Page-Hinkley update parameter. - double mn; - - //! Page-Hinkley update parameter. - double relaxedObjective; - - //! Page-Hinkley step counter. - size_t phCounter; - - //! Evaluations step counter. - size_t eveCounter; - - //! Memory parameter of the agnostic learning rate adaptation. - double alpha; - - //! Numerical stability parameter. - double epsilon; - - //! Agnostic learning rate update rate. - double adaptRate; - - //! Locally-stored parameter wise learning rates. - arma::mat learningRates; - - //! Locally-stored parameter wise sums. - arma::mat relaxedSums; - - //! Page-Hinkley update parameter. - double lambda; - - //! Locally-stored previous parameter matrix (backtracking). - arma::mat previousIterate; -}; - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_SPALERA_SGD_SPALERA_STEPSIZE_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/barzilai_borwein_decay.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/barzilai_borwein_decay.hpp deleted file mode 100644 index a53108730..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/barzilai_borwein_decay.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file barzilai_borwein_decay.hpp - * @author Marcus Edel - * - * Barzilai-Borwein decay policy. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SVRG_BARZILIA_BORWEIN_DECAY_HPP -#define MLPACK_CORE_OPTIMIZERS_SVRG_BARZILIA_BORWEIN_DECAY_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Barzilai-Borwein decay policy for Stochastic variance reduced gradient - * (SVRG). - * - * For more information, please refer to: - * - * @code - * @incollection{Tan2016, - * title = {Barzilai-Borwein Step Size for Stochastic Gradient Descent}, - * author = {Tan, Conghui and Ma, Shiqian and Dai, Yu-Hong - * and Qian, Yuqiu}, - * booktitle = {Advances in Neural Information Processing Systems 29}, - * editor = {D. D. Lee and M. Sugiyama and U. V. Luxburg and I. Guyon - * and R. Garnett}, - * pages = {685--693}, - * year = {2016}, - * publisher = {Curran Associates, Inc.} - * } - * @endcode - */ -class BarzilaiBorweinDecay -{ - public: - /* - * Construct the Barzilai-Borwein decay policy. - * - * @param maxStepSize The maximum step size. - * @param eps The eps coefficient to avoid division by zero (numerical - * stability). - */ - BarzilaiBorweinDecay(const double maxStepSize = DBL_MAX, - const double eps = 1e-7) : - eps(eps), - maxStepSize(maxStepSize) - { /* Nothing to do. */} - - /** - * The Initialize method is called by SVRG Optimizer method before the start - * of the iteration update process. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t /* rows */, const size_t /* cols */) - { /* Do nothing. */ } - - /** - * Barzilai-Borwein update step for SVRG. - * - * @param iterate The current function parameter at time t. - * @param iterate0 The last function parameters at time t - 1. - * @param gradient The current gradient matrix at time t. - * @param fullGradient The computed full gradient. - * @param numBatches The number of batches. - * @param stepSize Step size to be used for the given iteration. - */ - void Update(const arma::mat& iterate, - const arma::mat& iterate0, - const arma::mat& /* gradient */, - const arma::mat& fullGradient, - const size_t numBatches, - double& stepSize) - { - if (!fullGradient0.is_empty()) - { - // Step size selection based on Barzilai-Borwein (BB). - stepSize = std::pow(arma::norm(iterate - iterate0), 2.0) / - (arma::dot(iterate - iterate0, fullGradient - fullGradient0) + eps) / - (double) numBatches; - - stepSize = std::min(stepSize, maxStepSize); - } - - fullGradient0 = std::move(fullGradient); - } - - private: - //! Locally-stored full gradient. - arma::mat fullGradient0; - - //! The value used for numerical stability. - double eps; - - //! The maximum step size. - double maxStepSize; -}; - -} // namespace optimization -} // namespace mlpack - -#endif // MLPACK_CORE_OPTIMIZERS_SVRG_BARZILIA_BORWEIN_DECAY_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg.hpp deleted file mode 100644 index c4a6ac61e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg.hpp +++ /dev/null @@ -1,247 +0,0 @@ -/** - * @file svrg.hpp - * @author Marcus Edel - * - * Stochastic variance reduced gradient (SVRG). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SVRG_SVRG_HPP -#define MLPACK_CORE_OPTIMIZERS_SVRG_SVRG_HPP - -#include -#include - -#include "svrg_update.hpp" -#include "barzilai_borwein_decay.hpp" - -namespace mlpack { -namespace optimization { - -/** - * Stochastic Variance Reduced Gradient is a technique for minimizing a function - * which can be expressed as a sum of other functions. That is, suppose we have - * - * \f[ - * f(A) = \sum_{i = 0}^{n} f_i(A) - * \f] - * - * and our task is to minimize \f$ A \f$. Stochastic Variance Reduced Gradient - * iterates over each function \f$ f_i(A) \f$, based on the specified update - * policy. By default vanilla update policy is used. The SVRG class supports - * either scanning through each of the \f$ n \f$ - * functions \f$ f_i(A)\f$ linearly, or in a random sequence. The algorithm - * continues until \f$ j\f$ reaches the maximum number of iterations---or when a - * full sequence of updates through each of the \f$ n \f$ functions \f$ f_i(A) - * \f$ produces an improvement within a certain tolerance \f$ \epsilon \f$. - * That is, - * - * \f[ - * | f(A_{j + n}) - f(A_j) | < \epsilon. - * \f] - * - * The parameter \f$\epsilon\f$ is specified by the tolerance parameter to the - * constructor; \f$n\f$ is specified by the maxIterations parameter. - * - * This class is useful for data-dependent functions whose objective function - * can be expressed as a sum of objective functions operating on an individual - * point. Then, SVRG considers the gradient of the objective function operating - * on an individual point in its update of \f$ A \f$. - * - * For SVRG to work, a DecomposableFunctionType template parameter is required. - * This class must implement the following function: - * - * size_t NumFunctions(); - * double Evaluate(const arma::mat& coordinates, - * const size_t i, - * const size_t batchSize); - * void Gradient(const arma::mat& coordinates, - * const size_t i, - * arma::mat& gradient, - * const size_t batchSize); - * - * NumFunctions() should return the number of functions (\f$n\f$), and in the - * other two functions, the parameter i refers to which individual function (or - * gradient) is being evaluated. So, for the case of a data-dependent function, - * such as NCA (see mlpack::nca::NCA), NumFunctions() should return the number - * of points in the dataset, and Evaluate(coordinates, 0) will evaluate the - * objective function on the first point in the dataset (presumably, the dataset - * is held internally in the DecomposableFunctionType). - * - * For more information, please refer to: - * - * @code - * @inproceedings{Johnson2013, - * author = {Johnson, Rie and Zhang, Tong}, - * title = {Accelerating Stochastic Gradient Descent Using Predictive - * Variance Reduction}, - * booktitle = {Proceedings of the 26th International Conference on Neural - * Information Processing Systems - Volume 1}, - * series = {NIPS'13}, - * year = {2013}, - * location = {Lake Tahoe, Nevada}, - * pages = {315--323}, - * numpages = {9}, - * publisher = {Curran Associates Inc.}, - * } - * @endcode - * - * @tparam UpdatePolicyType update policy used by SVRG during the iterative - * update process. By default vanilla update policy - * (see mlpack::optimization::VanillaUpdate) is used. - * @tparam DecayPolicyType Decay policy used during the iterative update - * process to adjust the step size. By default the step size isn't going to - * be adjusted (i.e. NoDecay is used). - */ -template -class SVRGType -{ - public: - /** - * Construct the SVRG optimizer with the given function and parameters. The - * defaults here are not necessarily good for the given problem, so it is - * suggested that the values used be tailored to the task at hand. The - * maximum number of iterations refers to the maximum number of points that - * are processed (i.e., one iteration equals one point; one iteration does not - * equal one pass over the dataset). - * - * @param stepSize Step size for each iteration. - * @param batchSize Batch size to use for each step. - * @param maxIterations Maximum number of iterations allowed (0 means no - * limit). - * @param innerIterations The number of inner iterations allowed (0 means - * n / batchSize). Note that the full gradient is only calculated in - * the outer iteration. - * @param tolerance Maximum absolute tolerance to terminate algorithm. - * @param shuffle If true, the function order is shuffled; otherwise, each - * function is visited in linear order. - * @param updatePolicy Instantiated update policy used to adjust the given - * parameters. - * @param decayPolicy Instantiated decay policy used to adjust the step size. - * @param resetPolicy Flag that determines whether update policy parameters - * are reset before every Optimize call. - */ - SVRGType(const double stepSize = 0.01, - const size_t batchSize = 32, - const size_t maxIterations = 1000, - const size_t innerIterations = 0, - const double tolerance = 1e-5, - const bool shuffle = true, - const UpdatePolicyType& updatePolicy = UpdatePolicyType(), - const DecayPolicyType& decayPolicy = DecayPolicyType(), - const bool resetPolicy = true); - - /** - * Optimize the given function using SVRG. The given starting point will be - * modified to store the finishing point of the algorithm, and the final - * objective value is returned. - * - * @tparam DecomposableFunctionType Type of the function to be optimized. - * @param function Function to optimize. - * @param iterate Starting point (will be modified). - * @return Objective value of the final point. - */ - template - double Optimize(DecomposableFunctionType& function, arma::mat& iterate); - - //! Get the step size. - double StepSize() const { return stepSize; } - //! Modify the step size. - double& StepSize() { return stepSize; } - - //! Get the batch size. - size_t BatchSize() const { return batchSize; } - //! Modify the batch size. - size_t& BatchSize() { return batchSize; } - - //! Get the maximum number of iterations (0 indicates no limit). - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations (0 indicates no limit). - size_t& MaxIterations() { return maxIterations; } - - //! Get the maximum number of iterations (0 indicates default n / b). - size_t InnerIterations() const { return innerIterations; } - //! Modify the maximum number of iterations (0 indicates default n / b). - size_t& InnerIterations() { return innerIterations; } - - //! Get the tolerance for termination. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for termination. - double& Tolerance() { return tolerance; } - - //! Get whether or not the individual functions are shuffled. - bool Shuffle() const { return shuffle; } - //! Modify whether or not the individual functions are shuffled. - bool& Shuffle() { return shuffle; } - - //! Get whether or not the update policy parameters - //! are reset before Optimize call. - bool ResetPolicy() const { return resetPolicy; } - //! Modify whether or not the update policy parameters - //! are reset before Optimize call. - bool& ResetPolicy() { return resetPolicy; } - - //! Get the update policy. - const UpdatePolicyType& UpdatePolicy() const { return updatePolicy; } - //! Modify the update policy. - UpdatePolicyType& UpdatePolicy() { return updatePolicy; } - - //! Get the step size decay policy. - const DecayPolicyType& DecayPolicy() const { return decayPolicy; } - //! Modify the step size decay policy. - DecayPolicyType& DecayPolicy() { return decayPolicy; } - - private: - //! The step size for each example. - double stepSize; - - //! The batch size for processing. - size_t batchSize; - - //! The maximum number of allowed iterations. - size_t maxIterations; - - //! The maximum number of allowed inner iterations per epoch. - size_t innerIterations; - - //! The tolerance for termination. - double tolerance; - - //! Controls whether or not the individual functions are shuffled when - //! iterating. - bool shuffle; - - //! The update policy used to update the parameters in each iteration. - UpdatePolicyType updatePolicy; - - //! The decay policy used to update the step size. - DecayPolicyType decayPolicy; - - //! Flag indicating whether update policy - //! should be reset before running optimization. - bool resetPolicy; -}; - -// Convenience typedefs. - -/** - * Standard stochastic variance reduced gradient. - */ -using SVRG = SVRGType; - -/** - * Stochastic variance reduced gradient with Barzilai-Borwein. - */ -using SVRG_BB = SVRGType; - -} // namespace optimization -} // namespace mlpack - -// Include implementation. -#include "svrg_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg_impl.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg_impl.hpp deleted file mode 100644 index 00bc1edfd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg_impl.hpp +++ /dev/null @@ -1,176 +0,0 @@ -/** - * @file svrg_impl.hpp - * @author Marcus Edel - * - * Implementation of stochastic variance reduced gradient (SVRG). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SVRG_SVRG_IMPL_HPP -#define MLPACK_CORE_OPTIMIZERS_SVRG_SVRG_IMPL_HPP - -// In case it hasn't been included yet. -#include "svrg.hpp" - -namespace mlpack { -namespace optimization { - -template -SVRGType::SVRGType( - const double stepSize, - const size_t batchSize, - const size_t maxIterations, - const size_t innerIterations, - const double tolerance, - const bool shuffle, - const UpdatePolicyType& updatePolicy, - const DecayPolicyType& decayPolicy, - const bool resetPolicy) : - stepSize(stepSize), - batchSize(batchSize), - maxIterations(maxIterations), - innerIterations(innerIterations), - tolerance(tolerance), - shuffle(shuffle), - updatePolicy(updatePolicy), - decayPolicy(decayPolicy), - resetPolicy(resetPolicy) -{ /* Nothing to do. */ } - -//! Optimize the function (minimize). -template -template -double SVRGType::Optimize( - DecomposableFunctionType& function, - arma::mat& iterate) -{ - // Find the number of functions to use. - const size_t numFunctions = function.NumFunctions(); - - // To keep track of where we are and how things are going. - double overallObjective = 0; - double lastObjective = DBL_MAX; - - // Set epoch length to n / b if the user asked for. - if (innerIterations == 0) - innerIterations = numFunctions; - - // Initialize the update policy. - if (resetPolicy) - updatePolicy.Initialize(iterate.n_rows, iterate.n_cols); - - // Now iterate! - arma::mat gradient(iterate.n_rows, iterate.n_cols); - arma::mat gradient0(iterate.n_rows, iterate.n_cols); - arma::mat iterate0; - - // Find the number of batches. - size_t numBatches = numFunctions / batchSize; - if (numFunctions % batchSize != 0) - ++numBatches; // Capture last few. - - const size_t actualMaxIterations = (maxIterations == 0) ? - std::numeric_limits::max() : maxIterations; - for (size_t i = 0; i < actualMaxIterations; ++i) - { - // Calculate the objective function. - overallObjective = 0; - for (size_t f = 0; f < numFunctions; f += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - f); - overallObjective += function.Evaluate(iterate, f, effectiveBatchSize); - } - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "SVRG: converged to " << overallObjective - << "; terminating with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "SVRG: minimized within tolerance " << tolerance - << "; terminating optimization." << std::endl; - return overallObjective; - } - - lastObjective = overallObjective; - - // Compute the full gradient. - size_t effectiveBatchSize = std::min(batchSize, numFunctions); - arma::mat fullGradient(iterate.n_rows, iterate.n_cols); - function.Gradient(iterate, 0, fullGradient, effectiveBatchSize); - for (size_t f = effectiveBatchSize; f < numFunctions; - /* incrementing done manually */) - { - // Find the effective batch size (the last batch may be smaller). - effectiveBatchSize = std::min(batchSize, numFunctions - f); - - function.Gradient(iterate, f, gradient, effectiveBatchSize); - fullGradient += gradient; - - f += effectiveBatchSize; - } - fullGradient /= (double) numFunctions; - - // Store current parameter for the calculation of the variance reduced - // gradient. - iterate0 = iterate; - - for (size_t f = 0, currentFunction = 0; f < innerIterations; - /* incrementing done manually */) - { - // Is this iteration the start of a sequence? - if ((currentFunction % numFunctions) == 0) - { - currentFunction = 0; - - // Determine order of visitation. - if (shuffle) - function.Shuffle(); - } - - // Find the effective batch size (the last batch may be smaller). - effectiveBatchSize = std::min(batchSize, numFunctions - currentFunction); - - // Calculate variance reduced gradient. - function.Gradient(iterate, currentFunction, gradient, - effectiveBatchSize); - function.Gradient(iterate0, currentFunction, gradient0, - effectiveBatchSize); - - // Use the update policy to take a step. - updatePolicy.Update(iterate, fullGradient, gradient, gradient0, - effectiveBatchSize, stepSize); - - currentFunction += effectiveBatchSize; - f += effectiveBatchSize; - } - - // Update the learning rate if requested by the user. - decayPolicy.Update(iterate, iterate0, gradient, fullGradient, numBatches, - stepSize); - } - - Log::Info << "SVRG: maximum iterations (" << maxIterations << ") reached; " - << "terminating optimization." << std::endl; - - // Calculate final objective. - overallObjective = 0; - for (size_t i = 0; i < numFunctions; i += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, numFunctions - i); - overallObjective += function.Evaluate(iterate, i, effectiveBatchSize); - } - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg_update.hpp b/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg_update.hpp deleted file mode 100644 index 1090ec2ed..000000000 --- a/src/sdk/mlpack/include/mlpack/core/optimizers/svrg/svrg_update.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file svrg_update.hpp - * @author Marcus Edel - * - * Vanilla update for stochastic variance reduced gradient (SVRG). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_OPTIMIZERS_SVRG_SVRG_UPDATE_HPP -#define MLPACK_CORE_OPTIMIZERS_SVRG_SVRG_UPDATE_HPP - -#include - -namespace mlpack { -namespace optimization { - -/** - * Vanilla update policy for Stochastic variance reduced gradient (SVRG). - * The following update scheme is used to update SGD in every iteration: - */ -class SVRGUpdate -{ - public: - /** - * The Initialize method is called by SVRG Optimizer method before the start - * of the iteration update process. The vanilla update doesn't initialize - * anything. - * - * @param rows Number of rows in the gradient matrix. - * @param cols Number of columns in the gradient matrix. - */ - void Initialize(const size_t /* rows */, const size_t /* cols */) - { /* Do nothing. */ } - - /** - * Update step for SVRG. The function parameters are updated in the negative - * direction of the gradient. - * - * @param iterate Parameters that minimize the function. - * @param fullGradient The computed full gradient. - * @param gradient The current gradient matrix at time t. - * @param gradient0 The old gradient matrix at time t - 1. - * @param batchSize Batch size to be used for the given iteration. - * @param stepSize Step size to be used for the given iteration. - */ - void Update(arma::mat& iterate, - const arma::mat& fullGradient, - const arma::mat& gradient, - const arma::mat& gradient0, - const size_t batchSize, - const double stepSize) - { - // Perform the vanilla SVRG update. - iterate -= stepSize * (fullGradient + (gradient - gradient0) / - (double) batchSize); - } -}; - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/address.hpp b/src/sdk/mlpack/include/mlpack/core/tree/address.hpp deleted file mode 100644 index 03c8cb4f9..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/address.hpp +++ /dev/null @@ -1,267 +0,0 @@ -/** - * @file address.hpp - * @author Mikhail Lozhnikov - * - * This file contains a series of functions for translating points to addresses - * and back and functions for comparing addresses. - * - * The notion of addresses is described in the following paper. - * @code - * @inproceedings{bayer1997, - * author = {Bayer, Rudolf}, - * title = {The Universal B-Tree for Multidimensional Indexing: General - * Concepts}, - * booktitle = {Proceedings of the International Conference on Worldwide - * Computing and Its Applications}, - * series = {WWCA '97}, - * year = {1997}, - * isbn = {3-540-63343-X}, - * pages = {198--209}, - * numpages = {12}, - * publisher = {Springer-Verlag}, - * address = {London, UK, UK}, - * } - * @endcode -*/ -#ifndef MLPACK_CORE_TREE_ADDRESS_HPP -#define MLPACK_CORE_TREE_ADDRESS_HPP - -namespace mlpack { -namespace bound { -namespace addr { - -/** - * Calculate the address of a point. Be careful, the point and the address - * variables should be equal-sized and the type of the address should correspond - * to the type of the vector. - * - * The function maps each floating point coordinate to an equal-sized unsigned - * integer datatype in such a way that the transform preserves the ordering - * (i.e. lower floating point values correspond to lower integers). Thus, - * the mapping saves the exponent and the mantissa of each floating point value - * consequently, furthermore the exponent is stored before the mantissa. In the - * case of negative numbers the resulting integer value should be inverted. - * In the multi-dimensional case, after we transform the representation, we - * have to interleave the bits of the new representation across all the elements - * in the address vector. - * - * @param address The resulting address. - * @param point The point that is being translated to the address. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -template -void PointToAddress(AddressType& address, const VecType& point) -{ - typedef typename VecType::elem_type VecElemType; - // Check that the arguments are compatible. - typedef typename std::conditional::type AddressElemType; - - static_assert(std::is_same::value == true, "The vector element type does not " - "correspond to the address element type."); - arma::Col result(point.n_elem); - - constexpr size_t order = sizeof(AddressElemType) * CHAR_BIT; - // Calculate the number of bits for the exponent. - const int numExpBits = std::ceil(std::log2( - std::numeric_limits::max_exponent - - std::numeric_limits::min_exponent + 1.0)); - - // Calculate the number of bits for the mantissa. - const int numMantBits = order - numExpBits - 1; - - assert(point.n_elem == address.n_elem); - assert(address.n_elem > 0); - - for (size_t i = 0; i < point.n_elem; i++) - { - int e; - VecElemType normalizedVal = std::frexp(point(i), &e); - bool sgn = std::signbit(normalizedVal); - - if (point(i) == 0) - e = std::numeric_limits::min_exponent; - - if (sgn) - normalizedVal = -normalizedVal; - - if (e < std::numeric_limits::min_exponent) - { - AddressElemType tmp = (AddressElemType) 1 << - (std::numeric_limits::min_exponent - e); - - e = std::numeric_limits::min_exponent; - normalizedVal /= tmp; - } - - // Extract the mantissa. - AddressElemType tmp = (AddressElemType) 1 << numMantBits; - result(i) = std::floor(normalizedVal * tmp); - - // Add the exponent. - assert(result(i) < ((AddressElemType) 1 << numMantBits)); - result(i) |= ((AddressElemType) - (e - std::numeric_limits::min_exponent)) << numMantBits; - - assert(result(i) < ((AddressElemType) 1 << (order - 1)) - 1); - - // Negative values should be inverted. - if (sgn) - { - result(i) = ((AddressElemType) 1 << (order - 1)) - 1 - result(i); - assert((result(i) >> (order - 1)) == 0); - } - else - { - result(i) |= (AddressElemType) 1 << (order - 1); - assert((result(i) >> (order - 1)) == 1); - } - } - - address.zeros(point.n_elem); - - // Interleave the bits of the new representation across all the elements - // in the address vector. - for (size_t i = 0; i < order; i++) - for (size_t j = 0; j < point.n_elem; j++) - { - size_t bit = (i * point.n_elem + j) % order; - size_t row = (i * point.n_elem + j) / order; - - address(row) |= (((result(j) >> (order - 1 - i)) & 1) << - (order - 1 - bit)); - } -} - -/** - * Translate the address to the point. Be careful, the point and the address - * variables should be equal-sized and the type of the address should correspond - * to the type of the vector. - * - * The function makes the backward transform to the function above. - * - * @param address An address to translate. - * @param point The point that corresponds to the address. - */ -template -void AddressToPoint(VecType& point, const AddressType& address) -{ - typedef typename VecType::elem_type VecElemType; - // Check that the arguments are compatible. - typedef typename std::conditional::type AddressElemType; - - static_assert(std::is_same::value == true, "The vector element type does not " - "correspond to the address element type."); - - constexpr size_t order = sizeof(AddressElemType) * CHAR_BIT; - // Calculate the number of bits for the exponent. - const int numExpBits = std::ceil(std::log2( - std::numeric_limits::max_exponent - - std::numeric_limits::min_exponent + 1.0)); - - assert(point.n_elem == address.n_elem); - assert(address.n_elem > 0); - - arma::Col rearrangedAddress(address.n_elem, - arma::fill::zeros); - // Calculate the number of bits for the mantissa. - const int numMantBits = order - numExpBits - 1; - - for (size_t i = 0; i < order; i++) - for (size_t j = 0; j < address.n_elem; j++) - { - size_t bit = (i * address.n_elem + j) % order; - size_t row = (i * address.n_elem + j) / order; - - rearrangedAddress(j) |= (((address(row) >> (order - 1 - bit)) & 1) << - (order - 1 - i)); - } - - for (size_t i = 0; i < rearrangedAddress.n_elem; i++) - { - bool sgn = rearrangedAddress(i) & ((AddressElemType) 1 << (order - 1)); - - if (!sgn) - { - rearrangedAddress(i) = ((AddressElemType) 1 << (order - 1)) - 1 - - rearrangedAddress(i); - } - - // Extract the mantissa. - AddressElemType tmp = (AddressElemType) 1 << numMantBits; - AddressElemType mantissa = rearrangedAddress(i) & (tmp - 1); - if (mantissa == 0) - mantissa = 1; - - VecElemType normalizedVal = (VecElemType) mantissa / tmp; - - if (!sgn) - normalizedVal = -normalizedVal; - - // Extract the exponent - tmp = (AddressElemType) 1 << numExpBits; - AddressElemType e = (rearrangedAddress(i) >> numMantBits) & (tmp - 1); - - e += std::numeric_limits::min_exponent; - - point(i) = std::ldexp(normalizedVal, e); - if (std::isinf(point(i))) - { - if (point(i) > 0) - point(i) = std::numeric_limits::max(); - else - point(i) = std::numeric_limits::lowest(); - } - } -} - -/** - * Compare two addresses. The function returns 1 if the first address is greater - * than the second one, -1 if the first address is less than the second one, - * otherwise the function returns 0. - */ -template -int CompareAddresses(const AddressType1& addr1, const AddressType2& addr2) -{ - static_assert(std::is_same::value == true, "Can't compare " - "addresses of distinct types"); - - assert(addr1.n_elem == addr2.n_elem); - - for (size_t i = 0; i < addr1.n_elem; i++) - { - if (addr1[i] < addr2[i]) - return -1; - else if (addr2[i] < addr1[i]) - return 1; - } - - return 0; -} - -/** - * Returns true if an address is contained between two other addresses. - */ -template -bool Contains(const AddressType1& address, const AddressType2& loBound, - const AddressType3& hiBound) -{ - return ((CompareAddresses(loBound, address) <= 0) && - (CompareAddresses(hiBound, address) >= 0)); -} - -} // namespace addr -} // namespace bound -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_ADDRESS_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/ballbound.hpp b/src/sdk/mlpack/include/mlpack/core/tree/ballbound.hpp deleted file mode 100644 index 0e33bb63e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/ballbound.hpp +++ /dev/null @@ -1,206 +0,0 @@ -/** - * @file ballbound.hpp - * - * Bounds that are useful for binary space partitioning trees. - * Interface to a ball bound that works in arbitrary metric spaces. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BALLBOUND_HPP -#define MLPACK_CORE_TREE_BALLBOUND_HPP - -#include -#include -#include "bound_traits.hpp" - -namespace mlpack { -namespace bound { - -/** - * Ball bound encloses a set of points at a specific distance (radius) from a - * specific point (center). MetricType is the custom metric type that defaults - * to the Euclidean (L2) distance. - * - * @tparam MetricType metric type used in the distance measure. - * @tparam VecType Type of vector (arma::vec or arma::sp_vec or similar). - */ -template, - typename VecType = arma::vec> -class BallBound -{ - public: - //! The underlying data type. - typedef typename VecType::elem_type ElemType; - //! A public version of the vector type. - typedef VecType Vec; - - private: - //! The radius of the ball bound. - ElemType radius; - //! The center of the ball bound. - VecType center; - //! The metric used in this bound. - MetricType* metric; - - /** - * To know whether this object allocated memory to the metric member - * variable. This will be true except in the copy constructor and the - * overloaded assignment operator. We need this to know whether we should - * delete the metric member variable in the destructor. - */ - bool ownsMetric; - - public: - //! Empty Constructor. - BallBound(); - - /** - * Create the ball bound with the specified dimensionality. - * - * @param dimension Dimensionality of ball bound. - */ - BallBound(const size_t dimension); - - /** - * Create the ball bound with the specified radius and center. - * - * @param radius Radius of ball bound. - * @param center Center of ball bound. - */ - BallBound(const ElemType radius, const VecType& center); - - //! Copy constructor. To prevent memory leaks. - BallBound(const BallBound& other); - - //! For the same reason as the copy constructor: to prevent memory leaks. - BallBound& operator=(const BallBound& other); - - //! Move constructor: take possession of another bound. - BallBound(BallBound&& other); - - //! Destructor to release allocated memory. - ~BallBound(); - - //! Get the radius of the ball. - ElemType Radius() const { return radius; } - //! Modify the radius of the ball. - ElemType& Radius() { return radius; } - - //! Get the center point of the ball. - const VecType& Center() const { return center; } - //! Modify the center point of the ball. - VecType& Center() { return center; } - - //! Get the dimensionality of the ball. - size_t Dim() const { return center.n_elem; } - - /** - * Get the minimum width of the bound (this is same as the diameter). - * For ball bounds, width along all dimensions remain same. - */ - ElemType MinWidth() const { return radius * 2.0; } - - //! Get the range in a certain dimension. - math::RangeType operator[](const size_t i) const; - - /** - * Determines if a point is within this bound. - */ - bool Contains(const VecType& point) const; - - /** - * Place the center of BallBound into the given vector. - * - * @param center Vector which the centroid will be written to. - */ - void Center(VecType& center) const { center = this->center; } - - /** - * Calculates minimum bound-to-point squared distance. - */ - template - ElemType MinDistance( - const OtherVecType& point, - typename std::enable_if_t::value>* = 0) const; - - /** - * Calculates minimum bound-to-bound squared distance. - */ - ElemType MinDistance(const BallBound& other) const; - - /** - * Computes maximum distance. - */ - template - ElemType MaxDistance( - const OtherVecType& point, - typename std::enable_if_t::value>* = 0) const; - - /** - * Computes maximum distance. - */ - ElemType MaxDistance(const BallBound& other) const; - - /** - * Calculates minimum and maximum bound-to-point distance. - */ - template - math::RangeType RangeDistance( - const OtherVecType& other, - typename std::enable_if_t::value>* = 0) const; - - /** - * Calculates minimum and maximum bound-to-bound distance. - * - * Example: bound1.MinDistanceSq(other) for minimum distance. - */ - math::RangeType RangeDistance(const BallBound& other) const; - - /** - * Expand the bound to include the given node. - */ - const BallBound& operator|=(const BallBound& other); - - /** - * Expand the bound to include the given point. The centroid is recalculated - * to be the center of all of the given points. - * - * @tparam MatType Type of matrix; could be arma::mat, arma::spmat, or a - * vector. - * @tparam data Data points to add. - */ - template - const BallBound& operator|=(const MatType& data); - - /** - * Returns the diameter of the ballbound. - */ - ElemType Diameter() const { return 2 * radius; } - - //! Returns the distance metric used in this bound. - const MetricType& Metric() const { return *metric; } - //! Modify the distance metric used in this bound. - MetricType& Metric() { return *metric; } - - //! Serialize the bound. - template - void serialize(Archive& ar, const unsigned int version); -}; - -//! A specialization of BoundTraits for this bound type. -template -struct BoundTraits> -{ - //! These bounds are potentially loose in some dimensions. - const static bool HasTightBounds = false; -}; - -} // namespace bound -} // namespace mlpack - -#include "ballbound_impl.hpp" - -#endif // MLPACK_CORE_TREE_DBALLBOUND_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/ballbound_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/ballbound_impl.hpp deleted file mode 100644 index 30f83588b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/ballbound_impl.hpp +++ /dev/null @@ -1,307 +0,0 @@ -/** - * @file ballbound_impl.hpp - * - * Bounds that are useful for binary space partitioning trees. - * Implementation of BallBound ball bound metric policy class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BALLBOUND_IMPL_HPP -#define MLPACK_CORE_TREE_BALLBOUND_IMPL_HPP - -// In case it hasn't been included already. -#include "ballbound.hpp" -#include - -#include - -namespace mlpack { -namespace bound { - -//! Empty Constructor. -template -BallBound::BallBound() : - radius(std::numeric_limits::lowest()), - metric(new MetricType()), - ownsMetric(true) -{ /* Nothing to do. */ } - -/** - * Create the ball bound with the specified dimensionality. - * - * @param dimension Dimensionality of ball bound. - */ -template -BallBound::BallBound(const size_t dimension) : - radius(std::numeric_limits::lowest()), - center(dimension), - metric(new MetricType()), - ownsMetric(true) -{ /* Nothing to do. */ } - -/** - * Create the ball bound with the specified radius and center. - * - * @param radius Radius of ball bound. - * @param center Center of ball bound. - */ -template -BallBound::BallBound(const ElemType radius, - const VecType& center) : - radius(radius), - center(center), - metric(new MetricType()), - ownsMetric(true) -{ /* Nothing to do. */ } - -//! Copy Constructor. To prevent memory leaks. -template -BallBound::BallBound(const BallBound& other) : - radius(other.radius), - center(other.center), - metric(other.metric), - ownsMetric(false) -{ /* Nothing to do. */ } - -//! For the same reason as the copy constructor: to prevent memory leaks. -template -BallBound& BallBound::operator=( - const BallBound& other) -{ - radius = other.radius; - center = other.center; - metric = other.metric; - ownsMetric = false; -} - -//! Move constructor. -template -BallBound::BallBound(BallBound&& other) : - radius(other.radius), - center(other.center), - metric(other.metric), - ownsMetric(other.ownsMetric) -{ - // Fix the other bound. - other.radius = 0.0; - other.center = VecType(); - other.metric = NULL; - other.ownsMetric = false; -} - -//! Destructor to release allocated memory. -template -BallBound::~BallBound() -{ - if (ownsMetric) - delete metric; -} - -//! Get the range in a certain dimension. -template -math::RangeType::ElemType> -BallBound::operator[](const size_t i) const -{ - if (radius < 0) - return math::Range(); - else - return math::Range(center[i] - radius, center[i] + radius); -} - -/** - * Determines if a point is within the bound. - */ -template -bool BallBound::Contains(const VecType& point) const -{ - if (radius < 0) - return false; - else - return metric->Evaluate(center, point) <= radius; -} - -/** - * Calculates minimum bound-to-point squared distance. - */ -template -template -typename BallBound::ElemType -BallBound::MinDistance( - const OtherVecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - if (radius < 0) - return std::numeric_limits::max(); - else - return math::ClampNonNegative(metric->Evaluate(point, center) - radius); -} - -/** - * Calculates minimum bound-to-bound squared distance. - */ -template -typename BallBound::ElemType -BallBound::MinDistance(const BallBound& other) - const -{ - if (radius < 0) - return std::numeric_limits::max(); - else - { - const ElemType delta = metric->Evaluate(center, other.center) - radius - - other.radius; - return math::ClampNonNegative(delta); - } -} - -/** - * Computes maximum distance. - */ -template -template -typename BallBound::ElemType -BallBound::MaxDistance( - const OtherVecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - if (radius < 0) - return std::numeric_limits::max(); - else - return metric->Evaluate(point, center) + radius; -} - -/** - * Computes maximum distance. - */ -template -typename BallBound::ElemType -BallBound::MaxDistance(const BallBound& other) - const -{ - if (radius < 0) - return std::numeric_limits::max(); - else - return metric->Evaluate(other.center, center) + radius + other.radius; -} - -/** - * Calculates minimum and maximum bound-to-bound squared distance. - * - * Example: bound1.MinDistanceSq(other) for minimum squared distance. - */ -template -template -math::RangeType::ElemType> -BallBound::RangeDistance( - const OtherVecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - if (radius < 0) - return math::Range(std::numeric_limits::max(), - std::numeric_limits::max()); - else - { - const ElemType dist = metric->Evaluate(center, point); - return math::Range(math::ClampNonNegative(dist - radius), - dist + radius); - } -} - -template -math::RangeType::ElemType> -BallBound::RangeDistance( - const BallBound& other) const -{ - if (radius < 0) - return math::Range(std::numeric_limits::max(), - std::numeric_limits::max()); - else - { - const ElemType dist = metric->Evaluate(center, other.center); - const ElemType sumradius = radius + other.radius; - return math::Range(math::ClampNonNegative(dist - sumradius), - dist + sumradius); - } -} - -/** - * Expand the bound to include the given bound. - * -template -const BallBound& -BallBound::operator|=( - const BallBound& other) -{ - double dist = metric->Evaluate(center, other); - - // Now expand the radius as necessary. - if (dist > radius) - radius = dist; - - return *this; -}*/ - -/** - * Expand the bound to include the given point. Algorithm adapted from - * Jack Ritter, "An Efficient Bounding Sphere" in Graphics Gems (1990). - * The difference lies in the way we initialize the ball bound. The way we - * expand the bound is same. - */ -template -template -const BallBound& -BallBound::operator|=(const MatType& data) -{ - if (radius < 0) - { - center = data.col(0); - radius = 0; - } - - // Now iteratively add points. - for (size_t i = 0; i < data.n_cols; ++i) - { - const ElemType dist = metric->Evaluate(center, (VecType) data.col(i)); - - // See if the new point lies outside the bound. - if (dist > radius) - { - // Move towards the new point and increase the radius just enough to - // accommodate the new point. - const VecType diff = data.col(i) - center; - center += ((dist - radius) / (2 * dist)) * diff; - radius = 0.5 * (dist + radius); - } - } - - return *this; -} - -//! Serialize the BallBound. -template -template -void BallBound::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(radius); - ar & BOOST_SERIALIZATION_NVP(center); - - if (Archive::is_loading::value) - { - // If we're loading, delete the local metric since we'll have a new one. - if (ownsMetric) - delete metric; - } - - ar & BOOST_SERIALIZATION_NVP(metric); - ar & BOOST_SERIALIZATION_NVP(ownsMetric); -} - -} // namespace bound -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_DBALLBOUND_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree.hpp deleted file mode 100644 index 6ffcf6202..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * @file binary_space_tree.hpp - * @author Ryan Curtin - * - * Include all the necessary files to use the BinarySpaceTree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_HPP - -#include -#include "bounds.hpp" -#include "binary_space_tree/midpoint_split.hpp" -#include "binary_space_tree/mean_split.hpp" -#include "binary_space_tree/vantage_point_split.hpp" -#include "binary_space_tree/rp_tree_max_split.hpp" -#include "binary_space_tree/rp_tree_mean_split.hpp" -#include "binary_space_tree/ub_tree_split.hpp" -#include "binary_space_tree/binary_space_tree.hpp" -#include "binary_space_tree/single_tree_traverser.hpp" -#include "binary_space_tree/single_tree_traverser_impl.hpp" -#include "binary_space_tree/dual_tree_traverser.hpp" -#include "binary_space_tree/dual_tree_traverser_impl.hpp" -#include "binary_space_tree/breadth_first_dual_tree_traverser.hpp" -#include "binary_space_tree/breadth_first_dual_tree_traverser_impl.hpp" -#include "binary_space_tree/traits.hpp" -#include "binary_space_tree/typedef.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/binary_space_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/binary_space_tree.hpp deleted file mode 100644 index 32486902e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/binary_space_tree.hpp +++ /dev/null @@ -1,563 +0,0 @@ -/** - * @file binary_space_tree.hpp - * - * Definition of generalized binary space partitioning tree (BinarySpaceTree). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_BINARY_SPACE_TREE_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_BINARY_SPACE_TREE_HPP - -#include - -#include "../statistic.hpp" -#include "midpoint_split.hpp" - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * A binary space partitioning tree, such as a KD-tree or a ball tree. Once the - * bound and type of dataset is defined, the tree will construct itself. Call - * the constructor with the dataset to build the tree on, and the entire tree - * will be built. - * - * This particular tree does not allow growth, so you cannot add or delete nodes - * from it. If you need to add or delete a node, the better procedure is to - * rebuild the tree entirely. - * - * This tree does take one runtime parameter in the constructor, which is the - * max leaf size to be used. - * - * @tparam MetricType The metric used for tree-building. The BoundType may - * place restrictions on the metrics that can be used. - * @tparam StatisticType Extra data contained in the node. See statistic.hpp - * for the necessary skeleton interface. - * @tparam MatType The dataset class. - * @tparam BoundType The bound used for each node. HRectBound, the default, - * requires that an LMetric<> is used for MetricType (so, EuclideanDistance, - * ManhattanDistance, etc.). - * @tparam SplitType The class that partitions the dataset/points at a - * particular node into two parts. Its definition decides the way this split - * is done. - */ -template class BoundType = - bound::HRectBound, - template - class SplitType = MidpointSplit> -class BinarySpaceTree -{ - public: - //! So other classes can use TreeType::Mat. - typedef MatType Mat; - //! The type of element held in MatType. - typedef typename MatType::elem_type ElemType; - - typedef SplitType, MatType> Split; - - private: - //! The left child node. - BinarySpaceTree* left; - //! The right child node. - BinarySpaceTree* right; - //! The parent node (NULL if this is the root of the tree). - BinarySpaceTree* parent; - //! The index of the first point in the dataset contained in this node (and - //! its children). - size_t begin; - //! The number of points of the dataset contained in this node (and its - //! children). - size_t count; - //! The bound object for this node. - BoundType bound; - //! Any extra data contained in the node. - StatisticType stat; - //! The distance from the centroid of this node to the centroid of the parent. - ElemType parentDistance; - //! The worst possible distance to the furthest descendant, cached to speed - //! things up. - ElemType furthestDescendantDistance; - //! The minimum distance from the center to any edge of the bound. - ElemType minimumBoundDistance; - //! The dataset. If we are the root of the tree, we own the dataset and must - //! delete it. - MatType* dataset; - - public: - //! A single-tree traverser for binary space trees; see - //! single_tree_traverser.hpp for implementation. - template - class SingleTreeTraverser; - - //! A dual-tree traverser for binary space trees; see dual_tree_traverser.hpp. - template - class DualTreeTraverser; - - template - class BreadthFirstDualTreeTraverser; - - /** - * Construct this as the root node of a binary space tree using the given - * dataset. This will copy the input matrix; if you don't want this, consider - * using the constructor that takes an rvalue reference and use std::move(). - * - * @param data Dataset to create tree from. This will be copied! - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(const MatType& data, const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of a binary space tree using the given - * dataset. This will copy the input matrix and modify its ordering; a - * mapping of the old point indices to the new point indices is filled. If - * you don't want the matrix to be copied, consider using the constructor that - * takes an rvalue reference and use std::move(). - * - * @param data Dataset to create tree from. This will be copied! - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(const MatType& data, - std::vector& oldFromNew, - const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of a binary space tree using the given - * dataset. This will copy the input matrix and modify its ordering; a - * mapping of the old point indices to the new point indices is filled, as - * well as a mapping of the new point indices to the old point indices. If - * you don't want the matrix to be copied, consider using the constructor that - * takes an rvalue reference and use std::move(). - * - * @param data Dataset to create tree from. This will be copied! - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param newFromOld Vector which will be filled with the new positions for - * each old point. - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(const MatType& data, - std::vector& oldFromNew, - std::vector& newFromOld, - const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of a binary space tree using the given - * dataset. This will take ownership of the data matrix; if you don't want - * this, consider using the constructor that takes a const reference to a - * dataset. - * - * @param data Dataset to create tree from. - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(MatType&& data, - const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of a binary space tree using the given - * dataset. This will take ownership of the data matrix; a mapping of the - * old point indices to the new point indices is filled. If you don't want - * the matrix to have its ownership taken, consider using the constructor that - * takes a const reference to a dataset. - * - * @param data Dataset to create tree from. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(MatType&& data, - std::vector& oldFromNew, - const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of a binary space tree using the given - * dataset. This will take ownership of the data matrix; a mapping of the old - * point indices to the new point indices is filled, as well as a mapping of - * the new point indices to the old point indices. If you don't want the - * matrix to have its ownership taken, consider using the constructor that - * takes a const reference to a dataset. - * - * @param data Dataset to create tree from. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param newFromOld Vector which will be filled with the new positions for - * each old point. - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(MatType&& data, - std::vector& oldFromNew, - std::vector& newFromOld, - const size_t maxLeafSize = 20); - - /** - * Construct this node as a child of the given parent, starting at column - * begin and using count points. The ordering of that subset of points in the - * parent's data matrix will be modified! This is used for recursive - * tree-building by the other constructors which don't specify point indices. - * - * @param parent Parent of this node. Its dataset will be modified! - * @param begin Index of point to start tree construction with. - * @param count Number of points to use to construct tree. - * @param splitter Instantiated node splitter object. - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(BinarySpaceTree* parent, - const size_t begin, - const size_t count, - SplitType, MatType>& splitter, - const size_t maxLeafSize = 20); - - /** - * Construct this node as a child of the given parent, starting at column - * begin and using count points. The ordering of that subset of points in the - * parent's data matrix will be modified! This is used for recursive - * tree-building by the other constructors which don't specify point indices. - * - * A mapping of the old point indices to the new point indices is filled, but - * it is expected that the vector is already allocated with size greater than - * or equal to (begin + count), and if that is not true, invalid memory reads - * (and writes) will occur. - * - * @param parent Parent of this node. Its dataset will be modified! - * @param begin Index of point to start tree construction with. - * @param count Number of points to use to construct tree. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param splitter Instantiated node splitter object. - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(BinarySpaceTree* parent, - const size_t begin, - const size_t count, - std::vector& oldFromNew, - SplitType, MatType>& splitter, - const size_t maxLeafSize = 20); - - /** - * Construct this node as a child of the given parent, starting at column - * begin and using count points. The ordering of that subset of points in the - * parent's data matrix will be modified! This is used for recursive - * tree-building by the other constructors which don't specify point indices. - * - * A mapping of the old point indices to the new point indices is filled, as - * well as a mapping of the new point indices to the old point indices. It is - * expected that the vector is already allocated with size greater than or - * equal to (begin_in + count_in), and if that is not true, invalid memory - * reads (and writes) will occur. - * - * @param parent Parent of this node. Its dataset will be modified! - * @param begin Index of point to start tree construction with. - * @param count Number of points to use to construct tree. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param newFromOld Vector which will be filled with the new positions for - * each old point. - * @param maxLeafSize Size of each leaf in the tree. - */ - BinarySpaceTree(BinarySpaceTree* parent, - const size_t begin, - const size_t count, - std::vector& oldFromNew, - std::vector& newFromOld, - SplitType, MatType>& splitter, - const size_t maxLeafSize = 20); - - /** - * Create a binary space tree by copying the other tree. Be careful! This - * can take a long time and use a lot of memory. - * - * @param other Tree to be replicated. - */ - BinarySpaceTree(const BinarySpaceTree& other); - - /** - * Move constructor for a BinarySpaceTree; possess all the members of the - * given tree. - */ - BinarySpaceTree(BinarySpaceTree&& other); - - /** - * Initialize the tree from a boost::serialization archive. - * - * @param ar Archive to load tree from. Must be an iarchive, not an oarchive. - */ - template - BinarySpaceTree( - Archive& ar, - const typename std::enable_if_t* = 0); - - /** - * Deletes this node, deallocating the memory for the children and calling - * their destructors in turn. This will invalidate any pointers or references - * to any nodes which are children of this one. - */ - ~BinarySpaceTree(); - - //! Return the bound object for this node. - const BoundType& Bound() const { return bound; } - //! Return the bound object for this node. - BoundType& Bound() { return bound; } - - //! Return the statistic object for this node. - const StatisticType& Stat() const { return stat; } - //! Return the statistic object for this node. - StatisticType& Stat() { return stat; } - - //! Return whether or not this node is a leaf (true if it has no children). - bool IsLeaf() const; - - //! Gets the left child of this node. - BinarySpaceTree* Left() const { return left; } - //! Modify the left child of this node. - BinarySpaceTree*& Left() { return left; } - - //! Gets the right child of this node. - BinarySpaceTree* Right() const { return right; } - //! Modify the right child of this node. - BinarySpaceTree*& Right() { return right; } - - //! Gets the parent of this node. - BinarySpaceTree* Parent() const { return parent; } - //! Modify the parent of this node. - BinarySpaceTree*& Parent() { return parent; } - - //! Get the dataset which the tree is built on. - const MatType& Dataset() const { return *dataset; } - //! Modify the dataset which the tree is built on. Be careful! - MatType& Dataset() { return *dataset; } - - //! Get the metric that the tree uses. - MetricType Metric() const { return MetricType(); } - - //! Return the number of children in this node. - size_t NumChildren() const; - - /** - * Return the index of the nearest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ - template - size_t GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0); - - /** - * Return the index of the furthest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ - template - size_t GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0); - - /** - * Return the index of the nearest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ - size_t GetNearestChild(const BinarySpaceTree& queryNode); - - /** - * Return the index of the furthest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ - size_t GetFurthestChild(const BinarySpaceTree& queryNode); - - /** - * Return the furthest distance to a point held in this node. If this is not - * a leaf node, then the distance is 0 because the node holds no points. - */ - ElemType FurthestPointDistance() const; - - /** - * Return the furthest possible descendant distance. This returns the maximum - * distance from the centroid to the edge of the bound and not the empirical - * quantity which is the actual furthest descendant distance. So the actual - * furthest descendant distance may be less than what this method returns (but - * it will never be greater than this). - */ - ElemType FurthestDescendantDistance() const; - - //! Return the minimum distance from the center of the node to any bound edge. - ElemType MinimumBoundDistance() const; - - //! Return the distance from the center of this node to the center of the - //! parent node. - ElemType ParentDistance() const { return parentDistance; } - //! Modify the distance from the center of this node to the center of the - //! parent node. - ElemType& ParentDistance() { return parentDistance; } - - /** - * Return the specified child (0 will be left, 1 will be right). If the index - * is greater than 1, this will return the right child. - * - * @param child Index of child to return. - */ - BinarySpaceTree& Child(const size_t child) const; - - BinarySpaceTree*& ChildPtr(const size_t child) - { return (child == 0) ? left : right; } - - //! Return the number of points in this node (0 if not a leaf). - size_t NumPoints() const; - - /** - * Return the number of descendants of this node. For a non-leaf in a binary - * space tree, this is the number of points at the descendant leaves. For a - * leaf, this is the number of points in the leaf. - */ - size_t NumDescendants() const; - - /** - * Return the index (with reference to the dataset) of a particular descendant - * of this node. The index should be greater than zero but less than the - * number of descendants. - * - * @param index Index of the descendant. - */ - size_t Descendant(const size_t index) const; - - /** - * Return the index (with reference to the dataset) of a particular point in - * this node. This will happily return invalid indices if the given index is - * greater than the number of points in this node (obtained with NumPoints()) - * -- be careful. - * - * @param index Index of point for which a dataset index is wanted. - */ - size_t Point(const size_t index) const; - - //! Return the minimum distance to another node. - ElemType MinDistance(const BinarySpaceTree& other) const - { - return bound.MinDistance(other.Bound()); - } - - //! Return the maximum distance to another node. - ElemType MaxDistance(const BinarySpaceTree& other) const - { - return bound.MaxDistance(other.Bound()); - } - - //! Return the minimum and maximum distance to another node. - math::RangeType RangeDistance(const BinarySpaceTree& other) const - { - return bound.RangeDistance(other.Bound()); - } - - //! Return the minimum distance to another point. - template - ElemType MinDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const - { - return bound.MinDistance(point); - } - - //! Return the maximum distance to another point. - template - ElemType MaxDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const - { - return bound.MaxDistance(point); - } - - //! Return the minimum and maximum distance to another point. - template - math::RangeType - RangeDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) const - { - return bound.RangeDistance(point); - } - - //! Return the index of the beginning point of this subset. - size_t Begin() const { return begin; } - //! Modify the index of the beginning point of this subset. - size_t& Begin() { return begin; } - - //! Return the number of points in this subset. - size_t Count() const { return count; } - //! Modify the number of points in this subset. - size_t& Count() { return count; } - - //! Store the center of the bounding region in the given vector. - void Center(arma::vec& center) const { bound.Center(center); } - - private: - /** - * Splits the current node, assigning its left and right children recursively. - * - * @param maxLeafSize Maximum number of points held in a leaf. - * @param splitter Instantiated SplitType object. - */ - void SplitNode(const size_t maxLeafSize, - SplitType, MatType>& splitter); - - /** - * Splits the current node, assigning its left and right children recursively. - * Also returns a list of the changed indices. - * - * @param oldFromNew Vector holding permuted indices. - * @param maxLeafSize Maximum number of points held in a leaf. - * @param splitter Instantiated SplitType object. - */ - void SplitNode(std::vector& oldFromNew, - const size_t maxLeafSize, - SplitType, MatType>& splitter); - - /** - * Update the bound of the current node. This method does not take into - * account bound-specific properties. - * - * @param boundToUpdate The bound to update. - */ - template - void UpdateBound(BoundType2& boundToUpdate); - - /** - * Update the bound of the current node. This method is designed for - * HollowBallBound only. - * - * @param boundToUpdate The bound to update. - */ - void UpdateBound(bound::HollowBallBound& boundToUpdate); - - protected: - /** - * A default constructor. This is meant to only be used with - * boost::serialization, which is allowed with the friend declaration below. - * This does not return a valid tree! The method must be protected, so that - * the serialization shim can work with the default constructor. - */ - BinarySpaceTree(); - - //! Friend access is given for the default constructor. - friend class boost::serialization::access; - - public: - /** - * Serialize the tree. - */ - template - void serialize(Archive& ar, const unsigned int version); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "binary_space_tree_impl.hpp" - -// Include everything else, if necessary. -#include "../binary_space_tree.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/binary_space_tree_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/binary_space_tree_impl.hpp deleted file mode 100644 index ee83c766c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/binary_space_tree_impl.hpp +++ /dev/null @@ -1,994 +0,0 @@ -/** - * @file binary_space_tree_impl.hpp - * - * Implementation of generalized space partitioning tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_BINARY_SPACE_TREE_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_BINARY_SPACE_TREE_IMPL_HPP - -// In case it wasn't included already for some reason. -#include "binary_space_tree.hpp" - -#include -#include -#include - -namespace mlpack { -namespace tree { - -// Each of these overloads is kept as a separate function to keep the overhead -// from the two std::vectors out, if possible. -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - const MatType& data, - const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(NULL), - begin(0), /* This root node starts at index 0, */ - count(data.n_cols), /* and spans all of the dataset. */ - bound(data.n_rows), - parentDistance(0), // Parent distance for the root is 0: it has no parent. - dataset(new MatType(data)) // Copies the dataset. -{ - // Do the actual splitting of this node. - SplitType, MatType> splitter; - SplitNode(maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - const MatType& data, - std::vector& oldFromNew, - const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(NULL), - begin(0), - count(data.n_cols), - bound(data.n_rows), - parentDistance(0), // Parent distance for the root is 0: it has no parent. - dataset(new MatType(data)) // Copies the dataset. -{ - // Initialize oldFromNew correctly. - oldFromNew.resize(data.n_cols); - for (size_t i = 0; i < data.n_cols; i++) - oldFromNew[i] = i; // Fill with unharmed indices. - - // Now do the actual splitting. - SplitType, MatType> splitter; - SplitNode(oldFromNew, maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - const MatType& data, - std::vector& oldFromNew, - std::vector& newFromOld, - const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(NULL), - begin(0), - count(data.n_cols), - bound(data.n_rows), - parentDistance(0), // Parent distance for the root is 0: it has no parent. - dataset(new MatType(data)) // Copies the dataset. -{ - // Initialize the oldFromNew vector correctly. - oldFromNew.resize(data.n_cols); - for (size_t i = 0; i < data.n_cols; i++) - oldFromNew[i] = i; // Fill with unharmed indices. - - // Now do the actual splitting. - SplitType, MatType> splitter; - SplitNode(oldFromNew, maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); - - // Map the newFromOld indices correctly. - newFromOld.resize(data.n_cols); - for (size_t i = 0; i < data.n_cols; i++) - newFromOld[oldFromNew[i]] = i; -} - -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree(MatType&& data, const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(NULL), - begin(0), - count(data.n_cols), - bound(data.n_rows), - parentDistance(0), // Parent distance for the root is 0: it has no parent. - dataset(new MatType(std::move(data))) -{ - // Do the actual splitting of this node. - SplitType, MatType> splitter; - SplitNode(maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - MatType&& data, - std::vector& oldFromNew, - const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(NULL), - begin(0), - count(data.n_cols), - bound(data.n_rows), - parentDistance(0), // Parent distance for the root is 0: it has no parent. - dataset(new MatType(std::move(data))) -{ - // Initialize oldFromNew correctly. - oldFromNew.resize(dataset->n_cols); - for (size_t i = 0; i < dataset->n_cols; i++) - oldFromNew[i] = i; // Fill with unharmed indices. - - // Now do the actual splitting. - SplitType, MatType> splitter; - SplitNode(oldFromNew, maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - MatType&& data, - std::vector& oldFromNew, - std::vector& newFromOld, - const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(NULL), - begin(0), - count(data.n_cols), - bound(data.n_rows), - parentDistance(0), // Parent distance for the root is 0: it has no parent. - dataset(new MatType(std::move(data))) -{ - // Initialize the oldFromNew vector correctly. - oldFromNew.resize(dataset->n_cols); - for (size_t i = 0; i < dataset->n_cols; i++) - oldFromNew[i] = i; // Fill with unharmed indices. - - // Now do the actual splitting. - SplitType, MatType> splitter; - SplitNode(oldFromNew, maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); - - // Map the newFromOld indices correctly. - newFromOld.resize(dataset->n_cols); - for (size_t i = 0; i < dataset->n_cols; i++) - newFromOld[oldFromNew[i]] = i; -} - -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - BinarySpaceTree* parent, - const size_t begin, - const size_t count, - SplitType, MatType>& splitter, - const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(parent), - begin(begin), - count(count), - bound(parent->Dataset().n_rows), - dataset(&parent->Dataset()) // Point to the parent's dataset. -{ - // Perform the actual splitting. - SplitNode(maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - BinarySpaceTree* parent, - const size_t begin, - const size_t count, - std::vector& oldFromNew, - SplitType, MatType>& splitter, - const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(parent), - begin(begin), - count(count), - bound(parent->Dataset().n_rows), - dataset(&parent->Dataset()) -{ - // Hopefully the vector is initialized correctly! We can't check that - // entirely but we can do a minor sanity check. - assert(oldFromNew.size() == dataset->n_cols); - - // Perform the actual splitting. - SplitNode(oldFromNew, maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - BinarySpaceTree* parent, - const size_t begin, - const size_t count, - std::vector& oldFromNew, - std::vector& newFromOld, - SplitType, MatType>& splitter, - const size_t maxLeafSize) : - left(NULL), - right(NULL), - parent(parent), - begin(begin), - count(count), - bound(parent->Dataset()->n_rows), - dataset(&parent->Dataset()) -{ - // Hopefully the vector is initialized correctly! We can't check that - // entirely but we can do a minor sanity check. - Log::Assert(oldFromNew.size() == dataset->n_cols); - - // Perform the actual splitting. - SplitNode(oldFromNew, maxLeafSize, splitter); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); - - // Map the newFromOld indices correctly. - newFromOld.resize(dataset->n_cols); - for (size_t i = 0; i < dataset->n_cols; i++) - newFromOld[oldFromNew[i]] = i; -} - -/** - * Create a binary space tree by copying the other tree. Be careful! This can - * take a long time and use a lot of memory. - */ -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree( - const BinarySpaceTree& other) : - left(NULL), - right(NULL), - parent(other.parent), - begin(other.begin), - count(other.count), - bound(other.bound), - stat(other.stat), - parentDistance(other.parentDistance), - furthestDescendantDistance(other.furthestDescendantDistance), - // Copy matrix, but only if we are the root. - dataset((other.parent == NULL) ? new MatType(*other.dataset) : NULL) -{ - // Create left and right children (if any). - if (other.Left()) - { - left = new BinarySpaceTree(*other.Left()); - left->Parent() = this; // Set parent to this, not other tree. - } - - if (other.Right()) - { - right = new BinarySpaceTree(*other.Right()); - right->Parent() = this; // Set parent to this, not other tree. - } - - // Propagate matrix, but only if we are the root. - if (parent == NULL) - { - std::queue queue; - if (left) - queue.push(left); - if (right) - queue.push(right); - while (!queue.empty()) - { - BinarySpaceTree* node = queue.front(); - queue.pop(); - - node->dataset = dataset; - if (node->left) - queue.push(node->left); - if (node->right) - queue.push(node->right); - } - } -} - -/** - * Move constructor. - */ -template class BoundType, - template - class SplitType> -BinarySpaceTree:: -BinarySpaceTree(BinarySpaceTree&& other) : - left(other.left), - right(other.right), - parent(other.parent), - begin(other.begin), - count(other.count), - bound(std::move(other.bound)), - stat(std::move(other.stat)), - parentDistance(other.parentDistance), - furthestDescendantDistance(other.furthestDescendantDistance), - minimumBoundDistance(other.minimumBoundDistance), - dataset(other.dataset) -{ - // Now we are a clone of the other tree. But we must also clear the other - // tree's contents, so it doesn't delete anything when it is destructed. - other.left = NULL; - other.right = NULL; - other.begin = 0; - other.count = 0; - other.parentDistance = 0.0; - other.furthestDescendantDistance = 0.0; - other.minimumBoundDistance = 0.0; - other.dataset = NULL; - - // Set new parent. - if (left) - left->parent = this; - if (right) - right->parent = this; -} - -/** - * Initialize the tree from an archive. - */ -template class BoundType, - template - class SplitType> -template -BinarySpaceTree:: -BinarySpaceTree( - Archive& ar, - const typename std::enable_if_t*) : - BinarySpaceTree() // Create an empty BinarySpaceTree. -{ - // We've delegated to the constructor which gives us an empty tree, and now we - // can serialize from it. - ar >> BOOST_SERIALIZATION_NVP(*this); -} - -/** - * Deletes this node, deallocating the memory for the children and calling their - * destructors in turn. This will invalidate any pointers or references to any - * nodes which are children of this one. - */ -template class BoundType, - template - class SplitType> -BinarySpaceTree:: - ~BinarySpaceTree() -{ - delete left; - delete right; - - // If we're the root, delete the matrix. - if (!parent) - delete dataset; -} - -template class BoundType, - template - class SplitType> -inline bool BinarySpaceTree::IsLeaf() const -{ - return !left; -} - -/** - * Returns the number of children in this node. - */ -template class BoundType, - template - class SplitType> -inline size_t BinarySpaceTree::NumChildren() const -{ - if (left && right) - return 2; - if (left) - return 1; - - return 0; -} - -/** - * Return the index of the nearest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ -template class BoundType, - template - class SplitType> -template -size_t BinarySpaceTree::GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>*) -{ - if (IsLeaf() || !left || !right) - return 0; - - if (left->MinDistance(point) <= right->MinDistance(point)) - return 0; - return 1; -} - -/** - * Return the index of the furthest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ -template class BoundType, - template - class SplitType> -template -size_t BinarySpaceTree::GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>*) -{ - if (IsLeaf() || !left || !right) - return 0; - - if (left->MaxDistance(point) > right->MaxDistance(point)) - return 0; - return 1; -} - -/** - * Return the index of the nearest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ -template class BoundType, - template - class SplitType> -size_t BinarySpaceTree::GetNearestChild(const BinarySpaceTree& queryNode) -{ - if (IsLeaf() || !left || !right) - return 0; - - ElemType leftDist = left->MinDistance(queryNode); - ElemType rightDist = right->MinDistance(queryNode); - if (leftDist < rightDist) - return 0; - if (rightDist < leftDist) - return 1; - return NumChildren(); -} - -/** - * Return the index of the furthest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ -template class BoundType, - template - class SplitType> -size_t BinarySpaceTree::GetFurthestChild(const BinarySpaceTree& queryNode) -{ - if (IsLeaf() || !left || !right) - return 0; - - ElemType leftDist = left->MaxDistance(queryNode); - ElemType rightDist = right->MaxDistance(queryNode); - if (leftDist > rightDist) - return 0; - if (rightDist > leftDist) - return 1; - return NumChildren(); -} - -/** - * Return a bound on the furthest point in the node from the center. This - * returns 0 unless the node is a leaf. - */ -template class BoundType, - template - class SplitType> -inline -typename BinarySpaceTree::ElemType -BinarySpaceTree::FurthestPointDistance() const -{ - if (!IsLeaf()) - return 0.0; - - // Otherwise return the distance from the center to a corner of the bound. - return 0.5 * bound.Diameter(); -} - -/** - * Return the furthest possible descendant distance. This returns the maximum - * distance from the center to the edge of the bound and not the empirical - * quantity which is the actual furthest descendant distance. So the actual - * furthest descendant distance may be less than what this method returns (but - * it will never be greater than this). - */ -template class BoundType, - template - class SplitType> -inline -typename BinarySpaceTree::ElemType -BinarySpaceTree::FurthestDescendantDistance() const -{ - return furthestDescendantDistance; -} - -//! Return the minimum distance from the center to any bound edge. -template class BoundType, - template - class SplitType> -inline -typename BinarySpaceTree::ElemType -BinarySpaceTree::MinimumBoundDistance() const -{ - return bound.MinWidth() / 2.0; -} - -/** - * Return the specified child. - */ -template class BoundType, - template - class SplitType> -inline BinarySpaceTree& - BinarySpaceTree::Child(const size_t child) const -{ - if (child == 0) - return *left; - else - return *right; -} - -/** - * Return the number of points contained in this node. - */ -template class BoundType, - template - class SplitType> -inline size_t BinarySpaceTree::NumPoints() const -{ - if (left) - return 0; - - return count; -} - -/** - * Return the number of descendants contained in the node. - */ -template class BoundType, - template - class SplitType> -inline size_t BinarySpaceTree::NumDescendants() const -{ - return count; -} - -/** - * Return the index of a particular descendant contained in this node. - */ -template class BoundType, - template - class SplitType> -inline size_t BinarySpaceTree::Descendant(const size_t index) const -{ - return (begin + index); -} - -/** - * Return the index of a particular point contained in this node. - */ -template class BoundType, - template - class SplitType> -inline size_t BinarySpaceTree::Point(const size_t index) const -{ - return (begin + index); -} - -template class BoundType, - template - class SplitType> -void BinarySpaceTree:: - SplitNode(const size_t maxLeafSize, - SplitType, MatType>& splitter) -{ - // We need to expand the bounds of this node properly. - UpdateBound(bound); - - // Calculate the furthest descendant distance. - furthestDescendantDistance = 0.5 * bound.Diameter(); - - // Now, check if we need to split at all. - if (count <= maxLeafSize) - return; // We can't split this. - - // splitCol denotes the two partitions of the dataset after the split. The - // points on its left go to the left child and the others go to the right - // child. - size_t splitCol; - - // Find the partition of the node. This method does not perform the split. - typename Split::SplitInfo splitInfo; - - const bool split = splitter.SplitNode(bound, *dataset, begin, count, - splitInfo); - - // The node may not be always split. For instance, if all the points are the - // same, we can't split them. - if (!split) - return; - - // Perform the actual splitting. This will order the dataset such that - // points that belong to the left subtree are on the left of splitCol, and - // points from the right subtree are on the right side of splitCol. - splitCol = splitter.PerformSplit(*dataset, begin, count, splitInfo); - - assert(splitCol > begin); - assert(splitCol < begin + count); - - // Now that we know the split column, we will recursively split the children - // by calling their constructors (which perform this splitting process). - left = new BinarySpaceTree(this, begin, splitCol - begin, splitter, - maxLeafSize); - right = new BinarySpaceTree(this, splitCol, begin + count - splitCol, - splitter, maxLeafSize); - - // Calculate parent distances for those two nodes. - arma::vec center, leftCenter, rightCenter; - Center(center); - left->Center(leftCenter); - right->Center(rightCenter); - - const ElemType leftParentDistance = MetricType::Evaluate(center, leftCenter); - const ElemType rightParentDistance = MetricType::Evaluate(center, - rightCenter); - - left->ParentDistance() = leftParentDistance; - right->ParentDistance() = rightParentDistance; -} - -template class BoundType, - template - class SplitType> -void BinarySpaceTree:: -SplitNode(std::vector& oldFromNew, - const size_t maxLeafSize, - SplitType, MatType>& splitter) -{ - // We need to expand the bounds of this node properly. - UpdateBound(bound); - - // Calculate the furthest descendant distance. - furthestDescendantDistance = 0.5 * bound.Diameter(); - - // First, check if we need to split at all. - if (count <= maxLeafSize) - return; // We can't split this. - - // splitCol denotes the two partitions of the dataset after the split. The - // points on its left go to the left child and the others go to the right - // child. - size_t splitCol; - - // Find the partition of the node. This method does not perform the split. - typename Split::SplitInfo splitInfo; - - const bool split = splitter.SplitNode(bound, *dataset, begin, count, - splitInfo); - - // The node may not be always split. For instance, if all the points are the - // same, we can't split them. - if (!split) - return; - - // Perform the actual splitting. This will order the dataset such that - // points that belong to the left subtree are on the left of splitCol, and - // points from the right subtree are on the right side of splitCol. - splitCol = splitter.PerformSplit(*dataset, begin, count, splitInfo, - oldFromNew); - - assert(splitCol > begin); - assert(splitCol < begin + count); - - // Now that we know the split column, we will recursively split the children - // by calling their constructors (which perform this splitting process). - left = new BinarySpaceTree(this, begin, splitCol - begin, oldFromNew, - splitter, maxLeafSize); - right = new BinarySpaceTree(this, splitCol, begin + count - splitCol, - oldFromNew, splitter, maxLeafSize); - - // Calculate parent distances for those two nodes. - arma::vec center, leftCenter, rightCenter; - Center(center); - left->Center(leftCenter); - right->Center(rightCenter); - - const ElemType leftParentDistance = MetricType::Evaluate(center, leftCenter); - const ElemType rightParentDistance = MetricType::Evaluate(center, - rightCenter); - - left->ParentDistance() = leftParentDistance; - right->ParentDistance() = rightParentDistance; -} - -template class BoundType, - template - class SplitType> -template -void BinarySpaceTree:: -UpdateBound(BoundType2& boundToUpdate) -{ - if (count > 0) - boundToUpdate |= dataset->cols(begin, begin + count - 1); -} - -template class BoundType, - template - class SplitType> -void BinarySpaceTree:: -UpdateBound(bound::HollowBallBound& boundToUpdate) -{ - if (!parent) - { - if (count > 0) - boundToUpdate |= dataset->cols(begin, begin + count - 1); - return; - } - - if (parent->left != NULL && parent->left != this) - { - boundToUpdate.HollowCenter() = parent->left->bound.Center(); - boundToUpdate.InnerRadius() = std::numeric_limits::max(); - } - - if (count > 0) - boundToUpdate |= dataset->cols(begin, begin + count - 1); -} - -// Default constructor (private), for boost::serialization. -template class BoundType, - template - class SplitType> -BinarySpaceTree:: - BinarySpaceTree() : - left(NULL), - right(NULL), - parent(NULL), - begin(0), - count(0), - stat(*this), - parentDistance(0), - furthestDescendantDistance(0), - dataset(NULL) -{ - // Nothing to do. -} - -/** - * Serialize the tree. - */ -template class BoundType, - template - class SplitType> -template -void BinarySpaceTree:: - serialize(Archive& ar, const unsigned int /* version */) -{ - // If we're loading, and we have children, they need to be deleted. - if (Archive::is_loading::value) - { - if (left) - delete left; - if (right) - delete right; - if (!parent) - delete dataset; - - parent = NULL; - left = NULL; - right = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(begin); - ar & BOOST_SERIALIZATION_NVP(count); - ar & BOOST_SERIALIZATION_NVP(bound); - ar & BOOST_SERIALIZATION_NVP(stat); - - ar & BOOST_SERIALIZATION_NVP(parentDistance); - ar & BOOST_SERIALIZATION_NVP(furthestDescendantDistance); - ar & BOOST_SERIALIZATION_NVP(dataset); - - // Save children last; otherwise boost::serialization gets confused. - bool hasLeft = (left != NULL); - bool hasRight = (right != NULL); - - ar & BOOST_SERIALIZATION_NVP(hasLeft); - ar & BOOST_SERIALIZATION_NVP(hasRight); - if (hasLeft) - ar & BOOST_SERIALIZATION_NVP(left); - if (hasRight) - ar & BOOST_SERIALIZATION_NVP(right); - - if (Archive::is_loading::value) - { - if (left) - left->parent = this; - if (right) - right->parent = this; - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/breadth_first_dual_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/breadth_first_dual_tree_traverser.hpp deleted file mode 100644 index b313b5a72..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/breadth_first_dual_tree_traverser.hpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @file breadth_first_dual_tree_traverser.hpp - * @author Ryan Curtin - * - * Defines the BreadthFirstDualTreeTraverser for the BinarySpaceTree tree type. - * This is a nested class of BinarySpaceTree which traverses two trees in a - * breadth-first manner with a given set of rules which indicate the branches - * which can be pruned and the order in which to recurse. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_BF_DUAL_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_BF_DUAL_TREE_TRAVERSER_HPP - -#include -#include - -#include "../binary_space_tree.hpp" - -namespace mlpack { -namespace tree { - -template -struct QueueFrame -{ - TreeType* queryNode; - TreeType* referenceNode; - size_t queryDepth; - double score; - TraversalInfoType traversalInfo; -}; - -template class BoundType, - template - class SplitType> -template -class BinarySpaceTree::BreadthFirstDualTreeTraverser -{ - public: - /** - * Instantiate the dual-tree traverser with the given rule set. - */ - BreadthFirstDualTreeTraverser(RuleType& rule); - - typedef QueueFrame - QueueFrameType; - - /** - * Traverse the two trees. This does not reset the number of prunes. - * - * @param queryNode The query node to be traversed. - * @param referenceNode The reference node to be traversed. - * @param score The score of the current node combination. - */ - void Traverse(BinarySpaceTree& queryNode, - BinarySpaceTree& referenceNode); - void Traverse(BinarySpaceTree& queryNode, - std::priority_queue& referenceQueue); - - //! Get the number of prunes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of prunes. - size_t& NumPrunes() { return numPrunes; } - - //! Get the number of visited combinations. - size_t NumVisited() const { return numVisited; } - //! Modify the number of visited combinations. - size_t& NumVisited() { return numVisited; } - - //! Get the number of times a node combination was scored. - size_t NumScores() const { return numScores; } - //! Modify the number of times a node combination was scored. - size_t& NumScores() { return numScores; } - - //! Get the number of times a base case was calculated. - size_t NumBaseCases() const { return numBaseCases; } - //! Modify the number of times a base case was calculated. - size_t& NumBaseCases() { return numBaseCases; } - - private: - //! Reference to the rules with which the trees will be traversed. - RuleType& rule; - - //! The number of prunes. - size_t numPrunes; - - //! The number of node combinations that have been visited during traversal. - size_t numVisited; - - //! The number of times a node combination was scored. - size_t numScores; - - //! The number of times a base case was calculated. - size_t numBaseCases; - - //! Traversal information, held in the class so that it isn't continually - //! being reallocated. - typename RuleType::TraversalInfoType traversalInfo; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "breadth_first_dual_tree_traverser_impl.hpp" - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_BF_DUAL_TREE_TRAVERSER_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/breadth_first_dual_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/breadth_first_dual_tree_traverser_impl.hpp deleted file mode 100644 index fc0eabebe..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/breadth_first_dual_tree_traverser_impl.hpp +++ /dev/null @@ -1,210 +0,0 @@ -/** - * @file breadth_first_dual_tree_traverser_impl.hpp - * @author Ryan Curtin - * - * Implementation of the BreadthFirstDualTreeTraverser for BinarySpaceTree. - * This is a way to perform a dual-tree traversal of two trees. The trees must - * be the same type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_BF_DUAL_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_BF_DUAL_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "breadth_first_dual_tree_traverser.hpp" - -namespace mlpack { -namespace tree { - -template class BoundType, - template - class SplitType> -template -BinarySpaceTree:: -BreadthFirstDualTreeTraverser::BreadthFirstDualTreeTraverser( - RuleType& rule) : - rule(rule), - numPrunes(0), - numVisited(0), - numScores(0), - numBaseCases(0) -{ /* Nothing to do. */ } - -template -bool operator<(const QueueFrame& a, - const QueueFrame& b) -{ - if (a.queryDepth > b.queryDepth) - return true; - else if ((a.queryDepth == b.queryDepth) && (a.score > b.score)) - return true; - return false; -} - -template class BoundType, - template - class SplitType> -template -void BinarySpaceTree:: -BreadthFirstDualTreeTraverser::Traverse( - BinarySpaceTree& - queryRoot, - BinarySpaceTree& - referenceRoot) -{ - // Increment the visit counter. - ++numVisited; - - // Store the current traversal info. - traversalInfo = rule.TraversalInfo(); - - // Must score the root combination. - const double rootScore = rule.Score(queryRoot, referenceRoot); - if (rootScore == DBL_MAX) - return; // This probably means something is wrong. - - std::priority_queue queue; - - QueueFrameType rootFrame; - rootFrame.queryNode = &queryRoot; - rootFrame.referenceNode = &referenceRoot; - rootFrame.queryDepth = 0; - rootFrame.score = 0.0; - rootFrame.traversalInfo = rule.TraversalInfo(); - - queue.push(rootFrame); - - // Start the traversal. - Traverse(queryRoot, queue); -} - -template class BoundType, - template - class SplitType> -template -void BinarySpaceTree:: -BreadthFirstDualTreeTraverser::Traverse( - BinarySpaceTree& - queryNode, - std::priority_queue& referenceQueue) -{ - // Store queues for the children. We will recurse into the children once our - // queue is empty. - std::priority_queue leftChildQueue; - std::priority_queue rightChildQueue; - - while (!referenceQueue.empty()) - { - QueueFrameType currentFrame = referenceQueue.top(); - referenceQueue.pop(); - - BinarySpaceTree& queryNode = *currentFrame.queryNode; - BinarySpaceTree& referenceNode = *currentFrame.referenceNode; - typename RuleType::TraversalInfoType ti = currentFrame.traversalInfo; - rule.TraversalInfo() = ti; - const size_t queryDepth = currentFrame.queryDepth; - - double score = rule.Score(queryNode, referenceNode); - ++numScores; - - if (score == DBL_MAX) - { - ++numPrunes; - continue; - } - - // If both are leaves, we must evaluate the base case. - if (queryNode.IsLeaf() && referenceNode.IsLeaf()) - { - // Loop through each of the points in each node. - const size_t queryEnd = queryNode.Begin() + queryNode.Count(); - const size_t refEnd = referenceNode.Begin() + referenceNode.Count(); - for (size_t query = queryNode.Begin(); query < queryEnd; ++query) - { - // See if we need to investigate this point (this function should be - // implemented for the single-tree recursion too). Restore the - // traversal information first. -// const double childScore = rule.Score(query, referenceNode); - -// if (childScore == DBL_MAX) -// continue; // We can't improve this particular point. - - for (size_t ref = referenceNode.Begin(); ref < refEnd; ++ref) - rule.BaseCase(query, ref); - - numBaseCases += referenceNode.Count(); - } - } - else if ((!queryNode.IsLeaf()) && referenceNode.IsLeaf()) - { - // We have to recurse down the query node. - QueueFrameType fl = { queryNode.Left(), &referenceNode, queryDepth + 1, - score, rule.TraversalInfo() }; - leftChildQueue.push(fl); - - QueueFrameType fr = { queryNode.Right(), &referenceNode, queryDepth + 1, - score, ti }; - rightChildQueue.push(fr); - } - else if (queryNode.IsLeaf() && (!referenceNode.IsLeaf())) - { - // We have to recurse down the reference node. In this case the recursion - // order does matter. Before recursing, though, we have to set the - // traversal information correctly. - QueueFrameType fl = { &queryNode, referenceNode.Left(), queryDepth, - score, rule.TraversalInfo() }; - referenceQueue.push(fl); - - QueueFrameType fr = { &queryNode, referenceNode.Right(), queryDepth, - score, ti }; - referenceQueue.push(fr); - } - else - { - // We have to recurse down both query and reference nodes. Because the - // query descent order does not matter, we will go to the left query child - // first. Before recursing, we have to set the traversal information - // correctly. - QueueFrameType fll = { queryNode.Left(), referenceNode.Left(), - queryDepth + 1, score, rule.TraversalInfo() }; - leftChildQueue.push(fll); - - QueueFrameType flr = { queryNode.Left(), referenceNode.Right(), - queryDepth + 1, score, rule.TraversalInfo() }; - leftChildQueue.push(flr); - - QueueFrameType frl = { queryNode.Right(), referenceNode.Left(), - queryDepth + 1, score, rule.TraversalInfo() }; - rightChildQueue.push(frl); - - QueueFrameType frr = { queryNode.Right(), referenceNode.Right(), - queryDepth + 1, score, rule.TraversalInfo() }; - rightChildQueue.push(frr); - } - } - - // Now, recurse into the left and right children queues. The order doesn't - // matter. - if (leftChildQueue.size() > 0) - Traverse(*queryNode.Left(), leftChildQueue); - if (rightChildQueue.size() > 0) - Traverse(*queryNode.Right(), rightChildQueue); -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_BF_DUAL_TREE_TRAVERSER_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/dual_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/dual_tree_traverser.hpp deleted file mode 100644 index 8129efea7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/dual_tree_traverser.hpp +++ /dev/null @@ -1,99 +0,0 @@ -/** - * @file dual_tree_traverser.hpp - * @author Ryan Curtin - * - * Defines the DualTreeTraverser for the BinarySpaceTree tree type. This is a - * nested class of BinarySpaceTree which traverses two trees in a depth-first - * manner with a given set of rules which indicate the branches which can be - * pruned and the order in which to recurse. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_DUAL_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_DUAL_TREE_TRAVERSER_HPP - -#include - -#include "binary_space_tree.hpp" - -namespace mlpack { -namespace tree { - -template class BoundType, - template - class SplitType> -template -class BinarySpaceTree::DualTreeTraverser -{ - public: - /** - * Instantiate the dual-tree traverser with the given rule set. - */ - DualTreeTraverser(RuleType& rule); - - /** - * Traverse the two trees. This does not reset the number of prunes. - * - * @param queryNode The query node to be traversed. - * @param referenceNode The reference node to be traversed. - * @param score The score of the current node combination. - */ - void Traverse(BinarySpaceTree& queryNode, - BinarySpaceTree& referenceNode); - - //! Get the number of prunes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of prunes. - size_t& NumPrunes() { return numPrunes; } - - //! Get the number of visited combinations. - size_t NumVisited() const { return numVisited; } - //! Modify the number of visited combinations. - size_t& NumVisited() { return numVisited; } - - //! Get the number of times a node combination was scored. - size_t NumScores() const { return numScores; } - //! Modify the number of times a node combination was scored. - size_t& NumScores() { return numScores; } - - //! Get the number of times a base case was calculated. - size_t NumBaseCases() const { return numBaseCases; } - //! Modify the number of times a base case was calculated. - size_t& NumBaseCases() { return numBaseCases; } - - private: - //! Reference to the rules with which the trees will be traversed. - RuleType& rule; - - //! The number of prunes. - size_t numPrunes; - - //! The number of node combinations that have been visited during traversal. - size_t numVisited; - - //! The number of times a node combination was scored. - size_t numScores; - - //! The number of times a base case was calculated. - size_t numBaseCases; - - //! Traversal information, held in the class so that it isn't continually - //! being reallocated. - typename RuleType::TraversalInfoType traversalInfo; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "dual_tree_traverser_impl.hpp" - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_DUAL_TREE_TRAVERSER_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/dual_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/dual_tree_traverser_impl.hpp deleted file mode 100644 index 1c9f6afc8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/dual_tree_traverser_impl.hpp +++ /dev/null @@ -1,346 +0,0 @@ -/** - * @file dual_tree_traverser_impl.hpp - * @author Ryan Curtin - * - * Implementation of the DualTreeTraverser for BinarySpaceTree. This is a way - * to perform a dual-tree traversal of two trees. The trees must be the same - * type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_DUAL_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_DUAL_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "dual_tree_traverser.hpp" - -namespace mlpack { -namespace tree { - -template class BoundType, - template - class SplitType> -template -BinarySpaceTree:: -DualTreeTraverser::DualTreeTraverser(RuleType& rule) : - rule(rule), - numPrunes(0), - numVisited(0), - numScores(0), - numBaseCases(0) -{ /* Nothing to do. */ } - -template class BoundType, - template - class SplitType> -template -void BinarySpaceTree:: -DualTreeTraverser::Traverse( - BinarySpaceTree& - queryNode, - BinarySpaceTree& - referenceNode) -{ - // Increment the visit counter. - ++numVisited; - - // Store the current traversal info. - traversalInfo = rule.TraversalInfo(); - - // If both are leaves, we must evaluate the base case. - if (queryNode.IsLeaf() && referenceNode.IsLeaf()) - { - // Loop through each of the points in each node. - const size_t queryEnd = queryNode.Begin() + queryNode.Count(); - const size_t refEnd = referenceNode.Begin() + referenceNode.Count(); - for (size_t query = queryNode.Begin(); query < queryEnd; ++query) - { - // See if we need to investigate this point (this function should be - // implemented for the single-tree recursion too). Restore the traversal - // information first. - rule.TraversalInfo() = traversalInfo; - const double childScore = rule.Score(query, referenceNode); - - if (childScore == DBL_MAX) - continue; // We can't improve this particular point. - - for (size_t ref = referenceNode.Begin(); ref < refEnd; ++ref) - rule.BaseCase(query, ref); - - numBaseCases += referenceNode.Count(); - } - } - else if (((!queryNode.IsLeaf()) && referenceNode.IsLeaf()) || - (queryNode.NumDescendants() > 3 * referenceNode.NumDescendants() && - !queryNode.IsLeaf() && !referenceNode.IsLeaf())) - { - // We have to recurse down the query node. In this case the recursion order - // does not matter. - const double leftScore = rule.Score(*queryNode.Left(), referenceNode); - ++numScores; - - if (leftScore != DBL_MAX) - Traverse(*queryNode.Left(), referenceNode); - else - ++numPrunes; - - // Before recursing, we have to set the traversal information correctly. - rule.TraversalInfo() = traversalInfo; - const double rightScore = rule.Score(*queryNode.Right(), referenceNode); - ++numScores; - - if (rightScore != DBL_MAX) - Traverse(*queryNode.Right(), referenceNode); - else - ++numPrunes; - } - else if (queryNode.IsLeaf() && (!referenceNode.IsLeaf())) - { - // We have to recurse down the reference node. In this case the recursion - // order does matter. Before recursing, though, we have to set the - // traversal information correctly. - double leftScore = rule.Score(queryNode, *referenceNode.Left()); - typename RuleType::TraversalInfoType leftInfo = rule.TraversalInfo(); - rule.TraversalInfo() = traversalInfo; - double rightScore = rule.Score(queryNode, *referenceNode.Right()); - numScores += 2; - - if (leftScore < rightScore) - { - // Recurse to the left. Restore the left traversal info. Store the right - // traversal info. - traversalInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(queryNode, *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(queryNode, *referenceNode.Right(), rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = traversalInfo; - Traverse(queryNode, *referenceNode.Right()); - } - else - ++numPrunes; - } - else if (rightScore < leftScore) - { - // Recurse to the right. - Traverse(queryNode, *referenceNode.Right()); - - // Is it still valid to recurse to the left? - leftScore = rule.Rescore(queryNode, *referenceNode.Left(), leftScore); - - if (leftScore != DBL_MAX) - { - // Restore the left traversal info. - rule.TraversalInfo() = leftInfo; - Traverse(queryNode, *referenceNode.Left()); - } - else - ++numPrunes; - } - else // leftScore is equal to rightScore. - { - if (leftScore == DBL_MAX) - { - numPrunes += 2; - } - else - { - // Choose the left first. Restore the left traversal info. Store the - // right traversal info. - traversalInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(queryNode, *referenceNode.Left()); - - rightScore = rule.Rescore(queryNode, *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = traversalInfo; - Traverse(queryNode, *referenceNode.Right()); - } - else - ++numPrunes; - } - } - } - else - { - // We have to recurse down both query and reference nodes. Because the - // query descent order does not matter, we will go to the left query child - // first. Before recursing, we have to set the traversal information - // correctly. - double leftScore = rule.Score(*queryNode.Left(), *referenceNode.Left()); - typename RuleType::TraversalInfoType leftInfo = rule.TraversalInfo(); - rule.TraversalInfo() = traversalInfo; - double rightScore = rule.Score(*queryNode.Left(), *referenceNode.Right()); - typename RuleType::TraversalInfoType rightInfo; - numScores += 2; - - if (leftScore < rightScore) - { - // Recurse to the left. Restore the left traversal info. Store the right - // traversal info. - rightInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Left(), *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(*queryNode.Left(), *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = rightInfo; - Traverse(*queryNode.Left(), *referenceNode.Right()); - } - else - ++numPrunes; - } - else if (rightScore < leftScore) - { - // Recurse to the right. - Traverse(*queryNode.Left(), *referenceNode.Right()); - - // Is it still valid to recurse to the left? - leftScore = rule.Rescore(*queryNode.Left(), *referenceNode.Left(), - leftScore); - - if (leftScore != DBL_MAX) - { - // Restore the left traversal info. - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Left(), *referenceNode.Left()); - } - else - ++numPrunes; - } - else - { - if (leftScore == DBL_MAX) - { - numPrunes += 2; - } - else - { - // Choose the left first. Restore the left traversal info and store the - // right traversal info. - rightInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Left(), *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(*queryNode.Left(), *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal information. - rule.TraversalInfo() = rightInfo; - Traverse(*queryNode.Left(), *referenceNode.Right()); - } - else - ++numPrunes; - } - } - - // Restore the main traversal information. - rule.TraversalInfo() = traversalInfo; - - // Now recurse down the right query node. - leftScore = rule.Score(*queryNode.Right(), *referenceNode.Left()); - leftInfo = rule.TraversalInfo(); - rule.TraversalInfo() = traversalInfo; - rightScore = rule.Score(*queryNode.Right(), *referenceNode.Right()); - numScores += 2; - - if (leftScore < rightScore) - { - // Recurse to the left. Restore the left traversal info. Store the right - // traversal info. - rightInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Right(), *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(*queryNode.Right(), *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = rightInfo; - Traverse(*queryNode.Right(), *referenceNode.Right()); - } - else - ++numPrunes; - } - else if (rightScore < leftScore) - { - // Recurse to the right. - Traverse(*queryNode.Right(), *referenceNode.Right()); - - // Is it still valid to recurse to the left? - leftScore = rule.Rescore(*queryNode.Right(), *referenceNode.Left(), - leftScore); - - if (leftScore != DBL_MAX) - { - // Restore the left traversal info. - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Right(), *referenceNode.Left()); - } - else - ++numPrunes; - } - else - { - if (leftScore == DBL_MAX) - { - numPrunes += 2; - } - else - { - // Choose the left first. Restore the left traversal info. Store the - // right traversal info. - rightInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Right(), *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(*queryNode.Right(), *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = rightInfo; - Traverse(*queryNode.Right(), *referenceNode.Right()); - } - else - ++numPrunes; - } - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_DUAL_TREE_TRAVERSER_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/mean_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/mean_split.hpp deleted file mode 100644 index b1944613d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/mean_split.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @file mean_split.hpp - * @author Yash Vadalia - * @author Ryan Curtin - * - * Definition of MeanSplit, a class that splits a binary space partitioning tree - * node into two parts using the mean of the values in a certain dimension. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_HPP - -#include -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * A binary space partitioning tree node is split into its left and right child. - * The split is done in the dimension that has the maximum width. The points are - * divided into two parts based on the mean in this dimension. - */ -template -class MeanSplit -{ - public: - //! An information about the partition. - struct SplitInfo - { - //! The dimension to split the node on. - size_t splitDimension; - //! The split in dimension splitDimension is based on this value. - double splitVal; - }; - - /** - * Find the partition of the node. This method fills up the dimension - * that will be used to split the node and the value according which the split - * will be performed. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo An information about the split. This information contains - * the dimension and the value. - */ - static bool SplitNode(const BoundType& bound, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo); - - /** - * Perform the split process according to the information about the - * split. This will order the dataset such that points that belong to the left - * subtree are on the left of the split column, and points from the right - * subtree are on the right side of the split column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo) - { - return split::PerformSplit(data, begin, count, - splitInfo); - } - - /** - * Perform the split process according to the information about the split and - * return the list of changed indices. This will order the dataset such that - * points that belong to the left subtree are on the left of the split column, - * and points from the right subtree are on the right side of the split - * column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo, - std::vector& oldFromNew) - { - return split::PerformSplit(data, begin, count, - splitInfo, oldFromNew); - } - - /** - * Indicates that a point should be assigned to the left subtree. - * - * @param point The point that is being assigned. - * @param splitInfo An information about the split. - */ - template - static bool AssignToLeftNode(const VecType& point, - const SplitInfo& splitInfo) - { - return point[splitInfo.splitDimension] < splitInfo.splitVal; - } -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "mean_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/mean_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/mean_split_impl.hpp deleted file mode 100644 index ff6f932cc..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/mean_split_impl.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file mean_split_impl.hpp - * @author Yash Vadalia - * @author Ryan Curtin - * - * Implementation of class(MeanSplit) to split a binary space partition tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_IMPL_HPP - -#include "mean_split.hpp" - -namespace mlpack { -namespace tree { - -template -bool MeanSplit::SplitNode(const BoundType& bound, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo) -{ - double maxWidth = -1; - - splitInfo.splitDimension = data.n_rows; // Indicate invalid. - - // Find the split dimension. If the bound is tight, we only need to consult - // the bound's width. - if (bound::BoundTraits::HasTightBounds) - { - for (size_t d = 0; d < data.n_rows; d++) - { - const double width = bound[d].Width(); - - if (width > maxWidth) - { - maxWidth = width; - splitInfo.splitDimension = d; - } - } - } - else - { - // We must individually calculate bounding boxes. - math::Range* ranges = new math::Range[data.n_rows]; - for (size_t i = begin; i < begin + count; ++i) - { - // Expand each dimension as necessary. - for (size_t d = 0; d < data.n_rows; ++d) - { - const double val = data(d, i); - if (val < ranges[d].Lo()) - ranges[d].Lo() = val; - if (val > ranges[d].Hi()) - ranges[d].Hi() = val; - } - } - - // Now, which is the widest? - for (size_t d = 0; d < data.n_rows; d++) - { - const double width = ranges[d].Width(); - if (width > maxWidth) - { - maxWidth = width; - splitInfo.splitDimension = d; - } - } - - delete[] ranges; - } - - if (maxWidth == 0) // All these points are the same. We can't split. - return false; - - // Split in the mean of that dimension. - splitInfo.splitVal = 0.0; - for (size_t i = begin; i < begin + count; ++i) - splitInfo.splitVal += data(splitInfo.splitDimension, i); - splitInfo.splitVal /= count; - - Log::Assert(splitInfo.splitVal >= bound[splitInfo.splitDimension].Lo()); - Log::Assert(splitInfo.splitVal <= bound[splitInfo.splitDimension].Hi()); - - return true; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/midpoint_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/midpoint_split.hpp deleted file mode 100644 index cbbe86136..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/midpoint_split.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @file midpoint_split.hpp - * @author Yash Vadalia - * @author Ryan Curtin - * - * Definition of MidpointSplit, a class that splits a binary space partitioning - * tree node into two parts using the midpoint of the values in a certain - * dimension. The dimension to split on is the dimension with maximum variance. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_MIDPOINT_SPLIT_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_MIDPOINT_SPLIT_HPP - -#include -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * A binary space partitioning tree node is split into its left and right child. - * The split is done in the dimension that has the maximum width. The points are - * divided into two parts based on the midpoint in this dimension. - */ -template -class MidpointSplit -{ - public: - //! A struct that contains an information about the split. - struct SplitInfo - { - //! The dimension to split the node on. - size_t splitDimension; - //! The split in dimension splitDimension is based on this value. - double splitVal; - }; - /** - * Find the partition of the node. This method fills up the dimension that - * will be used to split the node and the value according which the split - * will be performed. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo An information about the split. This information contains - * the dimension and the value. - */ - static bool SplitNode(const BoundType& bound, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo); - - /** - * Perform the split process according to the information about the - * split. This will order the dataset such that points that belong to the left - * subtree are on the left of the split column, and points from the right - * subtree are on the right side of the split column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo) - { - return split::PerformSplit(data, begin, count, - splitInfo); - } - - /** - * Perform the split process according to the information about the split and - * return the list of changed indices. This will order the dataset such that - * points that belong to the left subtree are on the left of the split column, - * and points from the right subtree are on the right side of the split - * column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo, - std::vector& oldFromNew) - { - return split::PerformSplit(data, begin, count, - splitInfo, oldFromNew); - } - - /** - * Indicates that a point should be assigned to the left subtree. - * - * @param point The point that is being assigned. - * @param splitInfo An information about the split. - */ - template - static bool AssignToLeftNode(const VecType& point, - const SplitInfo& splitInfo) - { - return point[splitInfo.splitDimension] < splitInfo.splitVal; - } -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "midpoint_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/midpoint_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/midpoint_split_impl.hpp deleted file mode 100644 index aca8341e5..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/midpoint_split_impl.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file midpoint_split_impl.hpp - * @author Yash Vadalia - * @author Ryan Curtin - * - * Implementation of class (MidpointSplit) to split a binary space partition - * tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_MIDPOINT_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_MIDPOINT_SPLIT_IMPL_HPP - -#include "midpoint_split.hpp" -#include - -namespace mlpack { -namespace tree { - -template -bool MidpointSplit::SplitNode(const BoundType& bound, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo) -{ - double maxWidth = -1; - splitInfo.splitDimension = data.n_rows; // Indicate invalid. - - // Find the split dimension. If the bound is tight, we only need to consult - // the bound's width. - if (bound::BoundTraits::HasTightBounds) - { - for (size_t d = 0; d < data.n_rows; d++) - { - const double width = bound[d].Width(); - - if (width > maxWidth) - { - maxWidth = width; - splitInfo.splitDimension = d; - - // Split in the midpoint of that dimension. - splitInfo.splitVal = bound[d].Mid(); - } - } - } - else - { - // We must individually calculate bounding boxes. - math::Range* ranges = new math::Range[data.n_rows]; - for (size_t i = begin; i < begin + count; ++i) - { - // Expand each dimension as necessary. - for (size_t d = 0; d < data.n_rows; ++d) - { - const double val = data(d, i); - if (val < ranges[d].Lo()) - ranges[d].Lo() = val; - if (val > ranges[d].Hi()) - ranges[d].Hi() = val; - } - } - - // Now, which is the widest? - for (size_t d = 0; d < data.n_rows; d++) - { - const double width = ranges[d].Width(); - if (width > maxWidth) - { - maxWidth = width; - splitInfo.splitDimension = d; - // Split in the midpoint of that dimension. - splitInfo.splitVal = ranges[d].Mid(); - } - } - - delete[] ranges; - } - - if (maxWidth <= 0) // All these points are the same. We can't split. - return false; - - // Split in the midpoint of that dimension. - splitInfo.splitVal = bound[splitInfo.splitDimension].Mid(); - - return true; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_max_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_max_split.hpp deleted file mode 100644 index cc120ebea..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_max_split.hpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @file rp_tree_max_split.hpp - * @author Mikhail Lozhnikov - * - * Definition of class (RPTreeMaxSplit) to split a binary space partition - * tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MAX_SPLIT_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MAX_SPLIT_HPP - -#include -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * This class splits a node by a random hyperplane. In order to choose the - * hyperplane we need to choose the normal to the hyperplane and the position - * of the hyperplane i.e. the scalar product of the normal and a point. - * - * A point will be assigned to the left subtree if the product of - * this point and the normal is less or equal to the split value (i.e. the - * position of the hyperplane). - */ -template -class RPTreeMaxSplit -{ - public: - //! The element type held by the matrix type. - typedef typename MatType::elem_type ElemType; - //! An information about the partition. - struct SplitInfo - { - //! The normal vector to the hyperplane that splits the node. - arma::Col direction; - //! The value according to which the node is being split. - ElemType splitVal; - }; - - /** - * Split the node by a random hyperplane. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo An information about the split. This information contains - * the direction and the value. - */ - static bool SplitNode(const BoundType& /*bound*/, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo); - - /** - * Perform the split process according to the information about the - * split. This will order the dataset such that points that belong to the left - * subtree are on the left of the split column, and points from the right - * subtree are on the right side of the split column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo) - { - return split::PerformSplit(data, begin, count, - splitInfo); - } - - /** - * Perform the split process according to the information about the split and - * return the list of changed indices. This will order the dataset such that - * points that belong to the left subtree are on the left of the split column, - * and points from the right subtree are on the right side of the split - * column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo, - std::vector& oldFromNew) - { - return split::PerformSplit(data, begin, count, - splitInfo, oldFromNew); - } - - /** - * Indicates that a point should be assigned to the left subtree. - * - * @param point The point that is being assigned. - * @param splitInfo An information about the split. - */ - template - static bool AssignToLeftNode(const VecType& point, const SplitInfo& splitInfo) - { - return (arma::dot(point, splitInfo.direction) <= splitInfo.splitVal); - } - - private: - /** - * This method finds the position of the hyperplane that will split the node. - * - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param direction A random vector that is the normal to the hyperplane - * which will split the node. - * @param splitVal The value according which the node will be split. - */ - static bool GetSplitVal(const MatType& data, - const size_t begin, - const size_t count, - const arma::Col& direction, - ElemType& splitVal); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "rp_tree_max_split_impl.hpp" - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MAX_SPLIT_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_max_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_max_split_impl.hpp deleted file mode 100644 index 6ccd932c5..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_max_split_impl.hpp +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @file rp_tree_max_split_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of class (RPTreeMaxSplit) to split a binary space partition - * tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MAX_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MAX_SPLIT_IMPL_HPP - -#include "rp_tree_max_split.hpp" -#include "rp_tree_mean_split.hpp" - -namespace mlpack { -namespace tree { - -template -bool RPTreeMaxSplit::SplitNode(const BoundType& /* bound */, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo) -{ - splitInfo.direction.zeros(data.n_rows); - - // Get the normal to the hyperplane. - math::RandVector(splitInfo.direction); - - // Get the value according to which we will perform the split. - return GetSplitVal(data, begin, count, splitInfo.direction, - splitInfo.splitVal); -} - -template -bool RPTreeMaxSplit::GetSplitVal( - const MatType& data, - const size_t begin, - const size_t count, - const arma::Col& direction, - ElemType& splitVal) -{ - const size_t maxNumSamples = 100; - const size_t numSamples = std::min(maxNumSamples, count); - arma::uvec samples; - - // Get no more than numSamples distinct samples. - math::ObtainDistinctSamples(begin, begin + count, numSamples, samples); - - arma::Col values(samples.n_elem); - - // Find the median of scalar products of the samples and the normal vector. - for (size_t k = 0; k < samples.n_elem; k++) - values[k] = arma::dot(data.col(samples[k]), direction); - - const ElemType maximum = arma::max(values); - const ElemType minimum = arma::min(values); - if (minimum == maximum) - return false; - - splitVal = arma::median(values); - - // Add a random deviation to the median. - // This algorithm differs from the method suggested in the random projection - // tree paper, for two reasons: - // 1. Evaluating the method proposed in the paper is time-consuming, since - // we must solve the furthest-pair problem. - // 2. The proposed method does not appear to guarantee that a valid split - // value will be generated (i.e. it can produce a split value where there - // may be no points on the left or the right). - splitVal += math::Random((minimum - splitVal) * 0.75, - (maximum - splitVal) * 0.75); - - if (splitVal == maximum) - splitVal = minimum; - - return true; -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MAX_SPLIT_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_mean_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_mean_split.hpp deleted file mode 100644 index 6dd08a086..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_mean_split.hpp +++ /dev/null @@ -1,179 +0,0 @@ -/** - * @file rp_tree_mean_split.hpp - * @author Mikhail Lozhnikov - * - * Definition of class (RPTreeMaxSplit) to split a binary space partition - * tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MEAN_SPLIT_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MEAN_SPLIT_HPP - -#include -#include "rp_tree_max_split.hpp" -#include -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * This class splits a binary space tree. This class provides two different - * kinds of split. The mean split (i.e. all points are split by the median - * of their distance to the mean point) is performed if the average distance - * between points multiplied by a constant is greater than the diameter of the - * node. Otherwise, the median split (i.e. the node is split by a random - * hyperplane) is performed. - */ -template -class RPTreeMeanSplit -{ - public: - //! The element type held by the matrix type. - typedef typename MatType::elem_type ElemType; - //! An information about the partition. - struct SplitInfo - { - //! The normal to the hyperplane that will split the node. - arma::Col direction; - //! The mean of some sampled points. - arma::Col mean; - //! The value according to which the split will be performed. - ElemType splitVal; - //! Indicates that we should use the mean split algorithm instead of the - //! median split. - bool meanSplit; - }; - - /** - * Split the node according to the mean value in the dimension with maximum - * width. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo An information about the split. This information contains - * the direction and the value. - */ - static bool SplitNode(const BoundType& /* bound */, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo); - - /** - * Perform the split process according to the information about the - * split. This will order the dataset such that points that belong to the left - * subtree are on the left of the split column, and points from the right - * subtree are on the right side of the split column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo) - { - return split::PerformSplit(data, begin, count, - splitInfo); - } - - /** - * Perform the split process according to the information about the split and - * return the list of changed indices. This will order the dataset such that - * points that belong to the left subtree are on the left of the split column, - * and points from the right subtree are on the right side of the split - * column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo, - std::vector& oldFromNew) - { - return split::PerformSplit(data, begin, count, - splitInfo, oldFromNew); - } - - /** - * Indicates that a point should be assigned to the left subtree. - * - * @param point The point that is being assigned. - * @param splitInfo An information about the split. - */ - template - static bool AssignToLeftNode(const VecType& point, const SplitInfo& splitInfo) - { - if (splitInfo.meanSplit) - return arma::dot(point - splitInfo.mean, point - splitInfo.mean) <= - splitInfo.splitVal; - - return (arma::dot(point, splitInfo.direction) <= splitInfo.splitVal); - } - - private: - /** - * Get the average distance between points in the dataset. - * - * @param data The dataset used by the binary space tree. - * @param samples The indices of points that will be used for the calculation. - */ - static ElemType GetAveragePointDistance(MatType& data, - const arma::uvec& samples); - - /** - * Get the median of scalar products of the sampled points and the normal - * to the hyperplane (i.e. the position of the hyperplane). - * - * @param data The dataset used by the binary space tree. - * @param samples The indices of points that will be used for the calculation. - * @param direction The normal to the hyperplane. - * @param splitVal The median value. - */ - static bool GetDotMedian(const MatType& data, - const arma::uvec& samples, - const arma::Col& direction, - ElemType& splitVal); - - /** - * Get the mean point and the median of distance from the mean to any point of - * the dataset. - * - * @param data The dataset used by the binary space tree. - * @param samples The indices of points that will be used for the calculation. - * @param mean The mean point. - * @param splitVal The median value. - */ - static bool GetMeanMedian(const MatType& data, - const arma::uvec& samples, - arma::Col& mean, - ElemType& splitVal); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "rp_tree_mean_split_impl.hpp" - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MEAN_SPLIT_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_mean_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_mean_split_impl.hpp deleted file mode 100644 index 6c55008ad..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/rp_tree_mean_split_impl.hpp +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @file rp_tree_mean_split_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of class (RPTreeMeanSplit) to split a binary space partition - * tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MEAN_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MEAN_SPLIT_IMPL_HPP - -#include "rp_tree_max_split.hpp" - -namespace mlpack { -namespace tree { - -template -bool RPTreeMeanSplit::SplitNode(const BoundType& bound, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo) -{ - const size_t maxNumSamples = 100; - const size_t numSamples = std::min(maxNumSamples, count); - arma::uvec samples; - - // Get no more than numSamples distinct samples. - math::ObtainDistinctSamples(begin, begin + count, numSamples, samples); - - // Find the average distance between points. - ElemType averageDistanceSq = GetAveragePointDistance(data, samples); - - const ElemType threshold = 10; - - if (bound.Diameter() * bound.Diameter() <= threshold * averageDistanceSq) - { - // We will perform the median split. - splitInfo.meanSplit = false; - - splitInfo.direction.zeros(data.n_rows); - - // Get a random normal vector. - math::RandVector(splitInfo.direction); - - // Get the median value of the scalar products of the normal and the - // sampled points. The node will be split according to this value. - return GetDotMedian(data, samples, splitInfo.direction, splitInfo.splitVal); - } - else - { - // We will perform the mean split. - splitInfo.meanSplit = true; - - // Get the median of the distances between the mean point and the sampled - // points. The node will be split according to this value. - return GetMeanMedian(data, samples, splitInfo.mean, splitInfo.splitVal); - } -} - -template -typename MatType::elem_type RPTreeMeanSplit:: -GetAveragePointDistance( - MatType& data, - const arma::uvec& samples) -{ - ElemType dist = 0; - - for (size_t i = 0; i < samples.n_elem; i++) - for (size_t j = i + 1; j < samples.n_elem; j++) - dist += metric::SquaredEuclideanDistance::Evaluate(data.col(samples[i]), - data.col(samples[j])); - - dist /= (samples.n_elem * (samples.n_elem - 1) / 2); - - return dist; -} - -template -bool RPTreeMeanSplit::GetDotMedian( - const MatType& data, - const arma::uvec& samples, - const arma::Col& direction, - ElemType& splitVal) -{ - arma::Col values(samples.n_elem); - - for (size_t k = 0; k < samples.n_elem; k++) - values[k] = arma::dot(data.col(samples[k]), direction); - - const ElemType maximum = arma::max(values); - const ElemType minimum = arma::min(values); - if (minimum == maximum) - return false; - - splitVal = arma::median(values); - - if (splitVal == maximum) - splitVal = minimum; - - return true; -} - -template -bool RPTreeMeanSplit::GetMeanMedian( - const MatType& data, - const arma::uvec& samples, - arma::Col& mean, - ElemType& splitVal) -{ - arma::Col values(samples.n_elem); - - mean = arma::mean(data.cols(samples), 1); - - arma::Col tmp(data.n_rows); - - for (size_t k = 0; k < samples.n_elem; k++) - { - tmp = data.col(samples[k]); - tmp -= mean; - - values[k] = arma::dot(tmp, tmp); - } - - const ElemType maximum = arma::max(values); - const ElemType minimum = arma::min(values); - if (minimum == maximum) - return false; - - splitVal = arma::median(values); - - if (splitVal == maximum) - splitVal = minimum; - - return true; -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_RP_TREE_MEAN_SPLIT_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/single_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/single_tree_traverser.hpp deleted file mode 100644 index 49234b1fb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/single_tree_traverser.hpp +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @file single_tree_traverser.hpp - * @author Ryan Curtin - * - * A nested class of BinarySpaceTree which traverses the entire tree with a - * given set of rules which indicate the branches which can be pruned and the - * order in which to recurse. This traverser is a depth-first traverser. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_SINGLE_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_SINGLE_TREE_TRAVERSER_HPP - -#include - -#include "binary_space_tree.hpp" - -namespace mlpack { -namespace tree { - -template class BoundType, - template - class SplitType> -template -class BinarySpaceTree::SingleTreeTraverser -{ - public: - /** - * Instantiate the single tree traverser with the given rule set. - */ - SingleTreeTraverser(RuleType& rule); - - /** - * Traverse the tree with the given point. - * - * @param queryIndex The index of the point in the query set which is being - * used as the query point. - * @param referenceNode The tree node to be traversed. - */ - void Traverse(const size_t queryIndex, BinarySpaceTree& referenceNode); - - //! Get the number of prunes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of prunes. - size_t& NumPrunes() { return numPrunes; } - - private: - //! Reference to the rules with which the tree will be traversed. - RuleType& rule; - - //! The number of nodes which have been pruned during traversal. - size_t numPrunes; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "single_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/single_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/single_tree_traverser_impl.hpp deleted file mode 100644 index 65d188523..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/single_tree_traverser_impl.hpp +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file single_tree_traverser_impl.hpp - * @author Ryan Curtin - * - * A nested class of BinarySpaceTree which traverses the entire tree with a - * given set of rules which indicate the branches which can be pruned and the - * order in which to recurse. This traverser is a depth-first traverser. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_SINGLE_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_SINGLE_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "single_tree_traverser.hpp" - -#include - -namespace mlpack { -namespace tree { - -template class BoundType, - template - class SplitType> -template -BinarySpaceTree:: -SingleTreeTraverser::SingleTreeTraverser(RuleType& rule) : - rule(rule), - numPrunes(0) -{ /* Nothing to do. */ } - -template class BoundType, - template - class SplitType> -template -void BinarySpaceTree:: -SingleTreeTraverser::Traverse( - const size_t queryIndex, - BinarySpaceTree& - referenceNode) -{ - // If we are a leaf, run the base case as necessary. - if (referenceNode.IsLeaf()) - { - const size_t refEnd = referenceNode.Begin() + referenceNode.Count(); - for (size_t i = referenceNode.Begin(); i < refEnd; ++i) - rule.BaseCase(queryIndex, i); - } - else - { - // If either score is DBL_MAX, we do not recurse into that node. - double leftScore = rule.Score(queryIndex, *referenceNode.Left()); - double rightScore = rule.Score(queryIndex, *referenceNode.Right()); - - if (leftScore < rightScore) - { - // Recurse to the left. - Traverse(queryIndex, *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(queryIndex, *referenceNode.Right(), rightScore); - - if (rightScore != DBL_MAX) - Traverse(queryIndex, *referenceNode.Right()); // Recurse to the right. - else - ++numPrunes; - } - else if (rightScore < leftScore) - { - // Recurse to the right. - Traverse(queryIndex, *referenceNode.Right()); - - // Is it still valid to recurse to the left? - leftScore = rule.Rescore(queryIndex, *referenceNode.Left(), leftScore); - - if (leftScore != DBL_MAX) - Traverse(queryIndex, *referenceNode.Left()); // Recurse to the left. - else - ++numPrunes; - } - else // leftScore is equal to rightScore. - { - if (leftScore == DBL_MAX) - { - numPrunes += 2; // Pruned both left and right. - } - else - { - // Choose the left first. - Traverse(queryIndex, *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(queryIndex, *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - Traverse(queryIndex, *referenceNode.Right()); - else - ++numPrunes; - } - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/traits.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/traits.hpp deleted file mode 100644 index 9556cb649..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/traits.hpp +++ /dev/null @@ -1,251 +0,0 @@ -/** - * @file traits.hpp - * @author Ryan Curtin - * - * Specialization of the TreeTraits class for the BinarySpaceTree type of tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_TRAITS_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_TRAITS_HPP - -#include -#include - -namespace mlpack { -namespace tree { - -/** - * This is a specialization of the TreeTraits class to the BinarySpaceTree tree - * type. It defines characteristics of the binary space tree, and is used to - * help write tree-independent (but still optimized) tree-based algorithms. See - * mlpack/core/tree/tree_traits.hpp for more information. - */ -template class BoundType, - template - class SplitType> -class TreeTraits> -{ - public: - /** - * Each binary space tree node has two children which represent - * non-overlapping subsets of the space which the node represents. Therefore, - * children are not overlapping. - */ - static const bool HasOverlappingChildren = false; - - /** - * Each binary space tree node doesn't share points with any other node. - */ - static const bool HasDuplicatedPoints = false; - - /** - * There is no guarantee that the first point in a node is its centroid. - */ - static const bool FirstPointIsCentroid = false; - - /** - * Points are not contained at multiple levels of the binary space tree. - */ - static const bool HasSelfChildren = false; - - /** - * Points are rearranged during building of the tree. - */ - static const bool RearrangesDataset = true; - - /** - * This is always a binary tree. - */ - static const bool BinaryTree = true; - - /** - * Binary space trees don't have duplicated points, so NumDescendants() - * represents the number of unique descendant points. - */ - static const bool UniqueNumDescendants = true; -}; - -/** - * This is a specialization of the TreeType class to the max-split random - * projection tree. The only difference with general BinarySpaceTree is that the - * tree can have overlapping children. - */ -template class BoundType> -class TreeTraits> -{ - public: - /** - * Children of a random projection tree node may overlap. - */ - static const bool HasOverlappingChildren = true; - - /** - * The tree has not got duplicated points. - */ - static const bool HasDuplicatedPoints = false; - - /** - * There is no guarantee that the first point in a node is its centroid. - */ - static const bool FirstPointIsCentroid = false; - - /** - * Points are not contained at multiple levels of the binary space tree. - */ - static const bool HasSelfChildren = false; - - /** - * Points are rearranged during building of the tree. - */ - static const bool RearrangesDataset = true; - - /** - * This is always a binary tree. - */ - static const bool BinaryTree = true; - - /** - * Binary space trees don't have duplicated points, so NumDescendants() - * represents the number of unique descendant points. - */ - static const bool UniqueNumDescendants = true; -}; - -/** - * This is a specialization of the TreeType class to the mean-split random - * projection tree. The only difference with general BinarySpaceTree is that the - * tree can have overlapping children. - */ -template class BoundType> -class TreeTraits> -{ - public: - /** - * Children of a random projection tree node may overlap. - */ - static const bool HasOverlappingChildren = true; - - /** - * The tree has not got duplicated points. - */ - static const bool HasDuplicatedPoints = false; - - /** - * There is no guarantee that the first point in a node is its centroid. - */ - static const bool FirstPointIsCentroid = false; - - /** - * Points are not contained at multiple levels of the binary space tree. - */ - static const bool HasSelfChildren = false; - - /** - * Points are rearranged during building of the tree. - */ - static const bool RearrangesDataset = true; - - /** - * This is always a binary tree. - */ - static const bool BinaryTree = true; - - /** - * Binary space trees don't have duplicated points, so NumDescendants() - * represents the number of unique descendant points. - */ - static const bool UniqueNumDescendants = true; -}; - -/** - * This is a specialization of the TreeType class to the BallTree tree type. - * The only difference with general BinarySpaceTree is that BallTree can have - * overlapping children. - * See mlpack/core/tree/tree_traits.hpp for more information. - */ -template - class SplitType> -class TreeTraits> -{ - public: - static const bool HasOverlappingChildren = true; - static const bool HasDuplicatedPoints = false; - static const bool FirstPointIsCentroid = false; - static const bool HasSelfChildren = false; - static const bool RearrangesDataset = true; - static const bool BinaryTree = true; - static const bool UniqueNumDescendants = true; -}; - -/** - * This is a specialization of the TreeType class to an arbitrary tree with - * HollowBallBound (currently only the vantage point tree is supported). - * The only difference with general BinarySpaceTree is that the tree can have - * overlapping children. - */ -template - class SplitType> -class TreeTraits> -{ - public: - static const bool HasOverlappingChildren = true; - static const bool HasDuplicatedPoints = false; - static const bool FirstPointIsCentroid = false; - static const bool HasSelfChildren = false; - static const bool RearrangesDataset = true; - static const bool BinaryTree = true; - static const bool UniqueNumDescendants = true; -}; - -/** - * This is a specialization of the TreeType class to the UBTree tree type. - * The only difference with general BinarySpaceTree is that UBTree can have - * overlapping children. - * See mlpack/core/tree/tree_traits.hpp for more information. - */ -template - class SplitType> -class TreeTraits> -{ - public: - static const bool HasOverlappingChildren = true; - static const bool HasDuplicatedPoints = false; - static const bool FirstPointIsCentroid = false; - static const bool HasSelfChildren = false; - static const bool RearrangesDataset = true; - static const bool BinaryTree = true; - static const bool UniqueNumDescendants = true; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/typedef.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/typedef.hpp deleted file mode 100644 index 35d34720b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/typedef.hpp +++ /dev/null @@ -1,306 +0,0 @@ -/** - * @file typedef.hpp - * @author Ryan Curtin - * - * Template typedefs for the BinarySpaceTree class that satisfy the requirements - * of the TreeType policy class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_TYPEDEF_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_TYPEDEF_HPP - -// In case it hasn't been included yet. -#include "../binary_space_tree.hpp" - -namespace mlpack { -namespace tree { - -/** - * The standard midpoint-split kd-tree. This is not the original formulation by - * Bentley but instead the later formulation by Deng and Moore, which only holds - * points in the leaves of the tree. When recursively splitting nodes, the - * KDTree class select the dimension with maximum variance to split on, and - * picks the midpoint of the range in that dimension as the value on which to - * split nodes. - * - * For more information, see the following papers. - * - * @code - * @article{bentley1975multidimensional, - * title={Multidimensional binary search trees used for associative searching}, - * author={Bentley, J.L.}, - * journal={Communications of the ACM}, - * volume={18}, - * number={9}, - * pages={509--517}, - * year={1975}, - * publisher={ACM} - * } - * - * @inproceedings{deng1995multiresolution, - * title={Multiresolution instance-based learning}, - * author={Deng, K. and Moore, A.W.}, - * booktitle={Proceedings of the 1995 International Joint Conference on AI - * (IJCAI-95)}, - * pages={1233--1239}, - * year={1995} - * } - * @endcode - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, BinarySpaceTree, MeanSplitKDTree - */ -template -using KDTree = BinarySpaceTree; - -/** - * A mean-split kd-tree. This is the same as the KDTree, but this particular - * implementation will use the mean of the data in the split dimension as the - * value on which to split, instead of the midpoint. This can sometimes give - * better performance, but it is not always clear which type of tree is best. - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, BinarySpaceTree, KDTree - */ -template -using MeanSplitKDTree = BinarySpaceTree; - -/** - * A midpoint-split ball tree. This tree holds its points only in the leaves, - * similar to the KDTree and MeanSplitKDTree. However, the bounding shape of - * each node is a ball, not a hyper-rectangle. This can make the ball tree - * advantageous in some higher-dimensional situations and for some datasets. - * The tree construction algorithm here is the same as Omohundro's 'K-d - * construction algorithm', except the splitting value is the midpoint, not the - * median. This can result in trees that better reflect the data, although they - * may be unbalanced. - * - * @code - * @techreport{omohundro1989five, - * author={S.M. Omohundro}, - * title={Five balltree construction algorithms}, - * year={1989}, - * institution={University of California, Berkeley International Computer - * Science Institute Technical Reports}, - * number={TR-89-063} - * } - * @endcode - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, BinarySpaceTree, KDTree, MeanSplitBallTree - */ -template -using BallTree = BinarySpaceTree; - -/** - * A mean-split ball tree. This tree, like the BallTree, holds its points only - * in the leaves. The tree construction algorithm here is the same as - * Omohundro's 'K-dc onstruction algorithm', except the splitting value is the - * mean, not the median. This can result in trees that better reflect the data, - * although they may be unbalanced. - * - * @code - * @techreport{omohundro1989five, - * author={S.M. Omohundro}, - * title={Five balltree construction algorithms}, - * year={1989}, - * institution={University of California, Berkeley International Computer - * Science Institute Technical Reports}, - * number={TR-89-063} - * } - * @endcode - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, BinarySpaceTree, BallTree, MeanSplitKDTree - */ -template -using MeanSplitBallTree = BinarySpaceTree; - -/** - * The vantage point tree (which is also called the metric tree. Vantage point - * trees and metric trees were invented independently by Yianilos an Uhlmann) is - * a kind of the binary space tree. When recursively splitting nodes, the VPTree - * class selects the vantage point and splits the node according to the distance - * to this point. Thus, points that are closer to the vantage point form the - * inner subtree. Other points form the outer subtree. The vantage point is - * contained in the first (inner) node. - * - * This implementation differs from the original algorithms. Namely, vantage - * points are not contained in intermediate nodes. The tree has points only in - * the leaves of the tree. - * - * For more information, see the following papers. - * - * @code - * @inproceedings{yianilos1993vptrees, - * author = {Yianilos, Peter N.}, - * title = {Data Structures and Algorithms for Nearest Neighbor Search in - * General Metric Spaces}, - * booktitle = {Proceedings of the Fourth Annual ACM-SIAM Symposium on - * Discrete Algorithms}, - * series = {SODA '93}, - * year = {1993}, - * isbn = {0-89871-313-7}, - * pages = {311--321}, - * numpages = {11}, - * publisher = {Society for Industrial and Applied Mathematics}, - * address = {Philadelphia, PA, USA} - * } - * - * @article{uhlmann1991metrictrees, - * author = {Jeffrey K. Uhlmann}, - * title = {Satisfying general proximity / similarity queries with metric - * trees}, - * journal = {Information Processing Letters}, - * volume = {40}, - * number = {4}, - * pages = {175 - 179}, - * year = {1991}, - * } - * @endcode - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, BinarySpaceTree, VantagePointTree, VPTree - */ -template -using VPTreeSplit = VantagePointSplit; - -template -using VPTree = BinarySpaceTree; - -/** - * A max-split random projection tree. When recursively splitting nodes, the - * MaxSplitRPTree class selects a random hyperplane and splits a node by the - * hyperplane. The tree holds points in leaf nodes. In contrast to the k-d tree, - * children of a MaxSplitRPTree node may overlap. - * - * @code - * @inproceedings{dasgupta2008, - * author = {Dasgupta, Sanjoy and Freund, Yoav}, - * title = {Random Projection Trees and Low Dimensional Manifolds}, - * booktitle = {Proceedings of the Fortieth Annual ACM Symposium on Theory of - * Computing}, - * series = {STOC '08}, - * year = {2008}, - * pages = {537--546}, - * numpages = {10}, - * publisher = {ACM}, - * address = {New York, NY, USA}, - * } - * @endcode - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, BinarySpaceTree, BallTree, MeanSplitKDTree - */ - -template -using MaxRPTree = BinarySpaceTree; - -/** - * A mean-split random projection tree. When recursively splitting nodes, the - * RPTree class may perform one of two different kinds of split. - * Depending on the diameter and the average distance between points, the node - * may be split by a random hyperplane or according to the distance from the - * mean point. The tree holds points in leaf nodes. In contrast to the k-d tree, - * children of a MaxSplitRPTree node may overlap. - * - * @code - * @inproceedings{dasgupta2008, - * author = {Dasgupta, Sanjoy and Freund, Yoav}, - * title = {Random Projection Trees and Low Dimensional Manifolds}, - * booktitle = {Proceedings of the Fortieth Annual ACM Symposium on Theory of - * Computing}, - * series = {STOC '08}, - * year = {2008}, - * pages = {537--546}, - * numpages = {10}, - * publisher = {ACM}, - * address = {New York, NY, USA}, - * } - * @endcode - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, BinarySpaceTree, BallTree, MeanSplitKDTree - */ -template -using RPTree = BinarySpaceTree; - -/** - * The Universal B-tree. When recursively splitting nodes, the class - * calculates addresses of all points and splits each node according to the - * median address. Children may overlap since the implementation - * of a tighter bound requires a lot of arithmetic operations. In order to get - * a tighter bound increase the CellBound::maxNumBounds constant. - * - * @code - * @inproceedings{bayer1997, - * author = {Bayer, Rudolf}, - * title = {The Universal B-Tree for Multidimensional Indexing: General - * Concepts}, - * booktitle = {Proceedings of the International Conference on Worldwide - * Computing and Its Applications}, - * series = {WWCA '97}, - * year = {1997}, - * isbn = {3-540-63343-X}, - * pages = {198--209}, - * numpages = {12}, - * publisher = {Springer-Verlag}, - * address = {London, UK, UK}, - * } - * @endcode - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, BinarySpaceTree, BallTree, MeanSplitKDTree - */ -template -using UBTree = BinarySpaceTree; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/ub_tree_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/ub_tree_split.hpp deleted file mode 100644 index 5d0f75595..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/ub_tree_split.hpp +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @file ub_tree_split.hpp - * @author Mikhail Lozhnikov - * - * Definition of UBTreeSplit, a class that splits the space according - * to the median address of points contained in the node. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_UB_TREE_SPLIT_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_UB_TREE_SPLIT_HPP - -#include -#include "../address.hpp" - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * Split a node into two parts according to the median address of points - * contained in the node. The class reorders the dataset such that points - * with lower addresses belong to the left subtree and points with high - * addresses belong to the right subtree. - */ -template -class UBTreeSplit -{ - public: - //! The type of an address element. - typedef typename std::conditional< - sizeof(typename MatType::elem_type) * CHAR_BIT <= 32, - uint32_t, - uint64_t>::type AddressElemType; - - //! An information about the partition. - struct SplitInfo - { - //! This vector contains addresses of all points in the dataset. - std::vector, size_t>>* addresses; - }; - - /** - * Split the node according to the median address of points contained in the - * node. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo An information about the split (not used here). - */ - bool SplitNode(BoundType& bound, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo); - - /** - * Rearrange the dataset according to the addresses. - * - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo); - - /** - * Rearrange the dataset according to the addresses and return the list - * of changed indices. - * - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo, - std::vector& oldFromNew); - - private: - //! This vector contains addresses of all points in the dataset. - std::vector, size_t>> addresses; - - /** - * Calculate addresses for all points in the dataset. - * - * @param data The dataset used by the binary space tree. - */ - void InitializeAddresses(const MatType& data); - - //! A comparator for sorting addresses. - static bool ComparePair( - const std::pair, size_t>& p1, - const std::pair, size_t>& p2) - { - return bound::addr::CompareAddresses(p1.first, p2.first) < 0; - } -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "ub_tree_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/ub_tree_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/ub_tree_split_impl.hpp deleted file mode 100644 index 46f784b60..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/ub_tree_split_impl.hpp +++ /dev/null @@ -1,241 +0,0 @@ -/** - * @file ub_tree_split_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of UBTreeSplit, a class that splits a node according - * to the median address of points contained in the node. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_UB_TREE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_UB_TREE_SPLIT_IMPL_HPP - -#include "ub_tree_split.hpp" -#include - -namespace mlpack { -namespace tree { - -template -bool UBTreeSplit::SplitNode(BoundType& bound, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo) -{ - constexpr size_t order = sizeof(AddressElemType) * CHAR_BIT; - if (begin == 0 && count == data.n_cols) - { - // Calculate all addresses. - InitializeAddresses(data); - - // Probably this is not a good idea. Maybe it is better to get - // a number of distinct samples and find the median. - std::sort(addresses.begin(), addresses.end(), ComparePair); - - // Save the vector in order to rearrange the dataset later. - splitInfo.addresses = &addresses; - } - else - { - // We have already rearranged the dataset. - splitInfo.addresses = NULL; - } - - // The bound shouldn't contain too many subrectangles. - // In order to minimize the number of hyperrectangles we set last bits - // of the last address in the node to 1 and last bits of the first address - // in the next node to zero in such a way that the ordering is not - // disturbed. - if (begin + count < data.n_cols) - { - // Omit leading equal bits. - size_t row = 0; - arma::Col& lo = addresses[begin + count - 1].first; - const arma::Col& hi = addresses[begin + count].first; - - for (; row < data.n_rows; row++) - if (lo[row] != hi[row]) - break; - - size_t bit = 0; - - for (; bit < order; bit++) - if ((lo[row] & ((AddressElemType) 1 << (order - 1 - bit))) != - (hi[row] & ((AddressElemType) 1 << (order - 1 - bit)))) - break; - - bit++; - - // Replace insignificant bits. - if (bit == order) - { - bit = 0; - row++; - } - else - { - for (; bit < order; bit++) - lo[row] |= ((AddressElemType) 1 << (order - 1 - bit)); - row++; - } - - for (; row < data.n_rows; row++) - for (; bit < order; bit++) - lo[row] |= ((AddressElemType) 1 << (order - 1 - bit)); - } - - // The bound shouldn't contain too many subrectangles. - // In order to minimize the number of hyperrectangles we set last bits - // of the first address in the next node to 0 and last bits of the last - // address in the previous node to 1 in such a way that the ordering is not - // disturbed. - if (begin > 0) - { - // Omit leading equal bits. - size_t row = 0; - const arma::Col& lo = addresses[begin - 1].first; - arma::Col& hi = addresses[begin].first; - - for (; row < data.n_rows; row++) - if (lo[row] != hi[row]) - break; - - size_t bit = 0; - - for (; bit < order; bit++) - if ((lo[row] & ((AddressElemType) 1 << (order - 1 - bit))) != - (hi[row] & ((AddressElemType) 1 << (order - 1 - bit)))) - break; - - bit++; - - // Replace insignificant bits. - if (bit == order) - { - bit = 0; - row++; - } - else - { - for (; bit < order; bit++) - hi[row] &= ~((AddressElemType) 1 << (order - 1 - bit)); - row++; - } - - for (; row < data.n_rows; row++) - for (; bit < order; bit++) - hi[row] &= ~((AddressElemType) 1 << (order - 1 - bit)); - } - - // Set the minimum and the maximum addresses. - for (size_t k = 0; k < bound.Dim(); k++) - { - bound.LoAddress()[k] = addresses[begin].first[k]; - bound.HiAddress()[k] = addresses[begin + count - 1].first[k]; - } - bound.UpdateAddressBounds(data.cols(begin, begin + count - 1)); - - return true; -} - -template -void UBTreeSplit::InitializeAddresses(const MatType& data) -{ - addresses.resize(data.n_cols); - - // Calculate all addresses. - for (size_t i = 0; i < data.n_cols; i++) - { - addresses[i].first.zeros(data.n_rows); - bound::addr::PointToAddress(addresses[i].first, data.col(i)); - addresses[i].second = i; - } -} - -template -size_t UBTreeSplit::PerformSplit( - MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo) -{ - // For the first time we have to rearrange the dataset. - if (splitInfo.addresses) - { - std::vector newFromOld(data.n_cols); - std::vector oldFromNew(data.n_cols); - - for (size_t i = 0; i < splitInfo.addresses->size(); i++) - { - newFromOld[i] = i; - oldFromNew[i] = i; - } - - for (size_t i = 0; i < splitInfo.addresses->size(); i++) - { - size_t index = (*splitInfo.addresses)[i].second; - size_t oldI = oldFromNew[i]; - size_t newIndex = newFromOld[index]; - - data.swap_cols(i, newFromOld[index]); - - size_t tmp = newFromOld[index]; - newFromOld[index] = i; - newFromOld[oldI] = tmp; - - tmp = oldFromNew[i]; - oldFromNew[i] = oldFromNew[newIndex]; - oldFromNew[newIndex] = tmp; - } - } - - // Since the dataset is sorted we can easily obtain the split column. - return begin + count / 2; -} - -template -size_t UBTreeSplit::PerformSplit( - MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo, - std::vector& oldFromNew) -{ - // For the first time we have to rearrange the dataset. - if (splitInfo.addresses) - { - std::vector newFromOld(data.n_cols); - - for (size_t i = 0; i < splitInfo.addresses->size(); i++) - newFromOld[i] = i; - - for (size_t i = 0; i < splitInfo.addresses->size(); i++) - { - size_t index = (*splitInfo.addresses)[i].second; - size_t oldI = oldFromNew[i]; - size_t newIndex = newFromOld[index]; - - data.swap_cols(i, newFromOld[index]); - - size_t tmp = newFromOld[index]; - newFromOld[index] = i; - newFromOld[oldI] = tmp; - - tmp = oldFromNew[i]; - oldFromNew[i] = oldFromNew[newIndex]; - oldFromNew[newIndex] = tmp; - } - } - - // Since the dataset is sorted we can easily obtain the split column. - return begin + count / 2; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/vantage_point_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/vantage_point_split.hpp deleted file mode 100644 index 89271a3d0..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/vantage_point_split.hpp +++ /dev/null @@ -1,177 +0,0 @@ -/** - * @file vantage_point_split.hpp - * @author Mikhail Lozhnikov - * - * Definition of class VantagePointSplit, a class that splits a vantage point - * tree into two parts using the distance to a certain vantage point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_VANTAGE_POINT_SPLIT_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_VANTAGE_POINT_SPLIT_HPP - -#include -#include -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * The class splits a binary space partitioning tree node according to the - * median distance to the vantage point. Thus points that are closer to the - * vantage point belong to the left subtree and points that are farther from - * the vantage point belong to the right subtree. - */ -template -class VantagePointSplit -{ - public: - //! The matrix element type. - typedef typename MatType::elem_type ElemType; - //! The bounding shape type. - typedef typename BoundType::MetricType MetricType; - //! A struct that contains an information about the split. - struct SplitInfo - { - //! The vantage point. - arma::Col vantagePoint; - //! The median distance according to which the node will be split. - ElemType mu; - //! An instance of the MetricType class. - const MetricType* metric; - - SplitInfo() : - mu(0), - metric(NULL) - { } - - template - SplitInfo(const MetricType& metric, const VecType& vantagePoint, - ElemType mu) : - vantagePoint(vantagePoint), - mu(mu), - metric(&metric) - { } - }; - - /** - * Split the node according to the distance to a vantage point. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo An information about the split. This information contains - * the vantage point and the median distance to the vantage point. - */ - static bool SplitNode(const BoundType& bound, - MatType& data, - const size_t begin, - const size_t count, - SplitInfo& splitInfo); - - /** - * Perform the split process according to the information about the - * split. This will order the dataset such that points that belong to the left - * subtree are on the left of the split column, and points from the right - * subtree are on the right side of the split column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo) - { - return split::PerformSplit(data, begin, count, - splitInfo); - } - - /** - * Perform the split process according to the information about the split and - * return the list of changed indices. This will order the dataset such that - * points that belong to the left subtree are on the left of the split column, - * and points from the right subtree are on the right side of the split - * column. - * - * @param bound The bound used for this node. - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - */ - static size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const SplitInfo& splitInfo, - std::vector& oldFromNew) - { - return split::PerformSplit(data, begin, count, - splitInfo, oldFromNew); - } - - /** - * Indicates that a point should be assigned to the left subtree. - * This method returns true if a point should be assigned to the left subtree, - * i.e., if the distance from the point to the vantage point is less then the - * median value. Otherwise it returns false. - * - * @param point The point that is being assigned. - * @param splitInfo An information about the split. - */ - template - static bool AssignToLeftNode(const VecType& point, - const SplitInfo& splitInfo) - { - return (splitInfo.metric->Evaluate(splitInfo.vantagePoint, point) < - splitInfo.mu); - } - - private: - /** - * Select the best vantage point, i.e., the point with the largest second - * moment of the distance from a number of random node points to the vantage - * point. Firstly this method selects no more than MaxNumSamples random - * points. Then it evaluates each point, i.e., calculates the corresponding - * second moment and selects the point with the largest moment. Each random - * point belongs to the node. - * - * @param metric The metric used by the tree. - * @param data The dataset used by the tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param vantagePoint The index of the vantage point in the dataset. - * @param mu The median value of distance form the vantage point to - * a number of random points. - */ - static void SelectVantagePoint(const MetricType& metric, - const MatType& data, - const size_t begin, - const size_t count, - size_t& vantagePoint, - ElemType& mu); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "vantage_point_split_impl.hpp" - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_VANTAGE_POINT_SPLIT_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/vantage_point_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/vantage_point_split_impl.hpp deleted file mode 100644 index b1714b7c7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/binary_space_tree/vantage_point_split_impl.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file vantage_point_split_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of class (VantagePointSplit) to split a vantage point - * tree according to the median value of the distance to a certain vantage point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BINARY_SPACE_TREE_VANTAGE_POINT_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_BINARY_SPACE_TREE_VANTAGE_POINT_SPLIT_IMPL_HPP - -#include "vantage_point_split.hpp" -#include - -namespace mlpack { -namespace tree { - -template -bool VantagePointSplit:: -SplitNode(const BoundType& bound, MatType& data, const size_t begin, - const size_t count, SplitInfo& splitInfo) -{ - ElemType mu = 0; - size_t vantagePointIndex = 0; - - // Find the best vantage point. - SelectVantagePoint(bound.Metric(), data, begin, count, vantagePointIndex, mu); - - // If all points are equal, we can't split. - if (mu == 0) - return false; - - splitInfo = SplitInfo(bound.Metric(), data.col(vantagePointIndex), mu); - - return true; -} - -template -void VantagePointSplit:: -SelectVantagePoint(const MetricType& metric, const MatType& data, - const size_t begin, const size_t count, size_t& vantagePoint, ElemType& mu) -{ - arma::uvec vantagePointCandidates; - arma::Col distances(MaxNumSamples); - - // Get no more than max(MaxNumSamples, count) vantage point candidates - math::ObtainDistinctSamples(begin, begin + count, MaxNumSamples, - vantagePointCandidates); - - ElemType bestSpread = 0; - - arma::uvec samples; - // Evaluate each candidate - for (size_t i = 0; i < vantagePointCandidates.n_elem; i++) - { - // Get no more than min(MaxNumSamples, count) random samples - math::ObtainDistinctSamples(begin, begin + count, MaxNumSamples, samples); - - // Calculate the second moment of the distance to the vantage point - // candidate using these random samples. - distances.set_size(samples.n_elem); - - for (size_t j = 0; j < samples.n_elem; j++) - distances[j] = metric.Evaluate(data.col(vantagePointCandidates[i]), - data.col(samples[j])); - - const ElemType spread = arma::sum(distances % distances) / samples.n_elem; - - if (spread > bestSpread) - { - bestSpread = spread; - vantagePoint = vantagePointCandidates[i]; - // Calculate the median value of the distance from the vantage point - // candidate to these samples. - mu = arma::median(distances); - } - } - assert(bestSpread > 0); -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_VANTAGE_POINT_SPLIT_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/bound_traits.hpp b/src/sdk/mlpack/include/mlpack/core/tree/bound_traits.hpp deleted file mode 100644 index dbc529903..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/bound_traits.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @file bound_traits.hpp - * @author Ryan Curtin - * - * A class for template metaprogramming traits for bounds. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_BOUND_TRAITS_HPP -#define MLPACK_CORE_TREE_BOUND_TRAITS_HPP - -namespace mlpack { -namespace bound { - -/** - * A class to obtain compile-time traits about BoundType classes. If you are - * writing your own BoundType class, you should make a template specialization - * in order to set the values correctly. - * - * @see TreeTraits, KernelTraits - */ -template -struct BoundTraits -{ - //! If true, then the bounds for each dimension are tight. If false, then the - //! bounds for each dimension may be looser than the range of all points held - //! in the bound. This defaults to false. - static const bool HasTightBounds = false; -}; - -} // namespace bound -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/bounds.hpp b/src/sdk/mlpack/include/mlpack/core/tree/bounds.hpp deleted file mode 100644 index d5a075693..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/bounds.hpp +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @file bounds.hpp - * - * Bounds that are useful for binary space partitioning trees. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_TREE_BOUNDS_HPP -#define MLPACK_CORE_TREE_BOUNDS_HPP - -#include -#include - -#include "bound_traits.hpp" -#include "hrectbound.hpp" -#include "ballbound.hpp" -#include "hollow_ball_bound.hpp" -#include "cellbound.hpp" - -#endif // MLPACK_CORE_TREE_BOUNDS_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cellbound.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cellbound.hpp deleted file mode 100644 index 2ffbb190a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cellbound.hpp +++ /dev/null @@ -1,316 +0,0 @@ -/** - * @file cellbound.hpp - * @author Mikhail Lozhnikov - * - * Definition of the CellBound class. The class describes a bound that consists - * of a number of hyperrectangles. These hyperrectangles do not overlap each - * other. The bound is limited by an outer hyperrectangle and two addresses, - * the lower address and the high address. Thus, the bound contains all points - * included between the lower and the high addresses. - * - * The notion of addresses is described in the following paper. - * @code - * @inproceedings{bayer1997, - * author = {Bayer, Rudolf}, - * title = {The Universal B-Tree for Multidimensional Indexing: General - * Concepts}, - * booktitle = {Proceedings of the International Conference on Worldwide - * Computing and Its Applications}, - * series = {WWCA '97}, - * year = {1997}, - * isbn = {3-540-63343-X}, - * pages = {198--209}, - * numpages = {12}, - * publisher = {Springer-Verlag}, - * address = {London, UK, UK}, - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_CELLBOUND_HPP -#define MLPACK_CORE_TREE_CELLBOUND_HPP - -#include -#include -#include -#include "bound_traits.hpp" -#include "address.hpp" - -namespace mlpack { -namespace bound { - -/** - * The CellBound class describes a bound that consists of a number of - * hyperrectangles. These hyperrectangles do not overlap each other. The bound - * is limited by an outer hyperrectangle and two addresses, the lower address - * and the high address. Thus, the bound contains all points included between - * the lower and the high addresses. The class caches the minimum bounding - * rectangle, the lower and the high addresses and the hyperrectangles - * that are described by the addresses. - * - * The notion of addresses is described in the following paper. - * @code - * @inproceedings{bayer1997, - * author = {Bayer, Rudolf}, - * title = {The Universal B-Tree for Multidimensional Indexing: General - * Concepts}, - * booktitle = {Proceedings of the International Conference on Worldwide - * Computing and Its Applications}, - * series = {WWCA '97}, - * year = {1997}, - * isbn = {3-540-63343-X}, - * pages = {198--209}, - * numpages = {12}, - * publisher = {Springer-Verlag}, - * address = {London, UK, UK}, - * } - * @endcode - */ -template, - typename ElemType = double> -class CellBound -{ - public: - //! Depending on the precision of the tree element type, we may need to use - //! uint32_t or uint64_t. - typedef typename std::conditional::type AddressElemType; - - /** - * Empty constructor; creates a bound of dimensionality 0. - */ - CellBound(); - - /** - * Initializes to specified dimensionality with each dimension the empty - * set. - */ - CellBound(const size_t dimension); - - //! Copy constructor; necessary to prevent memory leaks. - CellBound(const CellBound& other); - //! Same as copy constructor; necessary to prevent memory leaks. - CellBound& operator=(const CellBound& other); - - //! Move constructor: take possession of another bound's information. - CellBound(CellBound&& other); - - //! Destructor: clean up memory. - ~CellBound(); - - /** - * Resets all dimensions to the empty set (so that this bound contains - * nothing). - */ - void Clear(); - - //! Gets the dimensionality. - size_t Dim() const { return dim; } - - //! Get the range for a particular dimension. No bounds checking. Be - //! careful: this may make MinWidth() invalid. - math::RangeType& operator[](const size_t i) { return bounds[i]; } - //! Modify the range for a particular dimension. No bounds checking. - const math::RangeType& operator[](const size_t i) const - { return bounds[i]; } - - //! Get lower address. - arma::Col& LoAddress() { return loAddress; } - //! Modify lower address. - const arma::Col& LoAddress() const {return loAddress; } - - //! Get high address. - arma::Col& HiAddress() { return hiAddress; } - //! Modify high address. - const arma::Col& HiAddress() const {return hiAddress; } - - //! Get lower bound of each subrectangle. - const arma::Mat& LoBound() const { return loBound; } - //! Get high bound of each subrectangle. - const arma::Mat& HiBound() const { return hiBound; } - - //! Get the number of subrectangles. - size_t NumBounds() const { return numBounds; } - - //! Get the minimum width of the bound. - ElemType MinWidth() const { return minWidth; } - //! Modify the minimum width of the bound. - ElemType& MinWidth() { return minWidth; } - - /** - * Calculates the center of the range, placing it into the given vector. - * - * @param center Vector which the center will be written to. - */ - void Center(arma::Col& center) const; - - /** - * Calculates minimum bound-to-point distance. - * - * @param point Point to which the minimum distance is requested. - */ - template - ElemType MinDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const; - - /** - * Calculates minimum bound-to-bound distance. - * - * @param other Bound to which the minimum distance is requested. - */ - ElemType MinDistance(const CellBound& other) const; - - /** - * Calculates maximum bound-to-point squared distance. - * - * @param point Point to which the maximum distance is requested. - */ - template - ElemType MaxDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const; - - /** - * Computes maximum distance. - * - * @param other Bound to which the maximum distance is requested. - */ - ElemType MaxDistance(const CellBound& other) const; - - /** - * Calculates minimum and maximum bound-to-bound distance. - * - * @param other Bound to which the minimum and maximum distances are - * requested. - */ - math::RangeType RangeDistance(const CellBound& other) const; - - /** - * Calculates minimum and maximum bound-to-point distance. - * - * @param point Point to which the minimum and maximum distances are - * requested. - */ - template - math::RangeType RangeDistance( - const VecType& point, - typename std::enable_if_t::value>* = 0) const; - - /** - * Expands this region to include new points. - * - * @tparam MatType Type of matrix; could be Mat, SpMat, a subview, or just a - * vector. - * @param data Data points to expand this region to include. - */ - template - CellBound& operator|=(const MatType& data); - - /** - * Expands this region to encompass another bound. - */ - CellBound& operator|=(const CellBound& other); - - /** - * Determines if a point is within this bound. - */ - template - bool Contains(const VecType& point) const; - - /** - * Calculate the bounds of all subrectangles. You should set the lower and the - * high addresses. - * - * @param data Points that are contained in the node. - */ - template - void UpdateAddressBounds(const MatType& data); - - /** - * Returns the diameter of the hyperrectangle (that is, the longest diagonal). - */ - ElemType Diameter() const; - - /** - * Serialize the bound object. - */ - template - void serialize(Archive& ar, const unsigned int version); - - private: - //! The precision of the tree element type. - static constexpr size_t order = sizeof(AddressElemType) * CHAR_BIT; - //! Maximum number of subrectangles. - const size_t maxNumBounds = 10; - //! The dimensionality of the bound. - size_t dim; - //! The bounds for each dimension. - math::RangeType* bounds; - //! Lower bounds of subrectangles. - arma::Mat loBound; - //! High bounds of subrectangles. - arma::Mat hiBound; - //! The numbre of subrectangles. - size_t numBounds; - //! The lowest address that the bound may contain. - arma::Col loAddress; - //! The highest address that the bound may contain. - arma::Col hiAddress; - //! The minimal width of the outer rectangle. - ElemType minWidth; - - /** - * Add a subrectangle to the bound. - * - * @param loCorner The lower corner of the subrectangle that is being added. - * @param hiCorner The high corner of the subrectangle that is being added. - * @param data Points that are contained in the node. - */ - template - void AddBound(const arma::Col& loCorner, - const arma::Col& hiCorner, - const MatType& data); - /** - * Initialize all subrectangles that touches the lower address. This function - * should be called before InitLowerBound(). - * - * @param numEqualBits The number of equal leading bits of the lower address - * and the high address. - * @param data Points that are contained in the node. - */ - template - void InitHighBound(size_t numEqualBits, const MatType& data); - - /** - * Initialize all subrectangles that touches the high address. This function - * should be called after InitHighBound(). - * - * @param numEqualBits The number of equal leading bits of the lower address - * and the high address. - * @param data Points that are contained in the node. - */ - template - void InitLowerBound(size_t numEqualBits, const MatType& data); -}; - -// A specialization of BoundTraits for this class. -template -struct BoundTraits> -{ - //! These bounds are always tight for each dimension. - const static bool HasTightBounds = true; -}; - -} // namespace bound -} // namespace mlpack - -#include "cellbound_impl.hpp" - -#endif // MLPACK_CORE_TREE_CELLBOUND_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cellbound_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cellbound_impl.hpp deleted file mode 100644 index 872046c8b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cellbound_impl.hpp +++ /dev/null @@ -1,1002 +0,0 @@ -/** - * @file cellbound_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of the CellBound class. The class describes a bound that - * consists of a number of hyperrectangles. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_CELLBOUND_IMPL_HPP -#define MLPACK_CORE_TREE_CELLBOUND_IMPL_HPP - -#include - -// In case it has not been included yet. -#include "cellbound.hpp" - -namespace mlpack { -namespace bound { - -/** - * Empty constructor. - */ -template -inline CellBound::CellBound() : - dim(0), - bounds(NULL), - loBound(arma::Mat()), - hiBound(arma::Mat()), - numBounds(0), - loAddress(arma::Col()), - hiAddress(arma::Col()), - minWidth(0) -{ /* Nothing to do. */ } - -/** - * Initializes to specified dimensionality with each dimension the empty - * set. - */ -template -inline CellBound::CellBound(const size_t dimension) : - dim(dimension), - bounds(new math::RangeType[dim]), - loBound(arma::Mat(dim, maxNumBounds)), - hiBound(arma::Mat(dim, maxNumBounds)), - numBounds(0), - loAddress(dim), - hiAddress(dim), - minWidth(0) -{ - for (size_t k = 0; k < dim ; k++) - { - loAddress[k] = std::numeric_limits::max(); - hiAddress[k] = 0; - } -} - -/** - * Copy constructor necessary to prevent memory leaks. - */ -template -inline CellBound::CellBound( - const CellBound& other) : - dim(other.Dim()), - bounds(new math::RangeType[dim]), - loBound(other.loBound), - hiBound(other.hiBound), - numBounds(other.numBounds), - loAddress(other.loAddress), - hiAddress(other.hiAddress), - minWidth(other.MinWidth()) -{ - // Copy other bounds over. - for (size_t i = 0; i < dim; i++) - bounds[i] = other.bounds[i]; -} - -/** - * Same as the copy constructor. - */ -template -inline CellBound< - MetricType, - ElemType>& CellBound::operator=( - const CellBound& other) -{ - if (dim != other.Dim()) - { - // Reallocation is necessary. - - dim = other.Dim(); - bounds = new math::RangeType[dim]; - } - - loBound = other.loBound; - hiBound = other.hiBound; - numBounds = other.numBounds; - loAddress = other.loAddress; - hiAddress = other.hiAddress; - - // Now copy each of the bound values. - for (size_t i = 0; i < dim; i++) - bounds[i] = other.bounds[i]; - - minWidth = other.MinWidth(); - - return *this; -} - -/** - * Move constructor: take possession of another bound's information. - */ -template -inline CellBound::CellBound( - CellBound&& other) : - dim(other.dim), - bounds(other.bounds), - loBound(std::move(other.loBound)), - hiBound(std::move(other.hiBound)), - numBounds(std::move(other.numBounds)), - loAddress(std::move(other.loAddress)), - hiAddress(std::move(other.hiAddress)), - minWidth(other.minWidth) -{ - // Fix the other bound. - other.dim = 0; - other.bounds = NULL; - other.minWidth = 0.0; -} - -/** - * Destructor: clean up memory. - */ -template -inline CellBound::~CellBound() -{ - if (bounds) - delete[] bounds; -} - -/** - * Resets all dimensions to the empty set. - */ -template -inline void CellBound::Clear() -{ - for (size_t k = 0; k < dim; k++) - { - bounds[k] = math::RangeType(); - - loAddress[k] = std::numeric_limits::max(); - hiAddress[k] = 0; - } - - minWidth = 0; -} - -/*** - * Calculates the centroid of the range, placing it into the given vector. - * - * @param centroid Vector which the centroid will be written to. - */ -template -inline void CellBound::Center( - arma::Col& center) const -{ - // Set size correctly if necessary. - if (!(center.n_elem == dim)) - center.set_size(dim); - - for (size_t i = 0; i < dim; i++) - center(i) = bounds[i].Mid(); -} - -template -template -void CellBound::AddBound( - const arma::Col& loCorner, - const arma::Col& hiCorner, - const MatType& data) -{ - assert(numBounds < loBound.n_cols); - assert(loBound.n_rows == dim); - assert(loCorner.n_elem == dim); - assert(hiCorner.n_elem == dim); - - for (size_t k = 0; k < dim; k++) - { - loBound(k, numBounds) = std::numeric_limits::max(); - hiBound(k, numBounds) = std::numeric_limits::lowest(); - } - - for (size_t i = 0; i < data.n_cols; i++) - { - size_t k = 0; - // Check if the point is contained in the hyperrectangle. - for (k = 0; k < dim; k++) - if (data(k, i) < loCorner[k] || data(k, i) > hiCorner[k]) - break; - - if (k < dim) - continue; // The point is not contained in the hyperrectangle. - - // Shrink the bound. - for (k = 0; k < dim; k++) - { - loBound(k, numBounds) = std::min(loBound(k, numBounds), data(k, i)); - hiBound(k, numBounds) = std::max(hiBound(k, numBounds), data(k, i)); - } - } - - for (size_t k = 0; k < dim; k++) - if (loBound(k, numBounds) > hiBound(k, numBounds)) - return; // The hyperrectangle does not contain points. - - numBounds++; -} - - -template -template -void CellBound::InitHighBound(size_t numEqualBits, - const MatType& data) -{ - arma::Col tmpHiAddress(hiAddress); - arma::Col tmpLoAddress(hiAddress); - arma::Col loCorner(tmpHiAddress.n_elem); - arma::Col hiCorner(tmpHiAddress.n_elem); - - assert(tmpHiAddress.n_elem > 0); - - // We have to calculate the number of subrectangles since the maximum number - // of hyperrectangles is restricted. - size_t numCorners = 0; - for (size_t pos = numEqualBits + 1; pos < order * tmpHiAddress.n_elem; pos++) - { - size_t row = pos / order; - size_t bit = order - 1 - pos % order; - - // This hyperrectangle is not contained entirely in the bound. - // So, the number of hyperrectangles should be increased. - if (tmpHiAddress[row] & ((AddressElemType) 1 << bit)) - numCorners++; - - // We ran out of the limit of hyperrectangles. In that case we enlare - // the last hyperrectangle. - if (numCorners >= maxNumBounds / 2) - tmpHiAddress[row] |= ((AddressElemType) 1 << bit); - } - - size_t pos = order * tmpHiAddress.n_elem - 1; - - // Find the last hyperrectangle and add it to the bound. - for ( ; pos > numEqualBits; pos--) - { - size_t row = pos / order; - size_t bit = order - 1 - pos % order; - - // All last bits after pos of tmpHiAddress are equal to 1 and - // All last bits of tmpLoAddress (after pos) are equal to 0. - // Thus, tmpHiAddress corresponds to the high corner of the enlarged - // rectangle and tmpLoAddress corresponds to the lower corner. - if (!(tmpHiAddress[row] & ((AddressElemType) 1 << bit))) - { - addr::AddressToPoint(loCorner, tmpLoAddress); - addr::AddressToPoint(hiCorner, tmpHiAddress); - - AddBound(loCorner, hiCorner, data); - break; - } - // Nullify the bit that corresponds to this step. - tmpLoAddress[row] &= ~((AddressElemType) 1 << bit); - } - - // Add the enlarged rectangle if we have not done that. - if (pos == numEqualBits) - { - addr::AddressToPoint(loCorner, tmpLoAddress); - addr::AddressToPoint(hiCorner, tmpHiAddress); - - AddBound(loCorner, hiCorner, data); - } - - for ( ; pos > numEqualBits; pos--) - { - size_t row = pos / order; - size_t bit = order - 1 - pos % order; - - // The lower bound should correspond to this step. - tmpLoAddress[row] &= ~((AddressElemType) 1 << bit); - - if (tmpHiAddress[row] & ((AddressElemType) 1 << bit)) - { - // This hyperrectangle is contained entirely in the bound and do not - // overlap with other hyperrectangles since loAddress is less than - // tmpLoAddress and tmpHiAddress is less that the lower addresses - // of hyperrectangles that we have added previously. - tmpHiAddress[row] ^= (AddressElemType) 1 << bit; - addr::AddressToPoint(loCorner, tmpLoAddress); - addr::AddressToPoint(hiCorner, tmpHiAddress); - - AddBound(loCorner, hiCorner, data); - } - // The high bound should correspond to this step. - tmpHiAddress[row] |= ((AddressElemType) 1 << bit); - } -} - -template -template -void CellBound::InitLowerBound(size_t numEqualBits, - const MatType& data) -{ - arma::Col tmpHiAddress(loAddress); - arma::Col tmpLoAddress(loAddress); - arma::Col loCorner(tmpHiAddress.n_elem); - arma::Col hiCorner(tmpHiAddress.n_elem); - - // We have to calculate the number of subrectangles since the maximum number - // of hyperrectangles is restricted. - size_t numCorners = 0; - for (size_t pos = numEqualBits + 1; pos < order * tmpHiAddress.n_elem; pos++) - { - size_t row = pos / order; - size_t bit = order - 1 - pos % order; - - // This hyperrectangle is not contained entirely in the bound. - // So, the number of hyperrectangles should be increased. - if (!(tmpLoAddress[row] & ((AddressElemType) 1 << bit))) - numCorners++; - - // We ran out of the limit of hyperrectangles. In that case we enlare - // the last hyperrectangle. - if (numCorners >= maxNumBounds - numBounds) - tmpLoAddress[row] &= ~((AddressElemType) 1 << bit); - } - - size_t pos = order * tmpHiAddress.n_elem - 1; - - // Find the last hyperrectangle and add it to the bound. - for ( ; pos > numEqualBits; pos--) - { - size_t row = pos / order; - size_t bit = order - 1 - pos % order; - - // All last bits after pos of tmpHiAddress are equal to 1 and - // All last bits of tmpLoAddress (after pos) are equal to 0. - // Thus, tmpHiAddress corresponds to the high corner of the enlarged - // rectangle and tmpLoAddress corresponds to the lower corner. - if (tmpLoAddress[row] & ((AddressElemType) 1 << bit)) - { - addr::AddressToPoint(loCorner, tmpLoAddress); - addr::AddressToPoint(hiCorner, tmpHiAddress); - - AddBound(loCorner, hiCorner, data); - break; - } - // Enlarge the hyperrectangle at this step since it is contained - // entirely in the bound. - tmpHiAddress[row] |= ((AddressElemType) 1 << bit); - } - - // Add the enlarged rectangle if we have not done that. - if (pos == numEqualBits) - { - addr::AddressToPoint(loCorner, tmpLoAddress); - addr::AddressToPoint(hiCorner, tmpHiAddress); - - AddBound(loCorner, hiCorner, data); - } - - for ( ; pos > numEqualBits; pos--) - { - size_t row = pos / order; - size_t bit = order - 1 - pos % order; - - // The high bound should correspond to this step. - tmpHiAddress[row] |= ((AddressElemType) 1 << bit); - - if (!(tmpLoAddress[row] & ((AddressElemType) 1 << bit))) - { - // This hyperrectangle is contained entirely in the bound and do not - // overlap with other hyperrectangles since hiAddress is greater than - // tmpHiAddress and tmpLoAddress is greater that the high addresses - // of hyperrectangles that we have added previously. - tmpLoAddress[row] ^= (AddressElemType) 1 << bit; - - addr::AddressToPoint(loCorner, tmpLoAddress); - addr::AddressToPoint(hiCorner, tmpHiAddress); - - AddBound(loCorner, hiCorner, data); - } - - // The lower bound should correspond to this step. - tmpLoAddress[row] &= ~((AddressElemType) 1 << bit); - } -} - -template -template -void CellBound::UpdateAddressBounds(const MatType& data) -{ - numBounds = 0; - - // Calculate the number of equal leading bits of the lower address and - // the high address. - size_t row = 0; - for ( ; row < hiAddress.n_elem; row++) - if (loAddress[row] != hiAddress[row]) - break; - - // If the high address is equal to the lower address. - if (row == hiAddress.n_elem) - { - for (size_t i = 0; i < dim; i++) - { - loBound(i, 0) = bounds[i].Lo(); - hiBound(i, 0) = bounds[i].Hi(); - } - numBounds = 1; - - return; - } - - size_t bit = 0; - for ( ; bit < order; bit++) - if ((loAddress[row] & ((AddressElemType) 1 << (order - 1 - bit))) != - (hiAddress[row] & ((AddressElemType) 1 << (order - 1 - bit)))) - break; - - if ((row == hiAddress.n_elem - 1) && (bit == order - 1)) - { - // If the addresses differ in the last bit. - for (size_t i = 0; i < dim; i++) - { - loBound(i, 0) = bounds[i].Lo(); - hiBound(i, 0) = bounds[i].Hi(); - } - - numBounds = 1; - - return; - } - - size_t numEqualBits = row * order + bit; - InitHighBound(numEqualBits, data); - InitLowerBound(numEqualBits, data); - - assert(numBounds <= maxNumBounds); - - if (numBounds == 0) - { - // I think this should never happen. - for (size_t i = 0; i < dim; i++) - { - loBound(i, 0) = bounds[i].Lo(); - hiBound(i, 0) = bounds[i].Hi(); - } - - numBounds = 1; - } -} - -/** - * Calculates minimum bound-to-point squared distance. - */ -template -template -inline ElemType CellBound::MinDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - Log::Assert(point.n_elem == dim); - - ElemType minSum = std::numeric_limits::max(); - - ElemType lower, higher; - - for (size_t i = 0; i < numBounds; i++) - { - ElemType sum = 0; - - for (size_t d = 0; d < dim; d++) - { - lower = loBound(d, i) - point[d]; - higher = point[d] - hiBound(d, i); - - // Since only one of 'lower' or 'higher' is negative, if we add - // each's absolute value to itself and then sum those two, our - // result is the non negative half of the equation times two; - // then we raise to power Power. - if (MetricType::Power == 1) - sum += lower + std::fabs(lower) + higher + std::fabs(higher); - else if (MetricType::Power == 2) - { - ElemType dist = lower + std::fabs(lower) + higher + std::fabs(higher); - sum += dist * dist; - } - else - { - sum += pow((lower + fabs(lower)) + (higher + fabs(higher)), - (ElemType) MetricType::Power); - } - - if (sum >= minSum) - break; - } - - if (sum < minSum) - minSum = sum; - } - - // Now take the Power'th root (but make sure our result is squared if it needs - // to be); then cancel out the constant of 2 (which may have been squared now) - // that was introduced earlier. The compiler should optimize out the if - // statement entirely. - if (MetricType::Power == 1) - return minSum * 0.5; - else if (MetricType::Power == 2) - { - if (MetricType::TakeRoot) - return (ElemType) std::sqrt(minSum) * 0.5; - else - return minSum * 0.25; - } - else - { - if (MetricType::TakeRoot) - return (ElemType) pow((double) minSum, - 1.0 / (double) MetricType::Power) / 2.0; - else - return minSum / pow(2.0, MetricType::Power); - } -} - -/** - * Calculates minimum bound-to-bound squared distance. - */ -template -ElemType CellBound::MinDistance(const CellBound& other) - const -{ - Log::Assert(dim == other.dim); - - ElemType minSum = std::numeric_limits::max(); - - ElemType lower, higher; - - for (size_t i = 0; i < numBounds; i++) - for (size_t j = 0; j < other.numBounds; j++) - { - ElemType sum = 0; - for (size_t d = 0; d < dim; d++) - { - lower = other.loBound(d, j) - hiBound(d, i); - higher = loBound(d, i) - other.hiBound(d, j); - // We invoke the following: - // x + fabs(x) = max(x * 2, 0) - // (x * 2)^2 / 4 = x^2 - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - sum += (lower + std::fabs(lower)) + (higher + std::fabs(higher)); - else if (MetricType::Power == 2) - { - ElemType dist = lower + std::fabs(lower) + higher + std::fabs(higher); - sum += dist * dist; - } - else - { - sum += pow((lower + fabs(lower)) + (higher + fabs(higher)), - (ElemType) MetricType::Power); - } - - if (sum >= minSum) - break; - } - - if (sum < minSum) - minSum = sum; - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - return minSum * 0.5; - else if (MetricType::Power == 2) - { - if (MetricType::TakeRoot) - return (ElemType) std::sqrt(minSum) * 0.5; - else - return minSum * 0.25; - } - else - { - if (MetricType::TakeRoot) - return (ElemType) pow((double) minSum, - 1.0 / (double) MetricType::Power) / 2.0; - else - return minSum / pow(2.0, MetricType::Power); - } -} - -/** - * Calculates maximum bound-to-point squared distance. - */ -template -template -inline ElemType CellBound::MaxDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - ElemType maxSum = std::numeric_limits::lowest(); - - Log::Assert(point.n_elem == dim); - - for (size_t i = 0; i < numBounds; i++) - { - ElemType sum = 0; - for (size_t d = 0; d < dim; d++) - { - ElemType v = std::max(fabs(point[d] - loBound(d, i)), - fabs(hiBound(d, i) - point[d])); - - if (MetricType::Power == 1) - sum += v; // v is non-negative. - else if (MetricType::Power == 2) - sum += v * v; - else - sum += std::pow(v, (ElemType) MetricType::Power); - } - - if (sum > maxSum) - maxSum = sum; - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::TakeRoot) - { - if (MetricType::Power == 1) - return maxSum; - else if (MetricType::Power == 2) - return (ElemType) std::sqrt(maxSum); - else - return (ElemType) pow((double) maxSum, 1.0 / (double) MetricType::Power); - } - else - return maxSum; -} - -/** - * Computes maximum distance. - */ -template -inline ElemType CellBound::MaxDistance( - const CellBound& other) - const -{ - ElemType maxSum = std::numeric_limits::lowest(); - - Log::Assert(dim == other.dim); - - ElemType v; - for (size_t i = 0; i < numBounds; i++) - for (size_t j = 0; j < other.numBounds; j++) - { - ElemType sum = 0; - for (size_t d = 0; d < dim; d++) - { - v = std::max(fabs(other.hiBound(d, j) - loBound(d, i)), - fabs(hiBound(d, i) - other.loBound(d, j))); - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - sum += v; // v is non-negative. - else if (MetricType::Power == 2) - sum += v * v; - else - sum += std::pow(v, (ElemType) MetricType::Power); - } - - if (sum > maxSum) - maxSum = sum; - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::TakeRoot) - { - if (MetricType::Power == 1) - return maxSum; - else if (MetricType::Power == 2) - return (ElemType) std::sqrt(maxSum); - else - return (ElemType) pow((double) maxSum, 1.0 / (double) MetricType::Power); - } - else - return maxSum; -} - -/** - * Calculates minimum and maximum bound-to-bound squared distance. - */ -template -inline math::RangeType -CellBound::RangeDistance( - const CellBound& other) const -{ - ElemType minLoSum = std::numeric_limits::max(); - ElemType maxHiSum = std::numeric_limits::lowest(); - - Log::Assert(dim == other.dim); - - ElemType v1, v2, vLo, vHi; - - for (size_t i = 0; i < numBounds; i++) - for (size_t j = 0; j < other.numBounds; j++) - { - ElemType loSum = 0; - ElemType hiSum = 0; - for (size_t d = 0; d < dim; d++) - { - v1 = other.loBound(d, j) - hiBound(d, i); - v2 = loBound(d, i) - other.hiBound(d, j); - // One of v1 or v2 is negative. - if (v1 >= v2) - { - vHi = -v2; // Make it nonnegative. - vLo = (v1 > 0) ? v1 : 0; // Force to be 0 if negative. - } - else - { - vHi = -v1; // Make it nonnegative. - vLo = (v2 > 0) ? v2 : 0; // Force to be 0 if negative. - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - { - loSum += vLo; // vLo is non-negative. - hiSum += vHi; // vHi is non-negative. - } - else if (MetricType::Power == 2) - { - loSum += vLo * vLo; - hiSum += vHi * vHi; - } - else - { - loSum += std::pow(vLo, (ElemType) MetricType::Power); - hiSum += std::pow(vHi, (ElemType) MetricType::Power); - } - } - - if (loSum < minLoSum) - minLoSum = loSum; - if (hiSum > maxHiSum) - maxHiSum = hiSum; - } - - if (MetricType::TakeRoot) - { - if (MetricType::Power == 1) - return math::RangeType(minLoSum, maxHiSum); - else if (MetricType::Power == 2) - return math::RangeType((ElemType) std::sqrt(minLoSum), - (ElemType) std::sqrt(maxHiSum)); - else - { - return math::RangeType( - (ElemType) pow((double) minLoSum, 1.0 / (double) MetricType::Power), - (ElemType) pow((double) maxHiSum, 1.0 / (double) MetricType::Power)); - } - } - else - return math::RangeType(minLoSum, maxHiSum); -} - -/** - * Calculates minimum and maximum bound-to-point squared distance. - */ -template -template -inline math::RangeType -CellBound::RangeDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - ElemType minLoSum = std::numeric_limits::max(); - ElemType maxHiSum = std::numeric_limits::lowest(); - - Log::Assert(point.n_elem == dim); - - ElemType v1, v2, vLo, vHi; - for (size_t i = 0; i < numBounds; i++) - { - ElemType loSum = 0; - ElemType hiSum = 0; - for (size_t d = 0; d < dim; d++) - { - v1 = loBound(d, i) - point[d]; // Negative if point[d] > lo. - v2 = point[d] - hiBound(d, i); // Negative if point[d] < hi. - // One of v1 or v2 (or both) is negative. - if (v1 >= 0) // point[d] <= bounds_[d].Lo(). - { - vHi = -v2; // v2 will be larger but must be negated. - vLo = v1; - } - else // point[d] is between lo and hi, or greater than hi. - { - if (v2 >= 0) - { - vHi = -v1; // v1 will be larger, but must be negated. - vLo = v2; - } - else - { - vHi = -std::min(v1, v2); // Both are negative, but we need the larger. - vLo = 0; - } - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - { - loSum += vLo; // vLo is non-negative. - hiSum += vHi; // vHi is non-negative. - } - else if (MetricType::Power == 2) - { - loSum += vLo * vLo; - hiSum += vHi * vHi; - } - else - { - loSum += std::pow(vLo, (ElemType) MetricType::Power); - hiSum += std::pow(vHi, (ElemType) MetricType::Power); - } - } - if (loSum < minLoSum) - minLoSum = loSum; - if (hiSum > maxHiSum) - maxHiSum = hiSum; - } - - if (MetricType::TakeRoot) - { - if (MetricType::Power == 1) - return math::RangeType(minLoSum, maxHiSum); - else if (MetricType::Power == 2) - return math::RangeType((ElemType) std::sqrt(minLoSum), - (ElemType) std::sqrt(maxHiSum)); - else - { - return math::RangeType( - (ElemType) pow((double) minLoSum, 1.0 / (double) MetricType::Power), - (ElemType) pow((double) maxHiSum, 1.0 / (double) MetricType::Power)); - } - } - else - return math::RangeType(minLoSum, maxHiSum); -} - -/** - * Expands this region to include a new point. - */ -template -template -inline CellBound& -CellBound::operator|=(const MatType& data) -{ - Log::Assert(data.n_rows == dim); - - arma::Col mins(arma::min(data, 1)); - arma::Col maxs(arma::max(data, 1)); - - minWidth = std::numeric_limits::max(); - for (size_t i = 0; i < dim; i++) - { - bounds[i] |= math::RangeType(mins[i], maxs[i]); - const ElemType width = bounds[i].Width(); - if (width < minWidth) - minWidth = width; - - loBound(i, 0) = bounds[i].Lo(); - hiBound(i, 0) = bounds[i].Hi(); - } - - numBounds = 1; - - return *this; -} - -/** - * Expands this region to encompass another bound. - */ -template -inline CellBound& -CellBound::operator|=(const CellBound& other) -{ - assert(other.dim == dim); - - minWidth = std::numeric_limits::max(); - for (size_t i = 0; i < dim; i++) - { - bounds[i] |= other.bounds[i]; - const ElemType width = bounds[i].Width(); - if (width < minWidth) - minWidth = width; - } - - if (addr::CompareAddresses(other.loAddress, loAddress) < 0) - loAddress = other.loAddress; - - if (addr::CompareAddresses(other.hiAddress, hiAddress) > 0) - hiAddress = other.hiAddress; - - if (loAddress[0] > hiAddress[0]) - { - for (size_t i = 0; i < dim; i++) - { - loBound(i, 0) = bounds[i].Lo(); - hiBound(i, 0) = bounds[i].Hi(); - } - numBounds = 1; - } - return *this; -} - -/** - * Determines if a point is within this bound. - */ -template -template -inline bool CellBound::Contains( - const VecType& point) const -{ - for (size_t i = 0; i < point.n_elem; i++) - { - if (!bounds[i].Contains(point(i))) - return false; - } - - if (loAddress[0] > hiAddress[0]) - return true; - - arma::Col address(dim); - - addr::PointToAddress(address, point); - - return addr::Contains(address, loAddress, hiAddress); -} - - -/** - * Returns the diameter of the hyperrectangle (that is, the longest diagonal). - */ -template -inline ElemType CellBound::Diameter() const -{ - ElemType d = 0; - for (size_t i = 0; i < dim; ++i) - d += std::pow(bounds[i].Hi() - bounds[i].Lo(), - (ElemType) MetricType::Power); - - if (MetricType::TakeRoot) - return (ElemType) std::pow((double) d, 1.0 / (double) MetricType::Power); - else - return d; -} - -//! Serialize the bound object. -template -template -void CellBound::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // Allocate memory for the bounds, if necessary. - if (Archive::is_loading::value) - { - if (bounds) - delete[] bounds; - bounds = new math::RangeType[dim]; - } - - auto boundsArray = boost::serialization::make_array(bounds, dim); - ar & BOOST_SERIALIZATION_NVP(boundsArray); - ar & BOOST_SERIALIZATION_NVP(minWidth); - ar & BOOST_SERIALIZATION_NVP(loBound); - ar & BOOST_SERIALIZATION_NVP(hiBound); - ar & BOOST_SERIALIZATION_NVP(numBounds); - ar & BOOST_SERIALIZATION_NVP(loAddress); - ar & BOOST_SERIALIZATION_NVP(hiAddress); -} - -} // namespace bound -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cosine_tree/cosine_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cosine_tree/cosine_tree.hpp deleted file mode 100644 index a94562afb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cosine_tree/cosine_tree.hpp +++ /dev/null @@ -1,259 +0,0 @@ -/** - * @file cosine_tree.hpp - * @author Siddharth Agrawal - * - * Definition of Cosine Tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COSINE_TREE_COSINE_TREE_HPP -#define MLPACK_CORE_TREE_COSINE_TREE_COSINE_TREE_HPP - -#include -#include - -namespace mlpack { -namespace tree { - -// Predeclare classes for CosineNodeQueue typedef. -class CompareCosineNode; -class CosineTree; - -// CosineNodeQueue typedef. -typedef boost::heap::priority_queue > CosineNodeQueue; - -class CosineTree -{ - public: - /** - * CosineTree constructor for the root node of the tree. It initializes the - * necessary variables required for splitting of the node, and building the - * tree further. It takes a pointer to the input matrix and calculates the - * relevant variables using it. - * - * @param dataset Matrix for which cosine tree is constructed. - */ - CosineTree(const arma::mat& dataset); - - /** - * CosineTree constructor for nodes other than the root node of the tree. It - * takes in a pointer to the parent node and a list of column indices which - * mentions the columns to be included in the node. The function calculate the - * relevant variables just like the constructor above. - * - * @param parentNode Pointer to the parent cosine node. - * @param subIndices Pointer to vector of column indices to be included. - */ - CosineTree(CosineTree& parentNode, const std::vector& subIndices); - - /** - * Construct the CosineTree and the basis for the given matrix, and passed - * 'epsilon' and 'delta' parameters. The CosineTree is constructed by - * splitting nodes in the direction of maximum error, stored using a priority - * queue. Basis vectors are added from the left and right children of the - * split node. The basis vector from a node is the orthonormalized centroid of - * its columns. The splitting continues till the Monte Carlo estimate of the - * input matrix's projection on the obtained subspace is less than a fraction - * of the norm of the input matrix. - * - * @param dataset Matrix for which the CosineTree is constructed. - * @param epsilon Error tolerance fraction for calculated subspace. - * @param delta Cumulative probability for Monte Carlo error lower bound. - */ - CosineTree(const arma::mat& dataset, - const double epsilon, - const double delta); - - /** - * Clean up the CosineTree: release allocated memory (including children). - */ - ~CosineTree(); - - /** - * Calculates the orthonormalization of the passed centroid, with respect to - * the current vector subspace. - * - * @param treeQueue Priority queue of cosine nodes. - * @param centroid Centroid of the node being added to the basis. - * @param newBasisVector Orthonormalized centroid of the node. - * @param addBasisVector Address to additional basis vector. - */ - void ModifiedGramSchmidt(CosineNodeQueue& treeQueue, - arma::vec& centroid, - arma::vec& newBasisVector, - arma::vec* addBasisVector = NULL); - - /** - * Estimates the squared error of the projection of the input node's matrix - * onto the current vector subspace. A normal distribution is fit using - * weighted norms of projections of samples drawn from the input node's matrix - * columns. The error is calculated as the difference between the Frobenius - * norm of the input node's matrix and lower bound of the normal distribution. - * - * @param node Node for which Monte Carlo estimate is calculated. - * @param treeQueue Priority queue of cosine nodes. - * @param addBasisVector1 Address to first additional basis vector. - * @param addBasisVector2 Address to second additional basis vector. - */ - double MonteCarloError(CosineTree* node, - CosineNodeQueue& treeQueue, - arma::vec* addBasisVector1 = NULL, - arma::vec* addBasisVector2 = NULL); - - /** - * Constructs the final basis matrix, after the cosine tree construction. - * - * @param treeQueue Priority queue of cosine nodes. - */ - void ConstructBasis(CosineNodeQueue& treeQueue); - - /** - * This function splits the cosine node into two children based on the cosines - * of the columns contained in the node, with respect to the sampled splitting - * point. The function also calls the CosineTree constructor for the children. - */ - void CosineNodeSplit(); - - /** - * Sample 'numSamples' points from the Length-Squared distribution of the - * cosine node. The function uses 'l2NormsSquared' to calculate the cumulative - * probability distribution of the column vectors. The sampling is based on a - * randomly generated values in the range [0, 1]. - */ - void ColumnSamplesLS(std::vector& sampledIndices, - arma::vec& probabilities, size_t numSamples); - - /** - * Sample a point from the Length-Squared distribution of the cosine node. The - * function uses 'l2NormsSquared' to calculate the cumulative probability - * distribution of the column vectors. The sampling is based on a randomly - * generated value in the range [0, 1]. - */ - size_t ColumnSampleLS(); - - /** - * Sample a column based on the cumulative Length-Squared distribution of the - * cosine node, and a randomly generated value in the range [0, 1]. Binary - * search is more efficient than searching linearly for the same. This leads - * a significant speedup when there are large number of columns to choose from - * and when a number of samples are to be drawn from the distribution. - * - * @param cDistribution Cumulative LS distribution of columns in the node. - * @param value Randomly generated value in the range [0, 1]. - * @param start Starting index of the distribution interval to search in. - * @param end Ending index of the distribution interval to search in. - */ - size_t BinarySearch(arma::vec& cDistribution, double value, size_t start, - size_t end); - - /** - * Calculate cosines of the columns present in the node, with respect to the - * sampled splitting point. The calculated cosine values are useful for - * splitting the node into its children. - * - * @param cosines Vector to store the cosine values in. - */ - void CalculateCosines(arma::vec& cosines); - - /** - * Calculate centroid of the columns present in the node. The calculated - * centroid is used as a basis vector for the cosine tree being constructed. - */ - void CalculateCentroid(); - - //! Returns the basis of the constructed subspace. - void GetFinalBasis(arma::mat& finalBasis) { finalBasis = basis; } - - //! Get pointer to the dataset matrix. - const arma::mat& GetDataset() const { return dataset; } - - //! Get the indices of columns in the node. - std::vector& VectorIndices() { return indices; } - - //! Set the Monte Carlo error. - void L2Error(const double error) { this->l2Error = error; } - //! Get the Monte Carlo error. - double L2Error() const { return l2Error; } - - //! Get pointer to the centroid vector. - arma::vec& Centroid() { return centroid; } - - //! Set the basis vector of the node. - void BasisVector(arma::vec& bVector) { this->basisVector = bVector; } - - //! Get the basis vector of the node. - arma::vec& BasisVector() { return basisVector; } - - //! Get pointer to the parent node. - CosineTree* Parent() const { return parent; } - //! Modify the pointer to the parent node. - CosineTree*& Parent() { return parent; } - - //! Get pointer to the left child of the node. - CosineTree* Left() const { return left; } - //! Modify the pointer to the left child of the node. - CosineTree*& Left() { return left; } - - //! Get pointer to the right child of the node. - CosineTree* Right() const { return right; } - //! Modify the pointer to the left child of the node. - CosineTree*& Right() { return right; } - - //! Get number of columns of input matrix in the node. - size_t NumColumns() const { return numColumns; } - - //! Get the Frobenius norm squared of columns in the node. - double FrobNormSquared() const { return frobNormSquared; } - - //! Get the column index of split point of the node. - size_t SplitPointIndex() const { return indices[splitPointIndex]; } - - private: - //! Matrix for which cosine tree is constructed. - const arma::mat& dataset; - //! Cumulative probability for Monte Carlo error lower bound. - double delta; - //! Subspace basis of the input dataset. - arma::mat basis; - //! Parent of the node. - CosineTree* parent; - //! Left child of the node. - CosineTree* left; - //! Right child of the node. - CosineTree* right; - //! Indices of columns of input matrix in the node. - std::vector indices; - //! L2-norm squared of columns in the node. - arma::vec l2NormsSquared; - //! Centroid of columns of input matrix in the node. - arma::vec centroid; - //! Orthonormalized basis vector of the node. - arma::vec basisVector; - //! Index of split point of cosine node. - size_t splitPointIndex; - //! Number of columns of input matrix in the node. - size_t numColumns; - //! Monte Carlo error for this node. - double l2Error; - //! Frobenius norm squared of columns in the node. - double frobNormSquared; -}; - -class CompareCosineNode -{ - public: - // Comparison function for construction of priority queue. - bool operator() (const CosineTree* a, const CosineTree* b) const - { - return a->L2Error() < b->L2Error(); - } -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree.hpp deleted file mode 100644 index dcb886270..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree.hpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @file cover_tree.hpp - * @author Ryan Curtin - * - * Includes all the necessary files to use the CoverTree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_HPP -#define MLPACK_CORE_TREE_COVER_TREE_HPP - -#include -#include "cover_tree/first_point_is_root.hpp" -#include "cover_tree/cover_tree.hpp" -#include "cover_tree/single_tree_traverser.hpp" -#include "cover_tree/single_tree_traverser_impl.hpp" -#include "cover_tree/dual_tree_traverser.hpp" -#include "cover_tree/dual_tree_traverser_impl.hpp" -#include "cover_tree/traits.hpp" -#include "cover_tree/typedef.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/cover_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/cover_tree.hpp deleted file mode 100644 index d339220d6..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/cover_tree.hpp +++ /dev/null @@ -1,571 +0,0 @@ -/** - * @file cover_tree.hpp - * @author Ryan Curtin - * - * Definition of CoverTree, which can be used in place of the BinarySpaceTree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_COVER_TREE_HPP -#define MLPACK_CORE_TREE_COVER_TREE_COVER_TREE_HPP - -#include -#include - -#include "../statistic.hpp" -#include "first_point_is_root.hpp" - -namespace mlpack { -namespace tree { - -/** - * A cover tree is a tree specifically designed to speed up nearest-neighbor - * computation in high-dimensional spaces. Each non-leaf node references a - * point and has a nonzero number of children, including a "self-child" which - * references the same point. A leaf node represents only one point. - * - * The tree can be thought of as a hierarchy with the root node at the top level - * and the leaf nodes at the bottom level. Each level in the tree has an - * assigned 'scale' i. The tree follows these two invariants: - * - * - nesting: the level C_i is a subset of the level C_{i - 1}. - * - covering: all node in level C_{i - 1} have at least one node in the - * level C_i with distance less than or equal to b^i (exactly one of these - * is a parent of the point in level C_{i - 1}. - * - * Note that in the cover tree paper, there is a third invariant (the - * 'separation invariant'), but that does not apply to our implementation, - * because we have relaxed the invariant. - * - * The value 'b' refers to the base, which is a parameter of the tree. These - * three properties make the cover tree very good for fast, high-dimensional - * nearest-neighbor search. - * - * The theoretical structure of the tree contains many 'implicit' nodes which - * only have a "self-child" (a child referencing the same point, but at a lower - * scale level). This practical implementation only constructs explicit nodes - * -- non-leaf nodes with more than one child. A leaf node has no children, and - * its scale level is INT_MIN. - * - * For more information on cover trees, see - * - * @code - * @inproceedings{ - * author = {Beygelzimer, Alina and Kakade, Sham and Langford, John}, - * title = {Cover trees for nearest neighbor}, - * booktitle = {Proceedings of the 23rd International Conference on Machine - * Learning}, - * series = {ICML '06}, - * year = {2006}, - * pages = {97--104] - * } - * @endcode - * - * For information on runtime bounds of the nearest-neighbor computation using - * cover trees, see the following paper, presented at NIPS 2009: - * - * @code - * @inproceedings{ - * author = {Ram, P., and Lee, D., and March, W.B., and Gray, A.G.}, - * title = {Linear-time Algorithms for Pairwise Statistical Problems}, - * booktitle = {Advances in Neural Information Processing Systems 22}, - * editor = {Y. Bengio and D. Schuurmans and J. Lafferty and C.K.I. Williams - * and A. Culotta}, - * pages = {1527--1535}, - * year = {2009} - * } - * @endcode - * - * The CoverTree class offers three template parameters; a custom metric type - * can be used with MetricType (this class defaults to the L2-squared metric). - * The root node's point can be chosen with the RootPointPolicy; by default, the - * FirstPointIsRoot policy is used, meaning the first point in the dataset is - * used. The StatisticType policy allows you to define statistics which can be - * gathered during the creation of the tree. - * - * @tparam MetricType Metric type to use during tree construction. - * @tparam RootPointPolicy Determines which point to use as the root node. - * @tparam StatisticType Statistic to be used during tree creation. - * @tparam MatType Type of matrix to build the tree on (generally mat or - * sp_mat). - */ -template, - typename StatisticType = EmptyStatistic, - typename MatType = arma::mat, - typename RootPointPolicy = FirstPointIsRoot> -class CoverTree -{ - public: - //! So that other classes can access the matrix type. - typedef MatType Mat; - //! The type held by the matrix type. - typedef typename MatType::elem_type ElemType; - - /** - * Create the cover tree with the given dataset and given base. - * The dataset will not be modified during the building procedure (unlike - * BinarySpaceTree). - * - * The last argument will be removed in mlpack 1.1.0 (see #274 and #273). - * - * @param dataset Reference to the dataset to build a tree on. - * @param base Base to use during tree building (default 2.0). - */ - CoverTree(const MatType& dataset, - const ElemType base = 2.0, - MetricType* metric = NULL); - - /** - * Create the cover tree with the given dataset and the given instantiated - * metric. Optionally, set the base. The dataset will not be modified during - * the building procedure (unlike BinarySpaceTree). - * - * @param dataset Reference to the dataset to build a tree on. - * @param metric Instantiated metric to use during tree building. - * @param base Base to use during tree building (default 2.0). - */ - CoverTree(const MatType& dataset, - MetricType& metric, - const ElemType base = 2.0); - - /** - * Create the cover tree with the given dataset, taking ownership of the - * dataset. Optionally, set the base. - * - * @param dataset Reference to the dataset to build a tree on. - * @param base Base to use during tree building (default 2.0). - */ - CoverTree(MatType&& dataset, - const ElemType base = 2.0); - - /** - * Create the cover tree with the given dataset and the given instantiated - * metric, taking ownership of the dataset. Optionally, set the base. - * - * @param dataset Reference to the dataset to build a tree on. - * @param metric Instantiated metric to use during tree building. - * @param base Base to use during tree building (default 2.0). - */ - CoverTree(MatType&& dataset, - MetricType& metric, - const ElemType base = 2.0); - - /** - * Construct a child cover tree node. This constructor is not meant to be - * used externally, but it could be used to insert another node into a tree. - * This procedure uses only one vector for the near set, the far set, and the - * used set (this is to prevent unnecessary memory allocation in recursive - * calls to this constructor). Therefore, the size of the near set, far set, - * and used set must be passed in. The near set will be entirely used up, and - * some of the far set may be used. The value of usedSetSize will be set to - * the number of points used in the construction of this node, and the value - * of farSetSize will be modified to reflect the number of points in the far - * set _after_ the construction of this node. - * - * If you are calling this manually, be careful that the given scale is - * as small as possible, or you may be creating an implicit node in your tree. - * - * @param dataset Reference to the dataset to build a tree on. - * @param base Base to use during tree building. - * @param pointIndex Index of the point this node references. - * @param scale Scale of this level in the tree. - * @param parent Parent of this node (NULL indicates no parent). - * @param parentDistance Distance to the parent node. - * @param indices Array of indices, ordered [ nearSet | farSet | usedSet ]; - * will be modified to [ farSet | usedSet ]. - * @param distances Array of distances, ordered the same way as the indices. - * These represent the distances between the point specified by pointIndex - * and each point in the indices array. - * @param nearSetSize Size of the near set; if 0, this will be a leaf. - * @param farSetSize Size of the far set; may be modified (if this node uses - * any points in the far set). - * @param usedSetSize The number of points used will be added to this number. - */ - CoverTree(const MatType& dataset, - const ElemType base, - const size_t pointIndex, - const int scale, - CoverTree* parent, - const ElemType parentDistance, - arma::Col& indices, - arma::vec& distances, - size_t nearSetSize, - size_t& farSetSize, - size_t& usedSetSize, - MetricType& metric = NULL); - - /** - * Manually construct a cover tree node; no tree assembly is done in this - * constructor, and children must be added manually (use Children()). This - * constructor is useful when the tree is being "imported" into the CoverTree - * class after being created in some other manner. - * - * @param dataset Reference to the dataset this node is a part of. - * @param base Base that was used for tree building. - * @param pointIndex Index of the point in the dataset which this node refers - * to. - * @param scale Scale of this node's level in the tree. - * @param parent Parent node (NULL indicates no parent). - * @param parentDistance Distance to parent node point. - * @param furthestDescendantDistance Distance to furthest descendant point. - * @param metric Instantiated metric (optional). - */ - CoverTree(const MatType& dataset, - const ElemType base, - const size_t pointIndex, - const int scale, - CoverTree* parent, - const ElemType parentDistance, - const ElemType furthestDescendantDistance, - MetricType* metric = NULL); - - /** - * Create a cover tree from another tree. Be careful! This may use a lot of - * memory and take a lot of time. This will also make a copy of the dataset. - * - * @param other Cover tree to copy from. - */ - CoverTree(const CoverTree& other); - - /** - * Move constructor for a Cover Tree, possess all the members of the given - * tree. - * - * @param other Cover Tree to move. - */ - CoverTree(CoverTree&& other); - - /** - * Create a cover tree from a boost::serialization archive. - */ - template - CoverTree( - Archive& ar, - const typename std::enable_if_t* = 0); - - /** - * Delete this cover tree node and its children. - */ - ~CoverTree(); - - //! A single-tree cover tree traverser; see single_tree_traverser.hpp for - //! implementation. - template - class SingleTreeTraverser; - - //! A dual-tree cover tree traverser; see dual_tree_traverser.hpp. - template - class DualTreeTraverser; - - template - using BreadthFirstDualTreeTraverser = DualTreeTraverser; - - //! Get a reference to the dataset. - const MatType& Dataset() const { return *dataset; } - - //! Get the index of the point which this node represents. - size_t Point() const { return point; } - //! For compatibility with other trees; the argument is ignored. - size_t Point(const size_t) const { return point; } - - bool IsLeaf() const { return (children.size() == 0); } - size_t NumPoints() const { return 1; } - - //! Get a particular child node. - const CoverTree& Child(const size_t index) const { return *children[index]; } - //! Modify a particular child node. - CoverTree& Child(const size_t index) { return *children[index]; } - - CoverTree*& ChildPtr(const size_t index) { return children[index]; } - - //! Get the number of children. - size_t NumChildren() const { return children.size(); } - - //! Get the children. - const std::vector& Children() const { return children; } - //! Modify the children manually (maybe not a great idea). - std::vector& Children() { return children; } - - //! Get the number of descendant points. - size_t NumDescendants() const; - - //! Get the index of a particular descendant point. - size_t Descendant(const size_t index) const; - - //! Get the scale of this node. - int Scale() const { return scale; } - //! Modify the scale of this node. Be careful... - int& Scale() { return scale; } - - //! Get the base. - ElemType Base() const { return base; } - //! Modify the base; don't do this, you'll break everything. - ElemType& Base() { return base; } - - //! Get the statistic for this node. - const StatisticType& Stat() const { return stat; } - //! Modify the statistic for this node. - StatisticType& Stat() { return stat; } - - /** - * Return the index of the nearest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ - template - size_t GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0); - - /** - * Return the index of the furthest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ - template - size_t GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0); - - /** - * Return the index of the nearest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ - size_t GetNearestChild(const CoverTree& queryNode); - - /** - * Return the index of the furthest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ - size_t GetFurthestChild(const CoverTree& queryNode); - - //! Return the minimum distance to another node. - ElemType MinDistance(const CoverTree& other) const; - - //! Return the minimum distance to another node given that the point-to-point - //! distance has already been calculated. - ElemType MinDistance(const CoverTree& other, const ElemType distance) const; - - //! Return the minimum distance to another point. - ElemType MinDistance(const arma::vec& other) const; - - //! Return the minimum distance to another point given that the distance from - //! the center to the point has already been calculated. - ElemType MinDistance(const arma::vec& other, const ElemType distance) const; - - //! Return the maximum distance to another node. - ElemType MaxDistance(const CoverTree& other) const; - - //! Return the maximum distance to another node given that the point-to-point - //! distance has already been calculated. - ElemType MaxDistance(const CoverTree& other, const ElemType distance) const; - - //! Return the maximum distance to another point. - ElemType MaxDistance(const arma::vec& other) const; - - //! Return the maximum distance to another point given that the distance from - //! the center to the point has already been calculated. - ElemType MaxDistance(const arma::vec& other, const ElemType distance) const; - - //! Return the minimum and maximum distance to another node. - math::RangeType RangeDistance(const CoverTree& other) const; - - //! Return the minimum and maximum distance to another node given that the - //! point-to-point distance has already been calculated. - math::RangeType RangeDistance(const CoverTree& other, - const ElemType distance) const; - - //! Return the minimum and maximum distance to another point. - math::RangeType RangeDistance(const arma::vec& other) const; - - //! Return the minimum and maximum distance to another point given that the - //! point-to-point distance has already been calculated. - math::RangeType RangeDistance(const arma::vec& other, - const ElemType distance) const; - - //! Get the parent node. - CoverTree* Parent() const { return parent; } - //! Modify the parent node. - CoverTree*& Parent() { return parent; } - - //! Get the distance to the parent. - ElemType ParentDistance() const { return parentDistance; } - //! Modify the distance to the parent. - ElemType& ParentDistance() { return parentDistance; } - - //! Get the distance to the furthest point. This is always 0 for cover trees. - ElemType FurthestPointDistance() const { return 0.0; } - - //! Get the distance from the center of the node to the furthest descendant. - ElemType FurthestDescendantDistance() const - { return furthestDescendantDistance; } - //! Modify the distance from the center of the node to the furthest - //! descendant. - ElemType& FurthestDescendantDistance() { return furthestDescendantDistance; } - - //! Get the minimum distance from the center to any bound edge (this is the - //! same as furthestDescendantDistance). - ElemType MinimumBoundDistance() const { return furthestDescendantDistance; } - - //! Get the center of the node and store it in the given vector. - void Center(arma::vec& center) const - { - center = arma::vec(dataset->col(point)); - } - - //! Get the instantiated metric. - MetricType& Metric() const { return *metric; } - - private: - //! Reference to the matrix which this tree is built on. - const MatType* dataset; - //! Index of the point in the matrix which this node represents. - size_t point; - //! The list of children; the first is the self-child. - std::vector children; - //! Scale level of the node. - int scale; - //! The base used to construct the tree. - ElemType base; - //! The instantiated statistic. - StatisticType stat; - //! The number of descendant points. - size_t numDescendants; - //! The parent node (NULL if this is the root of the tree). - CoverTree* parent; - //! Distance to the parent. - ElemType parentDistance; - //! Distance to the furthest descendant. - ElemType furthestDescendantDistance; - //! Whether or not we need to destroy the metric in the destructor. - bool localMetric; - //! If true, we own the dataset and need to destroy it in the destructor. - bool localDataset; - //! The metric used for this tree. - MetricType* metric; - - /** - * Create the children for this node. - */ - void CreateChildren(arma::Col& indices, - arma::vec& distances, - size_t nearSetSize, - size_t& farSetSize, - size_t& usedSetSize); - - /** - * Fill the vector of distances with the distances between the point specified - * by pointIndex and each point in the indices array. The distances of the - * first pointSetSize points in indices are calculated (so, this does not - * necessarily need to use all of the points in the arrays). - * - * @param pointIndex Point to build the distances for. - * @param indices List of indices to compute distances for. - * @param distances Vector to store calculated distances in. - * @param pointSetSize Number of points in arrays to calculate distances for. - */ - void ComputeDistances(const size_t pointIndex, - const arma::Col& indices, - arma::vec& distances, - const size_t pointSetSize); - /** - * Split the given indices and distances into a near and a far set, returning - * the number of points in the near set. The distances must already be - * initialized. This will order the indices and distances such that the - * points in the near set make up the first part of the array and the far set - * makes up the rest: [ nearSet | farSet ]. - * - * @param indices List of indices; will be reordered. - * @param distances List of distances; will be reordered. - * @param bound If the distance is less than or equal to this bound, the point - * is placed into the near set. - * @param pointSetSize Size of point set (because we may be sorting a smaller - * list than the indices vector will hold). - */ - size_t SplitNearFar(arma::Col& indices, - arma::vec& distances, - const ElemType bound, - const size_t pointSetSize); - - /** - * Assuming that the list of indices and distances is sorted as - * [ childFarSet | childUsedSet | farSet | usedSet ], - * resort the sets so the organization is - * [ childFarSet | farSet | childUsedSet | usedSet ]. - * - * The size_t parameters specify the sizes of each set in the array. Only the - * ordering of the indices and distances arrays will be modified (not their - * actual contents). - * - * The size of any of the four sets can be zero and this method will handle - * that case accordingly. - * - * @param indices List of indices to sort. - * @param distances List of distances to sort. - * @param childFarSetSize Number of points in child far set (childFarSet). - * @param childUsedSetSize Number of points in child used set (childUsedSet). - * @param farSetSize Number of points in far set (farSet). - */ - size_t SortPointSet(arma::Col& indices, - arma::vec& distances, - const size_t childFarSetSize, - const size_t childUsedSetSize, - const size_t farSetSize); - - void MoveToUsedSet(arma::Col& indices, - arma::vec& distances, - size_t& nearSetSize, - size_t& farSetSize, - size_t& usedSetSize, - arma::Col& childIndices, - const size_t childFarSetSize, - const size_t childUsedSetSize); - size_t PruneFarSet(arma::Col& indices, - arma::vec& distances, - const ElemType bound, - const size_t nearSetSize, - const size_t pointSetSize); - - /** - * Take a look at the last child (the most recently created one) and remove - * any implicit nodes that have been created. - */ - void RemoveNewImplicitNodes(); - - protected: - /** - * A default constructor. This is meant to only be used with - * boost::serialization, which is allowed with the friend declaration below. - * This does not return a valid tree! This method must be protected, so that - * the serialization shim can work with the default constructor. - */ - CoverTree(); - - //! Friend access is given for the default constructor. - friend class boost::serialization::access; - - public: - /** - * Serialize the tree. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - size_t DistanceComps() const { return distanceComps; } - size_t& DistanceComps() { return distanceComps; } - - private: - size_t distanceComps; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "cover_tree_impl.hpp" - -// Include the rest of the pieces, if necessary. -#include "../cover_tree.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/cover_tree_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/cover_tree_impl.hpp deleted file mode 100644 index d4749027f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/cover_tree_impl.hpp +++ /dev/null @@ -1,1635 +0,0 @@ -/** - * @file cover_tree_impl.hpp - * @author Ryan Curtin - * - * Implementation of CoverTree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_COVER_TREE_IMPL_HPP -#define MLPACK_CORE_TREE_COVER_TREE_COVER_TREE_IMPL_HPP - -// In case it hasn't already been included. -#include "cover_tree.hpp" - -#include -#include - -namespace mlpack { -namespace tree { - -// Create the cover tree. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree( - const MatType& dataset, - const ElemType base, - MetricType* metric) : - dataset(&dataset), - point(RootPointPolicy::ChooseRoot(dataset)), - scale(INT_MAX), - base(base), - numDescendants(0), - parent(NULL), - parentDistance(0), - furthestDescendantDistance(0), - localMetric(metric == NULL), - localDataset(false), - metric(metric), - distanceComps(0) -{ - // If we need to create a metric, do that. We'll just do it on the heap. - if (localMetric) - this->metric = new MetricType(); - - // If there is only one point or zero points in the dataset... uh, we're done. - // Technically, if the dataset has zero points, our node is not correct... - if (dataset.n_cols <= 1) - { - scale = INT_MIN; - return; - } - - // Kick off the building. Create the indices array and the distances array. - arma::Col indices = arma::linspace >(1, - dataset.n_cols - 1, dataset.n_cols - 1); - // This is now [1 2 3 4 ... n]. We must be sure that our point does not - // occur. - if (point != 0) - indices[point - 1] = 0; // Put 0 back into the set; remove what was there. - - arma::vec distances(dataset.n_cols - 1); - - // Build the initial distances. - ComputeDistances(point, indices, distances, dataset.n_cols - 1); - - // Create the children. - size_t farSetSize = 0; - size_t usedSetSize = 0; - CreateChildren(indices, distances, dataset.n_cols - 1, farSetSize, - usedSetSize); - - // If we ended up creating only one child, remove the implicit node. - while (children.size() == 1) - { - // Prepare to delete the implicit child node. - CoverTree* old = children[0]; - - // Now take its children and set their parent correctly. - children.erase(children.begin()); - for (size_t i = 0; i < old->NumChildren(); ++i) - { - children.push_back(&(old->Child(i))); - - // Set its parent correctly, and rebuild the statistic. - old->Child(i).Parent() = this; - old->Child(i).Stat() = StatisticType(old->Child(i)); - } - - // Remove all the children so they don't get erased. - old->Children().clear(); - - // Reduce our own scale. - scale = old->Scale(); - - // Now delete it. - delete old; - } - - // Use the furthest descendant distance to determine the scale of the root - // node. - if (furthestDescendantDistance == 0.0) - scale = INT_MIN; - else - scale = (int) ceil(log(furthestDescendantDistance) / log(base)); - - // Initialize statistic. - stat = StatisticType(*this); - - Log::Info << distanceComps << " distance computations during tree " - << "construction." << std::endl; -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree( - const MatType& dataset, - MetricType& metric, - const ElemType base) : - dataset(&dataset), - point(RootPointPolicy::ChooseRoot(dataset)), - scale(INT_MAX), - base(base), - numDescendants(0), - parent(NULL), - parentDistance(0), - furthestDescendantDistance(0), - localMetric(false), - localDataset(false), - metric(&metric), - distanceComps(0) -{ - // If there is only one point or zero points in the dataset... uh, we're done. - // Technically, if the dataset has zero points, our node is not correct... - if (dataset.n_cols <= 1) - { - scale = INT_MIN; - return; - } - - // Kick off the building. Create the indices array and the distances array. - arma::Col indices = arma::linspace >(1, - dataset.n_cols - 1, dataset.n_cols - 1); - // This is now [1 2 3 4 ... n]. We must be sure that our point does not - // occur. - if (point != 0) - indices[point - 1] = 0; // Put 0 back into the set; remove what was there. - - arma::vec distances(dataset.n_cols - 1); - - // Build the initial distances. - ComputeDistances(point, indices, distances, dataset.n_cols - 1); - - // Create the children. - size_t farSetSize = 0; - size_t usedSetSize = 0; - CreateChildren(indices, distances, dataset.n_cols - 1, farSetSize, - usedSetSize); - - // If we ended up creating only one child, remove the implicit node. - while (children.size() == 1) - { - // Prepare to delete the implicit child node. - CoverTree* old = children[0]; - - // Now take its children and set their parent correctly. - children.erase(children.begin()); - for (size_t i = 0; i < old->NumChildren(); ++i) - { - children.push_back(&(old->Child(i))); - - // Set its parent correctly. - old->Child(i).Parent() = this; - // Rebuild the statistic. - old->Child(i).Stat() = StatisticType(old->Child(i)); - } - - // Remove all the children so they don't get erased. - old->Children().clear(); - - // Reduce our own scale. - scale = old->Scale(); - - // Now delete it. - delete old; - } - - // Use the furthest descendant distance to determine the scale of the root - // node. - if (furthestDescendantDistance == 0.0) - scale = INT_MIN; - else - scale = (int) ceil(log(furthestDescendantDistance) / log(base)); - - // Initialize statistic. - stat = StatisticType(*this); - - Log::Info << distanceComps << " distance computations during tree " - << "construction." << std::endl; -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree( - MatType&& data, - const ElemType base) : - dataset(new MatType(std::move(data))), - point(RootPointPolicy::ChooseRoot(dataset)), - scale(INT_MAX), - base(base), - numDescendants(0), - parent(NULL), - parentDistance(0), - furthestDescendantDistance(0), - localMetric(true), - localDataset(true), - distanceComps(0) -{ - // We need to create a metric. We'll just do it on the heap. - this->metric = new MetricType(); - - // If there is only one point or zero points in the dataset... uh, we're done. - // Technically, if the dataset has zero points, our node is not correct... - if (dataset->n_cols <= 1) - { - scale = INT_MIN; - return; - } - - // Kick off the building. Create the indices array and the distances array. - arma::Col indices = arma::linspace >(1, - dataset->n_cols - 1, dataset->n_cols - 1); - // This is now [1 2 3 4 ... n]. We must be sure that our point does not - // occur. - if (point != 0) - indices[point - 1] = 0; // Put 0 back into the set; remove what was there. - - arma::vec distances(dataset->n_cols - 1); - - // Build the initial distances. - ComputeDistances(point, indices, distances, dataset->n_cols - 1); - - // Create the children. - size_t farSetSize = 0; - size_t usedSetSize = 0; - CreateChildren(indices, distances, dataset->n_cols - 1, farSetSize, - usedSetSize); - - // If we ended up creating only one child, remove the implicit node. - while (children.size() == 1) - { - // Prepare to delete the implicit child node. - CoverTree* old = children[0]; - - // Now take its children and set their parent correctly. - children.erase(children.begin()); - for (size_t i = 0; i < old->NumChildren(); ++i) - { - children.push_back(&(old->Child(i))); - - // Set its parent correctly, and rebuild the statistic. - old->Child(i).Parent() = this; - old->Child(i).Stat() = StatisticType(old->Child(i)); - } - - // Remove all the children so they don't get erased. - old->Children().clear(); - - // Reduce our own scale. - scale = old->Scale(); - - // Now delete it. - delete old; - } - - // Use the furthest descendant distance to determine the scale of the root - // node. - if (furthestDescendantDistance == 0.0) - scale = INT_MIN; - else - scale = (int) ceil(log(furthestDescendantDistance) / log(base)); - - // Initialize statistic. - stat = StatisticType(*this); - - Log::Info << distanceComps << " distance computations during tree " - << "construction." << std::endl; -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree( - MatType&& data, - MetricType& metric, - const ElemType base) : - dataset(new MatType(std::move(data))), - point(RootPointPolicy::ChooseRoot(dataset)), - scale(INT_MAX), - base(base), - numDescendants(0), - parent(NULL), - parentDistance(0), - furthestDescendantDistance(0), - localMetric(false), - localDataset(true), - metric(&metric), - distanceComps(0) -{ - // If there is only one point or zero points in the dataset... uh, we're done. - // Technically, if the dataset has zero points, our node is not correct... - if (dataset->n_cols <= 1) - { - scale = INT_MIN; - return; - } - - // Kick off the building. Create the indices array and the distances array. - arma::Col indices = arma::linspace >(1, - dataset->n_cols - 1, dataset->n_cols - 1); - // This is now [1 2 3 4 ... n]. We must be sure that our point does not - // occur. - if (point != 0) - indices[point - 1] = 0; // Put 0 back into the set; remove what was there. - - arma::vec distances(dataset->n_cols - 1); - - // Build the initial distances. - ComputeDistances(point, indices, distances, dataset->n_cols - 1); - - // Create the children. - size_t farSetSize = 0; - size_t usedSetSize = 0; - CreateChildren(indices, distances, dataset->n_cols - 1, farSetSize, - usedSetSize); - - // If we ended up creating only one child, remove the implicit node. - while (children.size() == 1) - { - // Prepare to delete the implicit child node. - CoverTree* old = children[0]; - - // Now take its children and set their parent correctly. - children.erase(children.begin()); - for (size_t i = 0; i < old->NumChildren(); ++i) - { - children.push_back(&(old->Child(i))); - - // Set its parent correctly, and rebuild the statistic. - old->Child(i).Parent() = this; - old->Child(i).Stat() = StatisticType(old->Child(i)); - } - - // Remove all the children so they don't get erased. - old->Children().clear(); - - // Reduce our own scale. - scale = old->Scale(); - - // Now delete it. - delete old; - } - - // Use the furthest descendant distance to determine the scale of the root - // node. - if (furthestDescendantDistance == 0.0) - scale = INT_MIN; - else - scale = (int) ceil(log(furthestDescendantDistance) / log(base)); - - // Initialize statistic. - stat = StatisticType(*this); - - Log::Info << distanceComps << " distance computations during tree " - << "construction." << std::endl; -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree( - const MatType& dataset, - const ElemType base, - const size_t pointIndex, - const int scale, - CoverTree* parent, - const ElemType parentDistance, - arma::Col& indices, - arma::vec& distances, - size_t nearSetSize, - size_t& farSetSize, - size_t& usedSetSize, - MetricType& metric) : - dataset(&dataset), - point(pointIndex), - scale(scale), - base(base), - numDescendants(0), - parent(parent), - parentDistance(parentDistance), - furthestDescendantDistance(0), - localMetric(false), - localDataset(false), - metric(&metric), - distanceComps(0) -{ - // If the size of the near set is 0, this is a leaf. - if (nearSetSize == 0) - { - this->scale = INT_MIN; - numDescendants = 1; - stat = StatisticType(*this); - return; - } - - // Otherwise, create the children. - CreateChildren(indices, distances, nearSetSize, farSetSize, usedSetSize); - - // Initialize statistic. - stat = StatisticType(*this); -} - -// Manually create a cover tree node. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree( - const MatType& dataset, - const ElemType base, - const size_t pointIndex, - const int scale, - CoverTree* parent, - const ElemType parentDistance, - const ElemType furthestDescendantDistance, - MetricType* metric) : - dataset(&dataset), - point(pointIndex), - scale(scale), - base(base), - numDescendants(0), - parent(parent), - parentDistance(parentDistance), - furthestDescendantDistance(furthestDescendantDistance), - localMetric(metric == NULL), - localDataset(false), - metric(metric), - distanceComps(0) -{ - // If necessary, create a local metric. - if (localMetric) - this->metric = new MetricType(); - - // Initialize the statistic. - stat = StatisticType(*this); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree( - const CoverTree& other) : - dataset((other.parent == NULL && other.localDataset) ? - new MatType(*other.dataset) : other.dataset), - point(other.point), - scale(other.scale), - base(other.base), - stat(other.stat), - numDescendants(other.numDescendants), - parent(other.parent), - parentDistance(other.parentDistance), - furthestDescendantDistance(other.furthestDescendantDistance), - localMetric(false), - localDataset(other.parent == NULL && other.localDataset), - metric(other.metric), - distanceComps(0) -{ - // Copy each child by hand. - for (size_t i = 0; i < other.NumChildren(); ++i) - { - children.push_back(new CoverTree(other.Child(i))); - children[i]->Parent() = this; - } - - // Propagate matrix, but only if we are the root. - if (parent == NULL && localDataset) - { - std::queue queue; - - for (size_t i = 0; i < NumChildren(); ++i) - queue.push(children[i]); - - while (!queue.empty()) - { - CoverTree* node = queue.front(); - queue.pop(); - - node->dataset = dataset; - for (size_t i = 0; i < node->NumChildren(); ++i) - queue.push(node->children[i]); - } - } -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree( - CoverTree&& other) : - dataset(other.dataset), - point(other.point), - children(std::move(other.children)), - scale(other.scale), - base(other.base), - stat(std::move(other.stat)), - numDescendants(other.numDescendants), - parent(other.parent), - parentDistance(other.parentDistance), - furthestDescendantDistance(other.furthestDescendantDistance), - localMetric(other.localMetric), - localDataset(other.localDataset), - metric(other.metric), - distanceComps(other.distanceComps) -{ - // Set proper parent pointer. - for (size_t i = 0; i < children.size(); ++i) - children[i]->Parent() = this; - - other.dataset = NULL; - other.point = 0; - other.scale = INT_MIN; - other.base = 0; - other.numDescendants = 0; - other.parent = NULL; - other.parentDistance = 0; - other.furthestDescendantDistance = 0; - other.localMetric = false; - other.localDataset = false; - other.metric = NULL; -} - -// Construct from a boost::serialization archive. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -CoverTree::CoverTree( - Archive& ar, - const typename std::enable_if_t*) : - CoverTree() // Create an empty CoverTree. -{ - // Now, serialize to our empty tree. - ar >> boost::serialization::make_nvp("this", *this); -} - - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::~CoverTree() -{ - // Delete each child. - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - - // Delete the local metric, if necessary. - if (localMetric) - delete metric; - - // Delete the local dataset, if necessary. - if (localDataset) - delete dataset; -} - -//! Return the number of descendant points. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -inline size_t -CoverTree:: - NumDescendants() const -{ - return numDescendants; -} - -//! Return the index of a particular descendant point. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -inline size_t -CoverTree::Descendant( - const size_t index) const -{ - // The first descendant is the point contained within this node. - if (index == 0) - return point; - - // Is it in the self-child? - if (index < children[0]->NumDescendants()) - return children[0]->Descendant(index); - - // Now check the other children. - size_t sum = children[0]->NumDescendants(); - for (size_t i = 1; i < children.size(); ++i) - { - if (index - sum < children[i]->NumDescendants()) - return children[i]->Descendant(index - sum); - sum += children[i]->NumDescendants(); - } - - // This should never happen. - return (size_t() - 1); -} - -/** - * Return the index of the nearest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ -template -template -size_t CoverTree:: - GetNearestChild(const VecType& point, - typename std::enable_if_t::value>*) -{ - if (IsLeaf()) - return 0; - - ElemType bestDistance = std::numeric_limits::max(); - size_t bestIndex = 0; - for (size_t i = 0; i < children.size(); ++i) - { - ElemType distance = children[i]->MinDistance(point); - if (distance <= bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - return bestIndex; -} - -/** - * Return the index of the furthest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ -template -template -size_t CoverTree:: - GetFurthestChild(const VecType& point, - typename std::enable_if_t::value>*) -{ - if (IsLeaf()) - return 0; - - ElemType bestDistance = 0; - size_t bestIndex = 0; - for (size_t i = 0; i < children.size(); ++i) - { - ElemType distance = children[i]->MaxDistance(point); - if (distance >= bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - return bestIndex; -} - -/** - * Return the index of the nearest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ -template -size_t CoverTree:: - GetNearestChild(const CoverTree& queryNode) -{ - if (IsLeaf()) - return 0; - - ElemType bestDistance = std::numeric_limits::max(); - size_t bestIndex = 0; - for (size_t i = 0; i < children.size(); ++i) - { - ElemType distance = children[i]->MinDistance(queryNode); - if (distance <= bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - return bestIndex; -} - -/** - * Return the index of the furthest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ -template -size_t CoverTree:: - GetFurthestChild(const CoverTree& queryNode) -{ - if (IsLeaf()) - return 0; - - ElemType bestDistance = 0; - size_t bestIndex = 0; - for (size_t i = 0; i < children.size(); ++i) - { - ElemType distance = children[i]->MaxDistance(queryNode); - if (distance >= bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - return bestIndex; -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -typename CoverTree::ElemType -CoverTree:: - MinDistance(const CoverTree& other) const -{ - // Every cover tree node will contain points up to base^(scale + 1) away. - return std::max(metric->Evaluate(dataset->col(point), - other.Dataset().col(other.Point())) - - furthestDescendantDistance - other.FurthestDescendantDistance(), 0.0); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -typename CoverTree::ElemType -CoverTree:: - MinDistance(const CoverTree& other, const ElemType distance) const -{ - // We already have the distance as evaluated by the metric. - return std::max(distance - furthestDescendantDistance - - other.FurthestDescendantDistance(), 0.0); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -typename CoverTree::ElemType -CoverTree:: - MinDistance(const arma::vec& other) const -{ - return std::max(metric->Evaluate(dataset->col(point), other) - - furthestDescendantDistance, 0.0); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -typename CoverTree::ElemType -CoverTree:: - MinDistance(const arma::vec& /* other */, const ElemType distance) const -{ - return std::max(distance - furthestDescendantDistance, 0.0); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -typename CoverTree::ElemType -CoverTree:: - MaxDistance(const CoverTree& other) const -{ - return metric->Evaluate(dataset->col(point), - other.Dataset().col(other.Point())) + - furthestDescendantDistance + other.FurthestDescendantDistance(); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -typename CoverTree::ElemType -CoverTree:: - MaxDistance(const CoverTree& other, const ElemType distance) const -{ - // We already have the distance as evaluated by the metric. - return distance + furthestDescendantDistance + - other.FurthestDescendantDistance(); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -typename CoverTree::ElemType -CoverTree:: - MaxDistance(const arma::vec& other) const -{ - return metric->Evaluate(dataset->col(point), other) + - furthestDescendantDistance; -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -typename CoverTree::ElemType -CoverTree:: - MaxDistance(const arma::vec& /* other */, const ElemType distance) const -{ - return distance + furthestDescendantDistance; -} - -//! Return the minimum and maximum distance to another node. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -math::RangeType::ElemType> -CoverTree:: - RangeDistance(const CoverTree& other) const -{ - const ElemType distance = metric->Evaluate(dataset->col(point), - other.Dataset().col(other.Point())); - - math::RangeType result; - result.Lo() = distance - furthestDescendantDistance - - other.FurthestDescendantDistance(); - result.Hi() = distance + furthestDescendantDistance + - other.FurthestDescendantDistance(); - - return result; -} - -//! Return the minimum and maximum distance to another node given that the -//! point-to-point distance has already been calculated. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -math::RangeType::ElemType> -CoverTree:: - RangeDistance(const CoverTree& other, - const ElemType distance) const -{ - math::RangeType result; - result.Lo() = distance - furthestDescendantDistance - - other.FurthestDescendantDistance(); - result.Hi() = distance + furthestDescendantDistance + - other.FurthestDescendantDistance(); - - return result; -} - -//! Return the minimum and maximum distance to another point. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -math::RangeType::ElemType> -CoverTree:: - RangeDistance(const arma::vec& other) const -{ - const ElemType distance = metric->Evaluate(dataset->col(point), other); - - return math::RangeType(distance - furthestDescendantDistance, - distance + furthestDescendantDistance); -} - -//! Return the minimum and maximum distance to another point given that the -//! point-to-point distance has already been calculated. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -math::RangeType::ElemType> -CoverTree:: - RangeDistance(const arma::vec& /* other */, - const ElemType distance) const -{ - return math::RangeType(distance - furthestDescendantDistance, - distance + furthestDescendantDistance); -} - -//! For a newly initialized node, create children using the near and far set. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -inline void -CoverTree::CreateChildren( - arma::Col& indices, - arma::vec& distances, - size_t nearSetSize, - size_t& farSetSize, - size_t& usedSetSize) -{ - // Determine the next scale level. This should be the first level where there - // are any points in the far set. So, if we know the maximum distance in the - // distances array, this will be the largest i such that - // maxDistance > pow(base, i) - // and using this for the scale factor should guarantee we are not creating an - // implicit node. If the maximum distance is 0, every point in the near set - // will be created as a leaf, and a child to this node. We also do not need - // to change the furthestChildDistance or furthestDescendantDistance. - const ElemType maxDistance = max(distances.rows(0, - nearSetSize + farSetSize - 1)); - if (maxDistance == 0) - { - // Make the self child at the lowest possible level. - // This should not modify farSetSize or usedSetSize. - size_t tempSize = 0; - children.push_back(new CoverTree(*dataset, base, point, INT_MIN, this, 0, - indices, distances, 0, tempSize, usedSetSize, *metric)); - distanceComps += children.back()->DistanceComps(); - - // Every point in the near set should be a leaf. - for (size_t i = 0; i < nearSetSize; ++i) - { - // farSetSize and usedSetSize will not be modified. - children.push_back(new CoverTree(*dataset, base, indices[i], - INT_MIN, this, distances[i], indices, distances, 0, tempSize, - usedSetSize, *metric)); - distanceComps += children.back()->DistanceComps(); - usedSetSize++; - } - - // The number of descendants is just the number of children, because each of - // them are leaves and contain one point. - numDescendants = children.size(); - - // Re-sort the dataset. We have - // [ used | far | other used ] - // and we want - // [ far | all used ]. - SortPointSet(indices, distances, 0, usedSetSize, farSetSize); - - return; - } - - const int nextScale = std::min(scale, - (int) ceil(log(maxDistance) / log(base))) - 1; - const ElemType bound = pow(base, nextScale); - - // First, make the self child. We must split the given near set into the near - // set and far set for the self child. - size_t childNearSetSize = - SplitNearFar(indices, distances, bound, nearSetSize); - - // Build the self child (recursively). - size_t childFarSetSize = nearSetSize - childNearSetSize; - size_t childUsedSetSize = 0; - children.push_back(new CoverTree(*dataset, base, point, nextScale, this, 0, - indices, distances, childNearSetSize, childFarSetSize, childUsedSetSize, - *metric)); - // Don't double-count the self-child (so, subtract one). - numDescendants += children[0]->NumDescendants(); - - // The self-child can't modify the furthestChildDistance away from 0, but it - // can modify the furthestDescendantDistance. - furthestDescendantDistance = children[0]->FurthestDescendantDistance(); - - // Remove any implicit nodes we may have created. - RemoveNewImplicitNodes(); - - distanceComps += children[0]->DistanceComps(); - - // Now the arrays, in memory, look like this: - // [ childFar | childUsed | far | used ] - // but we need to move the used points past our far set: - // [ childFar | far | childUsed + used ] - // and keeping in mind that childFar = our near set, - // [ near | far | childUsed + used ] - // is what we are trying to make. - SortPointSet(indices, distances, childFarSetSize, childUsedSetSize, - farSetSize); - - // Update size of near set and used set. - nearSetSize -= childUsedSetSize; - usedSetSize += childUsedSetSize; - - // Now for each point in the near set, we need to make children. To save - // computation later, we'll create an array holding the points in the near - // set, and then after each run we'll check which of those (if any) were used - // and we will remove them. ...if that's faster. I think it is. - while (nearSetSize > 0) - { - size_t newPointIndex = nearSetSize - 1; - - // Swap to front if necessary. - if (newPointIndex != 0) - { - const size_t tempIndex = indices[newPointIndex]; - const ElemType tempDist = distances[newPointIndex]; - - indices[newPointIndex] = indices[0]; - distances[newPointIndex] = distances[0]; - - indices[0] = tempIndex; - distances[0] = tempDist; - } - - // Will this be a new furthest child? - if (distances[0] > furthestDescendantDistance) - furthestDescendantDistance = distances[0]; - - // If there's only one point left, we don't need this crap. - if ((nearSetSize == 1) && (farSetSize == 0)) - { - size_t childNearSetSize = 0; - children.push_back(new CoverTree(*dataset, base, indices[0], nextScale, - this, distances[0], indices, distances, childNearSetSize, farSetSize, - usedSetSize, *metric)); - distanceComps += children.back()->DistanceComps(); - numDescendants += children.back()->NumDescendants(); - - // Because the far set size is 0, we don't have to do any swapping to - // move the point into the used set. - ++usedSetSize; - --nearSetSize; - - // And we're done. - break; - } - - // Create the near and far set indices and distance vectors. We don't fill - // in the self-point, yet. - arma::Col childIndices(nearSetSize + farSetSize); - childIndices.rows(0, (nearSetSize + farSetSize - 2)) = indices.rows(1, - nearSetSize + farSetSize - 1); - arma::vec childDistances(nearSetSize + farSetSize); - - // Build distances for the child. - ComputeDistances(indices[0], childIndices, childDistances, nearSetSize - + farSetSize - 1); - - // Split into near and far sets for this point. - childNearSetSize = SplitNearFar(childIndices, childDistances, bound, - nearSetSize + farSetSize - 1); - childFarSetSize = PruneFarSet(childIndices, childDistances, - base * bound, childNearSetSize, - (nearSetSize + farSetSize - 1)); - - // Now that we know the near and far set sizes, we can put the used point - // (the self point) in the correct place; now, when we call - // MoveToUsedSet(), it will move the self-point correctly. The distance - // does not matter. - childIndices(childNearSetSize + childFarSetSize) = indices[0]; - childDistances(childNearSetSize + childFarSetSize) = 0; - - // Build this child (recursively). - childUsedSetSize = 1; // Mark self point as used. - children.push_back(new CoverTree(*dataset, base, indices[0], nextScale, - this, distances[0], childIndices, childDistances, childNearSetSize, - childFarSetSize, childUsedSetSize, *metric)); - numDescendants += children.back()->NumDescendants(); - - // Remove any implicit nodes. - RemoveNewImplicitNodes(); - - distanceComps += children.back()->DistanceComps(); - - // Now with the child created, it returns the childIndices and - // childDistances vectors in this form: - // [ childFar | childUsed ] - // For each point in the childUsed set, we must move that point to the used - // set in our own vector. - MoveToUsedSet(indices, distances, nearSetSize, farSetSize, usedSetSize, - childIndices, childFarSetSize, childUsedSetSize); - } - - // Calculate furthest descendant. - for (size_t i = (nearSetSize + farSetSize); i < (nearSetSize + farSetSize + - usedSetSize); ++i) - if (distances[i] > furthestDescendantDistance) - furthestDescendantDistance = distances[i]; -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -size_t CoverTree:: - SplitNearFar(arma::Col& indices, - arma::vec& distances, - const ElemType bound, - const size_t pointSetSize) -{ - // Sanity check; there is no guarantee that this condition will not be true. - // ...or is there? - if (pointSetSize <= 1) - return 0; - - // We'll traverse from both left and right. - size_t left = 0; - size_t right = pointSetSize - 1; - - // A modification of quicksort, with the pivot value set to the bound. - // Everything on the left of the pivot will be less than or equal to the - // bound; everything on the right will be greater than the bound. - while ((distances[left] <= bound) && (left != right)) - ++left; - while ((distances[right] > bound) && (left != right)) - --right; - - while (left != right) - { - // Now swap the values and indices. - const size_t tempPoint = indices[left]; - const ElemType tempDist = distances[left]; - - indices[left] = indices[right]; - distances[left] = distances[right]; - - indices[right] = tempPoint; - distances[right] = tempDist; - - // Traverse the left, seeing how many points are correctly on that side. - // When we encounter an incorrect point, stop. We will switch it later. - while ((distances[left] <= bound) && (left != right)) - ++left; - - // Traverse the right, seeing how many points are correctly on that side. - // When we encounter an incorrect point, stop. We will switch it with the - // wrong point from the left side. - while ((distances[right] > bound) && (left != right)) - --right; - } - - // The final left value is the index of the first far value. - return left; -} - -// Returns the maximum distance between points. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -void CoverTree:: - ComputeDistances(const size_t pointIndex, - const arma::Col& indices, - arma::vec& distances, - const size_t pointSetSize) -{ - // For each point, rebuild the distances. The indices do not need to be - // modified. - distanceComps += pointSetSize; - for (size_t i = 0; i < pointSetSize; ++i) - { - distances[i] = metric->Evaluate(dataset->col(pointIndex), - dataset->col(indices[i])); - } -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -size_t CoverTree:: - SortPointSet(arma::Col& indices, - arma::vec& distances, - const size_t childFarSetSize, - const size_t childUsedSetSize, - const size_t farSetSize) -{ - // We'll use low-level memcpy calls ourselves, just to ensure it's done - // quickly and the way we want it to be. Unfortunately this takes up more - // memory than one-element swaps, but there's not a great way around that. - const size_t bufferSize = std::min(farSetSize, childUsedSetSize); - const size_t bigCopySize = std::max(farSetSize, childUsedSetSize); - - // Sanity check: there is no need to sort if the buffer size is going to be - // zero. - if (bufferSize == 0) - return (childFarSetSize + farSetSize); - - size_t* indicesBuffer = new size_t[bufferSize]; - ElemType* distancesBuffer = new ElemType[bufferSize]; - - // The start of the memory region to copy to the buffer. - const size_t bufferFromLocation = ((bufferSize == farSetSize) ? - (childFarSetSize + childUsedSetSize) : childFarSetSize); - // The start of the memory region to move directly to the new place. - const size_t directFromLocation = ((bufferSize == farSetSize) ? - childFarSetSize : (childFarSetSize + childUsedSetSize)); - // The destination to copy the buffer back to. - const size_t bufferToLocation = ((bufferSize == farSetSize) ? - childFarSetSize : (childFarSetSize + farSetSize)); - // The destination of the directly moved memory region. - const size_t directToLocation = ((bufferSize == farSetSize) ? - (childFarSetSize + farSetSize) : childFarSetSize); - - // Copy the smaller piece to the buffer. - memcpy(indicesBuffer, indices.memptr() + bufferFromLocation, - sizeof(size_t) * bufferSize); - memcpy(distancesBuffer, distances.memptr() + bufferFromLocation, - sizeof(ElemType) * bufferSize); - - // Now move the other memory. - memmove(indices.memptr() + directToLocation, - indices.memptr() + directFromLocation, sizeof(size_t) * bigCopySize); - memmove(distances.memptr() + directToLocation, - distances.memptr() + directFromLocation, sizeof(ElemType) * bigCopySize); - - // Now copy the temporary memory to the right place. - memcpy(indices.memptr() + bufferToLocation, indicesBuffer, - sizeof(size_t) * bufferSize); - memcpy(distances.memptr() + bufferToLocation, distancesBuffer, - sizeof(ElemType) * bufferSize); - - delete[] indicesBuffer; - delete[] distancesBuffer; - - // This returns the complete size of the far set. - return (childFarSetSize + farSetSize); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -void CoverTree:: - MoveToUsedSet(arma::Col& indices, - arma::vec& distances, - size_t& nearSetSize, - size_t& farSetSize, - size_t& usedSetSize, - arma::Col& childIndices, - const size_t childFarSetSize, // childNearSetSize is 0 here. - const size_t childUsedSetSize) -{ - const size_t originalSum = nearSetSize + farSetSize + usedSetSize; - - // Loop across the set. We will swap points as we need. It should be noted - // that farSetSize and nearSetSize may change with each iteration of this loop - // (depending on if we make a swap or not). - size_t startChildUsedSet = 0; // Where to start in the child set. - for (size_t i = 0; i < nearSetSize; ++i) - { - // Discover if this point was in the child's used set. - for (size_t j = startChildUsedSet; j < childUsedSetSize; ++j) - { - if (childIndices[childFarSetSize + j] == indices[i]) - { - // We have found a point; a swap is necessary. - - // Since this point is from the near set, to preserve the near set, we - // must do a swap. - if (farSetSize > 0) - { - if ((nearSetSize - 1) != i) - { - // In this case it must be a three-way swap. - size_t tempIndex = indices[nearSetSize + farSetSize - 1]; - ElemType tempDist = distances[nearSetSize + farSetSize - 1]; - - size_t tempNearIndex = indices[nearSetSize - 1]; - ElemType tempNearDist = distances[nearSetSize - 1]; - - indices[nearSetSize + farSetSize - 1] = indices[i]; - distances[nearSetSize + farSetSize - 1] = distances[i]; - - indices[nearSetSize - 1] = tempIndex; - distances[nearSetSize - 1] = tempDist; - - indices[i] = tempNearIndex; - distances[i] = tempNearDist; - } - else - { - // We can do a two-way swap. - size_t tempIndex = indices[nearSetSize + farSetSize - 1]; - ElemType tempDist = distances[nearSetSize + farSetSize - 1]; - - indices[nearSetSize + farSetSize - 1] = indices[i]; - distances[nearSetSize + farSetSize - 1] = distances[i]; - - indices[i] = tempIndex; - distances[i] = tempDist; - } - } - else if ((nearSetSize - 1) != i) - { - // A two-way swap is possible. - size_t tempIndex = indices[nearSetSize + farSetSize - 1]; - ElemType tempDist = distances[nearSetSize + farSetSize - 1]; - - indices[nearSetSize + farSetSize - 1] = indices[i]; - distances[nearSetSize + farSetSize - 1] = distances[i]; - - indices[i] = tempIndex; - distances[i] = tempDist; - } - else - { - // No swap is necessary. - } - - // We don't need to do a complete preservation of the child index set, - // but we want to make sure we only loop over points we haven't seen. - // So increment the child counter by 1 and move a point if we need. - if (j != startChildUsedSet) - { - childIndices[childFarSetSize + j] = childIndices[childFarSetSize + - startChildUsedSet]; - } - - // Update all counters from the swaps we have done. - ++startChildUsedSet; - --nearSetSize; - --i; // Since we moved a point out of the near set we must step back. - - break; // Break out of this for loop; back to the first one. - } - } - } - - // Now loop over the far set. This loop is different because we only require - // a normal two-way swap instead of the three-way swap to preserve the near - // set / far set ordering. - for (size_t i = 0; i < farSetSize; ++i) - { - // Discover if this point was in the child's used set. - for (size_t j = startChildUsedSet; j < childUsedSetSize; ++j) - { - if (childIndices[childFarSetSize + j] == indices[i + nearSetSize]) - { - // We have found a point to swap. - - // Perform the swap. - size_t tempIndex = indices[nearSetSize + farSetSize - 1]; - ElemType tempDist = distances[nearSetSize + farSetSize - 1]; - - indices[nearSetSize + farSetSize - 1] = indices[nearSetSize + i]; - distances[nearSetSize + farSetSize - 1] = distances[nearSetSize + i]; - - indices[nearSetSize + i] = tempIndex; - distances[nearSetSize + i] = tempDist; - - if (j != startChildUsedSet) - { - childIndices[childFarSetSize + j] = childIndices[childFarSetSize + - startChildUsedSet]; - } - - // Update all counters from the swaps we have done. - ++startChildUsedSet; - --farSetSize; - --i; - - break; // Break out of this for loop; back to the first one. - } - } - } - - // Update used set size. - usedSetSize += childUsedSetSize; - - Log::Assert(originalSum == (nearSetSize + farSetSize + usedSetSize)); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -size_t CoverTree:: - PruneFarSet(arma::Col& indices, - arma::vec& distances, - const ElemType bound, - const size_t nearSetSize, - const size_t pointSetSize) -{ - // What we are trying to do is remove any points greater than the bound from - // the far set. We don't care what happens to those indices and distances... - // so, we don't need to properly swap points -- just drop new ones in place. - size_t left = nearSetSize; - size_t right = pointSetSize - 1; - while ((distances[left] <= bound) && (left != right)) - ++left; - while ((distances[right] > bound) && (left != right)) - --right; - - while (left != right) - { - // We don't care what happens to the point which should be on the right. - indices[left] = indices[right]; - distances[left] = distances[right]; - --right; // Since we aren't changing the right. - - // Advance to next location which needs to switch. - while ((distances[left] <= bound) && (left != right)) - ++left; - while ((distances[right] > bound) && (left != right)) - --right; - } - - // The far set size is the left pointer, with the near set size subtracted - // from it. - return (left - nearSetSize); -} - -/** - * Take a look at the last child (the most recently created one) and remove any - * implicit nodes that have been created. - */ -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -inline void CoverTree:: - RemoveNewImplicitNodes() -{ - // If we created an implicit node, take its self-child instead (this could - // happen multiple times). - while (children[children.size() - 1]->NumChildren() == 1) - { - CoverTree* old = children[children.size() - 1]; - children.erase(children.begin() + children.size() - 1); - - // Now take its child. - children.push_back(&(old->Child(0))); - - // Set its parent and parameters correctly, and rebuild the statistic. - old->Child(0).Parent() = this; - old->Child(0).ParentDistance() = old->ParentDistance(); - old->Child(0).DistanceComps() = old->DistanceComps(); - old->Child(0).Stat() = StatisticType(old->Child(0)); - - // Remove its child (so it doesn't delete it). - old->Children().erase(old->Children().begin() + old->Children().size() - 1); - - // Now delete it. - delete old; - } -} - -/** - * Default constructor, only for use with boost::serialization. - */ -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -CoverTree::CoverTree() : - dataset(NULL), - point(0), - scale(INT_MIN), - base(0.0), - numDescendants(0), - parent(NULL), - parentDistance(0.0), - furthestDescendantDistance(0.0), - localMetric(false), - localDataset(false), - metric(NULL), - distanceComps(0) -{ - // Nothing to do. -} - -/** - * Serialize to/from a boost::serialization archive. - */ -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -void CoverTree::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // If we're loading, and we have children, they need to be deleted. We may - // also need to delete the local metric and dataset. - if (Archive::is_loading::value) - { - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - - if (localMetric && metric) - delete metric; - if (localDataset && dataset) - delete dataset; - - parent = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(dataset); - ar & BOOST_SERIALIZATION_NVP(point); - ar & BOOST_SERIALIZATION_NVP(scale); - ar & BOOST_SERIALIZATION_NVP(base); - ar & BOOST_SERIALIZATION_NVP(stat); - ar & BOOST_SERIALIZATION_NVP(numDescendants); - - bool hasParent = (parent != NULL); - ar & BOOST_SERIALIZATION_NVP(hasParent); - ar & BOOST_SERIALIZATION_NVP(parentDistance); - ar & BOOST_SERIALIZATION_NVP(furthestDescendantDistance); - ar & BOOST_SERIALIZATION_NVP(metric); - - if (Archive::is_loading::value && !hasParent) - { - localMetric = true; - localDataset = true; - } - - // Lastly, serialize the children. - ar & BOOST_SERIALIZATION_NVP(children); - - if (Archive::is_loading::value && parent == NULL) - { - // Look through each child individually. - for (size_t i = 0; i < children.size(); ++i) - { - children[i]->localMetric = false; - children[i]->localDataset = false; - children[i]->Parent() = this; - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/dual_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/dual_tree_traverser.hpp deleted file mode 100644 index 98a14f5ce..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/dual_tree_traverser.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file dual_tree_traverser.hpp - * @author Ryan Curtin - * - * A dual-tree traverser for the cover tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_DUAL_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_COVER_TREE_DUAL_TREE_TRAVERSER_HPP - -#include -#include - -namespace mlpack { -namespace tree { - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -class CoverTree:: - DualTreeTraverser -{ - public: - /** - * Initialize the dual tree traverser with the given rule type. - */ - DualTreeTraverser(RuleType& rule); - - /** - * Traverse the two specified trees. - * - * @param queryNode Root of query tree. - * @param referenceNode Root of reference tree. - */ - void Traverse(CoverTree& queryNode, CoverTree& referenceNode); - - //! Get the number of pruned nodes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of pruned nodes. - size_t& NumPrunes() { return numPrunes; } - - ///// These are all fake because this is a patch for kd-trees only and I still - ///// want it to compile! - size_t NumVisited() const { return 0; } - size_t NumScores() const { return 0; } - size_t NumBaseCases() const { return 0; } - - private: - //! The instantiated rule set for pruning branches. - RuleType& rule; - - //! The number of pruned nodes. - size_t numPrunes; - - //! Struct used for traversal. - struct DualCoverTreeMapEntry - { - //! The node this entry refers to. - CoverTree* - referenceNode; - //! The score of the node. - double score; - //! The base case. - double baseCase; - //! The traversal info associated with the call to Score() for this entry. - typename RuleType::TraversalInfoType traversalInfo; - - //! Comparison operator, for sorting within the map. - bool operator<(const DualCoverTreeMapEntry& other) const - { - if (score == other.score) - return (baseCase < other.baseCase); - else - return (score < other.score); - } - }; - - /** - * Helper function for traversal of the two trees. - */ - void Traverse(CoverTree& queryNode, - std::map >& - referenceMap); - - //! Prepare map for recursion. - void PruneMap(CoverTree& queryNode, - std::map >& - referenceMap, - std::map >& - childMap); - - void ReferenceRecursion(CoverTree& queryNode, - std::map >& - referenceMap); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "dual_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/dual_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/dual_tree_traverser_impl.hpp deleted file mode 100644 index 692ec9d59..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/dual_tree_traverser_impl.hpp +++ /dev/null @@ -1,360 +0,0 @@ -/** - * @file dual_tree_traverser_impl.hpp - * @author Ryan Curtin - * - * A dual-tree traverser for the cover tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_DUAL_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_COVER_TREE_DUAL_TREE_TRAVERSER_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace tree { - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -CoverTree:: -DualTreeTraverser::DualTreeTraverser(RuleType& rule) : - rule(rule), - numPrunes(0) -{ /* Nothing to do. */ } - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -void CoverTree:: -DualTreeTraverser::Traverse(CoverTree& queryNode, - CoverTree& referenceNode) -{ - // Start by creating a map and adding the reference root node to it. - std::map > refMap; - - DualCoverTreeMapEntry rootRefEntry; - - rootRefEntry.referenceNode = &referenceNode; - - // Perform the evaluation between the roots of either tree. - rootRefEntry.score = rule.Score(queryNode, referenceNode); - rootRefEntry.baseCase = rule.BaseCase(queryNode.Point(), - referenceNode.Point()); - rootRefEntry.traversalInfo = rule.TraversalInfo(); - - refMap[referenceNode.Scale()].push_back(rootRefEntry); - - Traverse(queryNode, refMap); -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -void CoverTree:: -DualTreeTraverser::Traverse( - CoverTree& queryNode, - std::map >& referenceMap) -{ - if (referenceMap.size() == 0) - return; // Nothing to do! - - // First recurse down the reference nodes as necessary. - ReferenceRecursion(queryNode, referenceMap); - - // Did the map get emptied? - if (referenceMap.size() == 0) - return; // Nothing to do! - - // Now, reduce the scale of the query node by recursing. But we can't recurse - // if the query node is a leaf node. - if ((queryNode.Scale() != INT_MIN) && - (queryNode.Scale() >= (*referenceMap.rbegin()).first)) - { - // Recurse into the non-self-children first. The recursion order cannot - // affect the runtime of the algorithm, because each query child recursion's - // results are separate and independent. I don't think this is true in - // every case, and we may have to modify this section to consider scores in - // the future. - for (size_t i = 1; i < queryNode.NumChildren(); ++i) - { - // We need a copy of the map for this child. - std::map > childMap; - PruneMap(queryNode.Child(i), referenceMap, childMap); - Traverse(queryNode.Child(i), childMap); - } - std::map > selfChildMap; - PruneMap(queryNode.Child(0), referenceMap, selfChildMap); - Traverse(queryNode.Child(0), selfChildMap); - } - - if (queryNode.Scale() != INT_MIN) - return; // No need to evaluate base cases at this level. It's all done. - - // If we have made it this far, all we have is a bunch of base case - // evaluations to do. - Log::Assert((*referenceMap.begin()).first == INT_MIN); - Log::Assert(queryNode.Scale() == INT_MIN); - std::vector& pointVector = - (*referenceMap.begin()).second; - - for (size_t i = 0; i < pointVector.size(); ++i) - { - // Get a reference to the frame. - const DualCoverTreeMapEntry& frame = pointVector[i]; - - CoverTree* refNode = frame.referenceNode; - - // If the point is the same as both parents, then we have already done this - // base case. - if ((refNode->Point() == refNode->Parent()->Point()) && - (queryNode.Point() == queryNode.Parent()->Point())) - { - ++numPrunes; - continue; - } - - // Score the node, to see if we can prune it, after restoring the traversal - // info. - rule.TraversalInfo() = frame.traversalInfo; - double score = rule.Score(queryNode, *refNode); - - if (score == DBL_MAX) - { - ++numPrunes; - continue; - } - - // If not, compute the base case. - rule.BaseCase(queryNode.Point(), pointVector[i].referenceNode->Point()); - } -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -void CoverTree:: -DualTreeTraverser::PruneMap( - CoverTree& queryNode, - std::map >& referenceMap, - std::map >& childMap) -{ - if (referenceMap.empty()) - return; // Nothing to do. - - // Copy the zero set first. - if ((*referenceMap.begin()).first == INT_MIN) - { - // Get a reference to the vector representing the entries at this scale. - std::vector& scaleVector = - (*referenceMap.begin()).second; - - // Before traversing all the points in this scale, sort by score. - std::sort(scaleVector.begin(), scaleVector.end()); - - const int thisScale = (*referenceMap.begin()).first; - childMap[thisScale].reserve(scaleVector.size()); - std::vector& newScaleVector = childMap[thisScale]; - - // Loop over each entry in the vector. - for (size_t j = 0; j < scaleVector.size(); ++j) - { - const DualCoverTreeMapEntry& frame = scaleVector[j]; - - // First evaluate if we can prune without performing the base case. - CoverTree* refNode = frame.referenceNode; - - // Perform the actual scoring, after restoring the traversal info. - rule.TraversalInfo() = frame.traversalInfo; - double score = rule.Score(queryNode, *refNode); - - if (score == DBL_MAX) - { - // Pruned. Move on. - ++numPrunes; - continue; - } - - // If it isn't pruned, we must evaluate the base case. - const double baseCase = rule.BaseCase(queryNode.Point(), - refNode->Point()); - - // Add to child map. - newScaleVector.push_back(frame); - newScaleVector.back().score = score; - newScaleVector.back().baseCase = baseCase; - newScaleVector.back().traversalInfo = rule.TraversalInfo(); - } - - // If we didn't add anything, then strike this vector from the map. - if (newScaleVector.size() == 0) - childMap.erase((*referenceMap.begin()).first); - } - - typename std::map >::reverse_iterator - it = referenceMap.rbegin(); - - while ((it != referenceMap.rend())) - { - const int thisScale = (*it).first; - if (thisScale == INT_MIN) // We already did it. - break; - - // Get a reference to the vector representing the entries at this scale. - std::vector& scaleVector = (*it).second; - - // Before traversing all the points in this scale, sort by score. - std::sort(scaleVector.begin(), scaleVector.end()); - - childMap[thisScale].reserve(scaleVector.size()); - std::vector& newScaleVector = childMap[thisScale]; - - // Loop over each entry in the vector. - for (size_t j = 0; j < scaleVector.size(); ++j) - { - const DualCoverTreeMapEntry& frame = scaleVector[j]; - - // First evaluate if we can prune without performing the base case. - CoverTree* refNode = frame.referenceNode; - - // Perform the actual scoring, after restoring the traversal info. - rule.TraversalInfo() = frame.traversalInfo; - double score = rule.Score(queryNode, *refNode); - - if (score == DBL_MAX) - { - // Pruned. Move on. - ++numPrunes; - continue; - } - - // If it isn't pruned, we must evaluate the base case. - const double baseCase = rule.BaseCase(queryNode.Point(), - refNode->Point()); - - // Add to child map. - newScaleVector.push_back(frame); - newScaleVector.back().score = score; - newScaleVector.back().baseCase = baseCase; - newScaleVector.back().traversalInfo = rule.TraversalInfo(); - } - - // If we didn't add anything, then strike this vector from the map. - if (newScaleVector.size() == 0) - childMap.erase((*it).first); - - ++it; // Advance to next scale. - } -} - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -void CoverTree:: -DualTreeTraverser::ReferenceRecursion( - CoverTree& queryNode, - std::map >& referenceMap) -{ - // First, reduce the maximum scale in the reference map down to the scale of - // the query node. - while (!referenceMap.empty()) - { - // Hacky bullshit to imitate jl cover tree. - if (queryNode.Parent() == NULL && (*referenceMap.rbegin()).first < - queryNode.Scale()) - break; - if (queryNode.Parent() != NULL && (*referenceMap.rbegin()).first <= - queryNode.Scale()) - break; - // If the query node's scale is INT_MIN and the reference map's maximum - // scale is INT_MIN, don't try to recurse... - if ((queryNode.Scale() == INT_MIN) && - ((*referenceMap.rbegin()).first == INT_MIN)) - break; - - // Get a reference to the current largest scale. - std::vector& scaleVector = - (*referenceMap.rbegin()).second; - - // Before traversing all the points in this scale, sort by score. - std::sort(scaleVector.begin(), scaleVector.end()); - - // Now loop over each element. - for (size_t i = 0; i < scaleVector.size(); ++i) - { - // Get a reference to the current element. - const DualCoverTreeMapEntry& frame = scaleVector.at(i); - - CoverTree* refNode = frame.referenceNode; - - // Create the score for the children. - double score = rule.Rescore(queryNode, *refNode, frame.score); - - // Now if this childScore is DBL_MAX we can prune all children. In this - // recursion setup pruning is all or nothing for children. - if (score == DBL_MAX) - { - ++numPrunes; - continue; - } - - // If it is not pruned, we must evaluate the base case. - - // Add the children. - for (size_t j = 0; j < refNode->NumChildren(); ++j) - { - rule.TraversalInfo() = frame.traversalInfo; - double childScore = rule.Score(queryNode, refNode->Child(j)); - if (childScore == DBL_MAX) - { - ++numPrunes; - continue; - } - - // It wasn't pruned; evaluate the base case. - const double baseCase = rule.BaseCase(queryNode.Point(), - refNode->Child(j).Point()); - - DualCoverTreeMapEntry newFrame; - newFrame.referenceNode = &refNode->Child(j); - newFrame.score = childScore; // Use the score of the parent. - newFrame.baseCase = baseCase; - newFrame.traversalInfo = rule.TraversalInfo(); - - referenceMap[newFrame.referenceNode->Scale()].push_back(newFrame); - } - } - - // Now clear the memory for this scale; it isn't needed anymore. - referenceMap.erase((*referenceMap.rbegin()).first); - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/first_point_is_root.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/first_point_is_root.hpp deleted file mode 100644 index 3e377070f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/first_point_is_root.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @file first_point_is_root.hpp - * @author Ryan Curtin - * - * A very simple policy for the cover tree; the first point in the dataset is - * chosen as the root of the cover tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_FIRST_POINT_IS_ROOT_HPP -#define MLPACK_CORE_TREE_FIRST_POINT_IS_ROOT_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * This class is meant to be used as a choice for the policy class - * RootPointPolicy of the CoverTree class. This policy determines which point - * is used for the root node of the cover tree. This particular implementation - * simply chooses the first point in the dataset as the root. A more complex - * implementation might choose, for instance, the point with least maximum - * distance to other points (the closest to the "middle"). - */ -class FirstPointIsRoot -{ - public: - /** - * Return the point to be used as the root point of the cover tree. This just - * returns 0. - */ - template - static size_t ChooseRoot(const MatType& /* dataset */) { return 0; } -}; - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_FIRST_POINT_IS_ROOT_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/single_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/single_tree_traverser.hpp deleted file mode 100644 index 2411f55d8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/single_tree_traverser.hpp +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @file single_tree_traverser.hpp - * @author Ryan Curtin - * - * Defines the SingleTreeTraverser for the cover tree. This implements a - * single-tree breadth-first recursion with a pruning rule and a base case (two - * point) rule. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_SINGLE_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_COVER_TREE_SINGLE_TREE_TRAVERSER_HPP - -#include - -#include "cover_tree.hpp" - -namespace mlpack { -namespace tree { - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -class CoverTree:: - SingleTreeTraverser -{ - public: - /** - * Initialize the single tree traverser with the given rule. - */ - SingleTreeTraverser(RuleType& rule); - - /** - * Traverse the tree with the given point. - * - * @param queryIndex The index of the point in the query set which is used as - * the query point. - * @param referenceNode The tree node to be traversed. - */ - void Traverse(const size_t queryIndex, CoverTree& referenceNode); - - //! Get the number of prunes so far. - size_t NumPrunes() const { return numPrunes; } - //! Set the number of prunes (good for a reset to 0). - size_t& NumPrunes() { return numPrunes; } - - private: - //! Reference to the rules with which the tree will be traversed. - RuleType& rule; - - //! The number of nodes which have been pruned during traversal. - size_t numPrunes; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "single_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/single_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/single_tree_traverser_impl.hpp deleted file mode 100644 index 46b39001d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/single_tree_traverser_impl.hpp +++ /dev/null @@ -1,241 +0,0 @@ -/** - * @file single_tree_traverser_impl.hpp - * @author Ryan Curtin - * - * Implementation of the single tree traverser for cover trees, which implements - * a breadth-first traversal. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_SINGLE_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_COVER_TREE_SINGLE_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "single_tree_traverser.hpp" - -#include - -namespace mlpack { -namespace tree { - -//! This is the structure the cover tree map will use for traversal. -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -struct CoverTreeMapEntry -{ - //! The node this entry refers to. - CoverTree* node; - //! The score of the node. - double score; - //! The index of the parent node. - size_t parent; - //! The base case evaluation. - double baseCase; - - //! Comparison operator. - bool operator<(const CoverTreeMapEntry& other) const - { - return (score < other.score); - } -}; - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -CoverTree:: -SingleTreeTraverser::SingleTreeTraverser(RuleType& rule) : - rule(rule), - numPrunes(0) -{ /* Nothing to do. */ } - -template< - typename MetricType, - typename StatisticType, - typename MatType, - typename RootPointPolicy -> -template -void CoverTree:: -SingleTreeTraverser::Traverse( - const size_t queryIndex, - CoverTree& referenceNode) -{ - // This is a non-recursive implementation (which should be faster than a - // recursive implementation). - typedef CoverTreeMapEntry - MapEntryType; - - // We will use this map as a priority queue. Each key represents the scale, - // and then the vector is all the nodes in that scale which need to be - // investigated. Because no point in a scale can add a point in its own - // scale, we know that the vector for each scale is final when we get to it. - // In addition, map is organized in such a way that rbegin() will return the - // largest scale. - std::map > mapQueue; - - // Create the score for the children. - double rootChildScore = rule.Score(queryIndex, referenceNode); - - if (rootChildScore == DBL_MAX) - { - numPrunes += referenceNode.NumChildren(); - } - else - { - // Manually add the children of the first node. - // Often, a ruleset will return without doing any computation on cover trees - // using TreeTraits::FirstPointIsCentroid; this is an optimization that - // (theoretically) the compiler should get right. - double rootBaseCase = rule.BaseCase(queryIndex, referenceNode.Point()); - - // Don't add the self-leaf. - size_t i = 0; - if (referenceNode.Child(0).NumChildren() == 0) - { - ++numPrunes; - i = 1; - } - - for (/* i was set above. */; i < referenceNode.NumChildren(); ++i) - { - MapEntryType newFrame; - newFrame.node = &referenceNode.Child(i); - newFrame.score = rootChildScore; - newFrame.baseCase = rootBaseCase; - newFrame.parent = referenceNode.Point(); - - // Put it into the map. - mapQueue[newFrame.node->Scale()].push_back(newFrame); - } - } - - // Now begin the iteration through the map, but only if it has anything in it. - if (mapQueue.empty()) - return; - typename std::map >::reverse_iterator rit = - mapQueue.rbegin(); - - // We will treat the leaves differently (below). - while ((*rit).first != INT_MIN) - { - // Get a reference to the current scale. - std::vector& scaleVector = (*rit).second; - - // Before traversing all the points in this scale, sort by score. - std::sort(scaleVector.begin(), scaleVector.end()); - - // Now loop over each element. - for (size_t i = 0; i < scaleVector.size(); ++i) - { - // Get a reference to the current element. - const MapEntryType& frame = scaleVector.at(i); - - CoverTree* node = frame.node; - const double score = frame.score; - const size_t parent = frame.parent; - const size_t point = node->Point(); - double baseCase = frame.baseCase; - - // First we recalculate the score of this node to find if we can prune it. - if (rule.Rescore(queryIndex, *node, score) == DBL_MAX) - { - ++numPrunes; - continue; - } - - // Create the score for the children. - const double childScore = rule.Score(queryIndex, *node); - - // Now if this childScore is DBL_MAX we can prune all children. In this - // recursion setup pruning is all or nothing for children. - if (childScore == DBL_MAX) - { - numPrunes += node->NumChildren(); - continue; - } - - // If we are a self-child, the base case has already been evaluated. - // Often, a ruleset will return without doing any computation on cover - // trees using TreeTraits::FirstPointIsCentroid; this is an optimization - // that (theoretically) the compiler should get right. - if (point != parent) - baseCase = rule.BaseCase(queryIndex, point); - - // Don't add the self-leaf. - size_t j = 0; - if (node->Child(0).NumChildren() == 0) - { - ++numPrunes; - j = 1; - } - - for (/* j is already set. */; j < node->NumChildren(); ++j) - { - MapEntryType newFrame; - newFrame.node = &node->Child(j); - newFrame.score = childScore; - newFrame.baseCase = baseCase; - newFrame.parent = point; - - mapQueue[newFrame.node->Scale()].push_back(newFrame); - } - } - - // Now clear the memory for this scale; it isn't needed anymore. - mapQueue.erase((*rit).first); - } - - // Now deal with the leaves. - for (size_t i = 0; i < mapQueue[INT_MIN].size(); ++i) - { - const MapEntryType& frame = mapQueue[INT_MIN].at(i); - - CoverTree* node = frame.node; - const double score = frame.score; - const size_t point = node->Point(); - - // First, recalculate the score of this node to find if we can prune it. - double rescore = rule.Rescore(queryIndex, *node, score); - - if (rescore == DBL_MAX) - { - ++numPrunes; - continue; - } - - // For this to be a valid dual-tree algorithm, we *must* evaluate the - // combination, even if pruning it will make no difference. It's the - // definition. - const double actualScore = rule.Score(queryIndex, *node); - - if (actualScore == DBL_MAX) - { - ++numPrunes; - continue; - } - else - { - // Evaluate the base case, since the combination was not pruned. - // Often, a ruleset will return without doing any computation on cover - // trees using TreeTraits::FirstPointIsCentroid; this is an optimization - // that (theoretically) the compiler should get right. - rule.BaseCase(queryIndex, point); - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/traits.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/traits.hpp deleted file mode 100644 index a28edc1f1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/traits.hpp +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @file traits.hpp - * @author Ryan Curtin - * - * This file contains the specialization of the TreeTraits class for the - * CoverTree type of tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_TRAITS_HPP -#define MLPACK_CORE_TREE_COVER_TREE_TRAITS_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * The specialization of the TreeTraits class for the CoverTree tree type. It - * defines characteristics of the cover tree, and is used to help write - * tree-independent (but still optimized) tree-based algorithms. See - * mlpack/core/tree/tree_traits.hpp for more information. - */ -template -class TreeTraits> -{ - public: - /** - * The cover tree (or, this implementation of it) does not require that - * children represent non-overlapping subsets of the parent node. - */ - static const bool HasOverlappingChildren = true; - - /** - * Cover trees do have self-children, so points can be included in more than - * one node. - */ - static const bool HasDuplicatedPoints = true; - - /** - * Each cover tree node contains only one point, and that point is its - * centroid. - */ - static const bool FirstPointIsCentroid = true; - - /** - * Cover trees do have self-children. - */ - static const bool HasSelfChildren = true; - - /** - * Points are not rearranged when the tree is built. - */ - static const bool RearrangesDataset = false; - - /** - * The cover tree is not necessarily a binary tree. - */ - static const bool BinaryTree = false; - - /** - * NumDescendants() represents the number of unique descendant points. - */ - static const bool UniqueNumDescendants = true; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/typedef.hpp b/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/typedef.hpp deleted file mode 100644 index cbf54532f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/cover_tree/typedef.hpp +++ /dev/null @@ -1,47 +0,0 @@ -/** - * @file typedef.hpp - * @author Ryan Curtin - * - * Typedef of cover tree to match TreeType API. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_COVER_TREE_TYPEDEF_HPP -#define MLPACK_CORE_TREE_COVER_TREE_TYPEDEF_HPP - -#include "cover_tree.hpp" - -namespace mlpack { -namespace tree { - -/** - * The standard cover tree, as detailed in the original cover tree paper: - * - * @code - * @inproceedings{ - * author={Beygelzimer, A. and Kakade, S. and Langford, J.}, - * title={Cover trees for nearest neighbor}, - * booktitle={Proceedings of the 23rd International Conference on Machine - * Learning (ICML 2006)}, - * pages={97--104}, - * year={2006} - * } - * @endcode - * - * This template typedef satisfies the requirements of the TreeType API. - * - * @see @ref trees, CoverTree - */ -template -using StandardCoverTree = CoverTree; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/enumerate_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/enumerate_tree.hpp deleted file mode 100644 index 8811c8f4c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/enumerate_tree.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @file enumerate_tree.hpp - * @author Ivan (Jonan) Georgiev - * - * This file contains function that performs a simple depth-first walk on the tree - * calling `Enter` and `Leave` methods of a provided walker. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_ENUMERATE_TREE_HPP -#define MLPACK_CORE_TREE_ENUMERATE_TREE_HPP - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { -namespace enumerate { - -// Actual implementation of the enumeration. The problem is the unified -// detection if we're on the root, because Enter and Leave expect the -// parent being passed. -template -void EnumerateTreeImpl(TreeType* tree, Walker& walker, bool root) -{ - if (root) - walker.Enter(tree, (const TreeType*)nullptr); - - const size_t numChildren = tree->NumChildren(); - for (size_t i = 0; i < numChildren; ++i) - { - TreeType* child = tree->ChildPtr(i); - walker.Enter(child, tree); - EnumerateTreeImpl(child, walker, false); - walker.Leave(child, tree); - } - - if (root) - walker.Leave(tree, (const TreeType*)nullptr); -} - -} // namespace enumerate - - -/** - * Traverses all nodes of the tree, including the inner ones. On each node - * two methods of the `enumer` are called: - * - * Enter(TreeType* node, TreeType* parent); - * Leave(TreeType* node, TreeType* parent); - * - * @param walker An instance of custom class, receiver of the enumeration. - */ -template -inline void EnumerateTree(TreeType* tree, Walker& walker) -{ - enumerate::EnumerateTreeImpl(tree, walker, true); -} - -} // namespace tree -} // namespace mlpack - - -#endif // MLPACK_CORE_TREE_ENUMERATE_TREE_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/example_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/example_tree.hpp deleted file mode 100644 index f2a5eebce..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/example_tree.hpp +++ /dev/null @@ -1,240 +0,0 @@ -/** - * @file example_tree.hpp - * @author Ryan Curtin - * - * An example tree. This contains all the functions that mlpack trees must - * implement (although the actual implementations here don't make any sense - * because this is just an example). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_EXAMPLE_TREE_HPP -#define MLPACK_CORE_TREE_EXAMPLE_TREE_HPP - -namespace mlpack { -namespace tree { - -/** - * This is not an actual space tree but instead an example tree that exists to - * show and document all the functions that mlpack trees must implement. For a - * better overview of trees, see @ref trees. Also be aware that the - * implementations of each of the methods in this example tree are entirely fake - * and do not work; this example tree exists for its API, not its - * implementation. - * - * Note that trees often have different properties. These properties are known - * at compile-time through the mlpack::tree::TreeTraits class, and some - * properties may imply the existence (or non-existence) of certain functions. - * Refer to the TreeTraits for more documentation on that. - * - * The three template parameters below must be template parameters to the tree, - * in the order given below. More template parameters are fine, but they must - * come after the first three. - * - * @tparam MetricType This defines the space in which the tree will be built. - * For some trees, arbitrary metrics cannot be used, and a template - * metaprogramming approach should be used to issue a compile-time error if - * a metric cannot be used with a specific tree type. One example is the - * tree::BinarySpaceTree tree type, which cannot work with the - * metric::IPMetric class. - * @tparam StatisticType A tree node can hold a statistic, which is sometimes - * useful for various dual-tree algorithms. The tree itself does not need - * to know anything about how the statistic works, but it needs to hold a - * StatisticType in each node. It can be assumed that the StatisticType - * class has a constructor StatisticType(const ExampleTree&). - * @tparam MatType A tree could be built on a dense matrix or a sparse matrix. - * All mlpack trees should be able to support any Armadillo-compatible - * matrix type. When the tree is written it should be assumed that MatType - * has the same functionality as arma::mat. - */ -template, - typename StatisticType = EmptyStatistic, - typename MatType = arma::mat> -class ExampleTree -{ - public: - /** - * This constructor will build the tree given a dataset and an instantiated - * metric. Note that the parameter is a MatType& and not an arma::mat&. The - * dataset is not modified by the tree-building process (if it is, see the - * documentation for mlpack::tree::TreeTraits::RearrangesDataset for how to - * deal with that situation). The MetricType parameter is necessary even - * though some metrics do not hold any state. This is so that the tree does - * not have to worry about instantiating the metric (if the tree had to worry - * about this, this would almost certainly incur additional runtime complexity - * and a larger runtime size of the tree node objects, which is to be - * avoided). The metric can't be const, in case MetricType::Evaluate() is - * non-const. - * - * When this constructor is finished, the entire tree will be built and ready - * to use. The constructor should call the constructor of the statistic for - * each node that is built (see tree::EmptyStatistic for more information). - * - * @param dataset The dataset that the tree will be built on. - * @param metric The instantiated metric to use to build the dataset. - */ - ExampleTree(const MatType& dataset, - MetricType& metric); - - //! Return the number of children of this node. - size_t NumChildren() const; - - //! Return a particular child of this node. - const ExampleTree& Child(const size_t i) const; - //! Modify a particular child of this node. - ExampleTree& Child(const size_t i); - - //! Return the parent node (NULL if this is the root of the tree). - ExampleTree* Parent() const; - - //! Return the number of points held in this node. - size_t NumPoints() const; - - /** - * Return the index of a particular point of this node. mlpack trees do not, - * in general, hold the actual dataset, and instead just hold the indices of - * the points they contain. Thus, you might use this function in code like - * this: - * - * @code - * arma::vec thirdPoint = dataset.col(treeNode.Point(2)); - * @endcode - */ - size_t Point(const size_t i) const; - - /** - * Get the number of descendant points. This is the number of unique points - * held in this node plus the number of points held in all descendant nodes. - * This could be calculated at build-time and cached, or could be calculated - * at run-time. This may be harder to calculate for trees that may hold - * points in multiple nodes (like cover trees and spill trees, for instance). - */ - size_t NumDescendants() const; - - /** - * Get the index of a particular descendant point. The ordering of the - * descendants does not matter, as long as calling Descendant(0) through - * Descendant(NumDescendants() - 1) will return the indices of every - * unique descendant point of the node. - */ - size_t Descendant(const size_t i) const; - - //! Get the statistic for this node. - const StatisticType& Stat() const; - //! Modify the statistic for this node. - StatisticType& Stat(); - - //! Get the instantiated metric for this node. - const MetricType& Metric() const; - //! Modify the instantiated metric for this node. - MetricType& Metric(); - - /** - * Return the minimum distance between this node and a point. It is not - * required that the exact minimum distance between the node and the point is - * returned but instead a lower bound on the minimum distance will suffice. - * See the definitions in @ref trees for more information. - * - * @param point Point to return [lower bound on] minimum distance to. - */ - double MinDistance(const MatType& point) const; - - /** - * Return the minimum distance between this node and another node. It is not - * required that the exact minimum distance between the two nodes be returned - * but instead a lower bound on the minimum distance will suffice. See the - * definitions in @ref trees for more information. - * - * @param node Node to return [lower bound on] minimum distance to. - */ - double MinDistance(const ExampleTree& other) const; - - /** - * Return the maximum distance between this node and a point. It is not - * required that the exact maximum distance between the node and the point is - * returned but instead an upper bound on the maximum distance will suffice. - * See the definitions in @ref trees for more information. - * - * @param point Point to return [upper bound on] maximum distance to. - */ - double MaxDistance(const MatType& point) const; - - /** - * Return the maximum distance between this node and another node. It is not - * required that the exact maximum distance between the two nodes be returned - * but instead an upper bound on the maximum distance will suffice. See the - * definitions in @ref trees for more information. - * - * @param node Node to return [upper bound on] maximum distance to. - */ - double MaxDistance(const ExampleTree& other) const; - - /** - * Return both the minimum and maximum distances between this node and a point - * as a math::Range object. This overload is given because it is possible - * that, for some tree types, calculation of both at once is faster than a - * call to MinDistance() then MaxDistance(). It is not necessary that the - * minimum and maximum distances be exact; it is sufficient to return a lower - * bound on the minimum distance and an upper bound on the maximum distance. - * See the definitions in @ref trees for more information. - * - * @param point Point to return [bounds on] minimum and maximum distances to. - */ - math::Range RangeDistance(const MatType& point) const; - - /** - * Return both the minimum and maximum distances between this node and another - * node as a math::Range object. This overload is given because it is - * possible that, for some tree types, calculation of both at once is faster - * than a call to MinDistance() then MaxDistance(). It is not necessary that - * the minimum and maximum distances be exact; it is sufficient to return a - * lower bound on the minimum distance and an upper bound on the maximum - * distance. See the definitions in @ref trees for more information. - * - * @param node Node to return [bounds on] minimum and maximum distances to. - */ - math::Range RangeDistance(const ExampleTree& other) const; - - /** - * Fill the given vector with the center of the node. - * - * @param centroid Vector to be filled with the center of the node. - */ - void Centroid(arma::vec& centroid) const; - - /** - * Get the distance from the center of the node to the furthest descendant - * point of this node. This does not necessarily need to be the exact - * furthest descendant distance but instead can be an upper bound. See the - * definitions in @ref trees for more information. - */ - double FurthestDescendantDistance() const; - - /** - * Get the distance from the center of this node to the center of the parent - * node. - */ - double ParentDistance() const; - - private: - //! This member is just here so the ExampleTree compiles without warnings. It - //! is not required to be a member in every type of tree. - StatisticType stat; - - /** - * This member is just here so the ExampleTree compiles without warnings. It - * is not required to be a member in every type of tree. Be aware that - * storing the metric as a member and not a reference may mean that for some - * metrics (such as metric::MahalanobisDistance in high dimensionality) may - * incur lots of unnecessary matrix copying. - */ - MetricType& metric; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/greedy_single_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/greedy_single_tree_traverser.hpp deleted file mode 100644 index 33034c3c0..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/greedy_single_tree_traverser.hpp +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @file greedy_single_tree_traverser_impl.hpp - * @author Marcos Pividori - * - * A simple greedy traverser which always chooses the child with the best score - * and doesn't do backtracking. The RuleType class must implement the method - * 'GetBestChild()'. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_GREEDY_SINGLE_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_GREEDY_SINGLE_TREE_TRAVERSER_HPP - -#include - -namespace mlpack { -namespace tree { - -template -class GreedySingleTreeTraverser -{ - public: - /** - * Instantiate the greedy single tree traverser with the given rule set. - */ - GreedySingleTreeTraverser(RuleType& rule); - - /** - * Traverse the tree with the given point. - * - * @param queryIndex The index of the point in the query set which is being - * used as the query point. - * @param referenceNode The tree node to be traversed. - */ - void Traverse(const size_t queryIndex, TreeType& referenceNode); - - //! Get the number of prunes. - size_t NumPrunes() const { return numPrunes; } - - //! Set value of minBaseCases. - size_t& MinBaseCases() { return minBaseCases; } - - //! Get value of minBaseCases. - size_t MinBaseCases() const { return minBaseCases; } - - private: - //! Reference to the rules with which the tree will be traversed. - RuleType& rule; - - //! The number of nodes which have been pruned during traversal. - size_t numPrunes; - - //! The number of base cases required. For example the number of nearest - //! neighbours(k) in case of knn. - size_t minBaseCases; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "greedy_single_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/greedy_single_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/greedy_single_tree_traverser_impl.hpp deleted file mode 100644 index d6392db02..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/greedy_single_tree_traverser_impl.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file greedy_single_tree_traverser_impl.hpp - * @author Marcos Pividori - * - * A simple greedy traverser which always chooses the child with the best score - * and doesn't do backtracking. The RuleType class must implement the method - * 'GetBestChild()'. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_GREEDY_SINGLE_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_GREEDY_SINGLE_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "greedy_single_tree_traverser.hpp" - -namespace mlpack { -namespace tree { - -template -GreedySingleTreeTraverser::GreedySingleTreeTraverser( - RuleType& rule) : - rule(rule), - numPrunes(0), - minBaseCases(0) -{ /* Nothing to do. */ } - -template -void GreedySingleTreeTraverser::Traverse( - const size_t queryIndex, - TreeType& referenceNode) -{ - // Run the base case as necessary for all the points in the reference node. - for (size_t i = 0; i < referenceNode.NumPoints(); ++i) - rule.BaseCase(queryIndex, referenceNode.Point(i)); - - size_t bestChild = rule.GetBestChild(queryIndex, referenceNode); - size_t numDescendants; - - // Check that referencenode is not a leaf node while calculating number of - // descendants of it's best child. - if (!referenceNode.IsLeaf()) - numDescendants = referenceNode.Child(bestChild).NumDescendants(); - else - numDescendants = referenceNode.NumPoints(); - - // If number of descendants are more than minBaseCases than we can go along - // with best child otherwise we need to traverse for each descendant to - // ensure that we calculate at least minBaseCases number of base cases. - if (!referenceNode.IsLeaf()) - { - if (numDescendants > minBaseCases) - { - // We are prunning all but one child. - numPrunes += referenceNode.NumChildren() - 1; - // Recurse the best child. - Traverse(queryIndex, referenceNode.Child(bestChild)); - } - else - { - // Run the base case over first minBaseCases number of descendants. - for (size_t i = 0; i <= minBaseCases; ++i) - rule.BaseCase(queryIndex, referenceNode.Descendant(i)); - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/hollow_ball_bound.hpp b/src/sdk/mlpack/include/mlpack/core/tree/hollow_ball_bound.hpp deleted file mode 100644 index 9c6e210e2..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/hollow_ball_bound.hpp +++ /dev/null @@ -1,233 +0,0 @@ -/** - * @file hollow_ball_bound.hpp - * - * Bounds that are useful for binary space partitioning trees. - * Interface to a ball bound that works in arbitrary metric spaces. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_HOLLOW_BALL_BOUND_HPP -#define MLPACK_CORE_TREE_HOLLOW_BALL_BOUND_HPP - -#include -#include -#include "bound_traits.hpp" - -namespace mlpack { -namespace bound { - -/** - * Hollow ball bound encloses a set of points at a specific distance (radius) - * from a specific point (center) except points at a specific distance from - * another point (the center of the hole). MetricType is the custom metric type - * that defaults to the Euclidean (L2) distance. - * - * @tparam TMetricType metric type used in the distance measure. - * @tparam ElemType Type of element (float or double or similar). - */ -template, - typename ElemType = double> -class HollowBallBound -{ - public: - //! A public version of the metric type. - typedef TMetricType MetricType; - - private: - //! The inner and the outer radii of the bound. - math::RangeType radii; - //! The center of the ball bound. - arma::Col center; - //! The center of the hollow. - arma::Col hollowCenter; - //! The metric used in this bound. - MetricType* metric; - - /** - * To know whether this object allocated memory to the metric member - * variable. This will be true except in the copy constructor and the - * overloaded assignment operator. We need this to know whether we should - * delete the metric member variable in the destructor. - */ - bool ownsMetric; - - public: - //! Empty Constructor. - HollowBallBound(); - - /** - * Create the ball bound with the specified dimensionality. - * - * @param dimension Dimensionality of ball bound. - */ - HollowBallBound(const size_t dimension); - - /** - * Create the ball bound with the specified radius and center. - * - * @param innerRadius Inner radius of ball bound. - * @param outerRadius Outer radius of ball bound. - * @param center Center of ball bound. - */ - template - HollowBallBound(const ElemType innerRadius, - const ElemType outerRadius, - const VecType& center); - - //! Copy constructor. To prevent memory leaks. - HollowBallBound(const HollowBallBound& other); - - //! For the same reason as the copy constructor: to prevent memory leaks. - HollowBallBound& operator=(const HollowBallBound& other); - - //! Move constructor: take possession of another bound. - HollowBallBound(HollowBallBound&& other); - - //! Destructor to release allocated memory. - ~HollowBallBound(); - - //! Get the outer radius of the ball. - ElemType OuterRadius() const { return radii.Hi(); } - //! Modify the outer radius of the ball. - ElemType& OuterRadius() { return radii.Hi(); } - - //! Get the innner radius of the ball. - ElemType InnerRadius() const { return radii.Lo(); } - //! Modify the inner radius of the ball. - ElemType& InnerRadius() { return radii.Lo(); } - - //! Get the center point of the ball. - const arma::Col& Center() const { return center; } - //! Modify the center point of the ball. - arma::Col& Center() { return center; } - - //! Get the center point of the hollow. - const arma::Col& HollowCenter() const { return hollowCenter; } - //! Modify the center point of the hollow. - arma::Col& HollowCenter() { return hollowCenter; } - - //! Get the dimensionality of the ball. - size_t Dim() const { return center.n_elem; } - - /** - * Get the minimum width of the bound (this is same as the diameter). - * For ball bounds, width along all dimensions remain same. - */ - ElemType MinWidth() const { return radii.Hi() * 2.0; } - - //! Get the range in a certain dimension. - math::RangeType operator[](const size_t i) const; - - /** - * Determines if a point is within this bound. - */ - template - bool Contains(const VecType& point) const; - - /** - * Determines if another bound is within this bound. - */ - bool Contains(const HollowBallBound& other) const; - - /** - * Place the center of BallBound into the given vector. - * - * @param center Vector which the centroid will be written to. - */ - template - void Center(VecType& center) const { center = this->center; } - - /** - * Calculates minimum bound-to-point squared distance. - */ - template - ElemType MinDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const; - - /** - * Calculates minimum bound-to-bound squared distance. - */ - ElemType MinDistance(const HollowBallBound& other) const; - - /** - * Computes maximum distance. - */ - template - ElemType MaxDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const; - - /** - * Computes maximum distance. - */ - ElemType MaxDistance(const HollowBallBound& other) const; - - /** - * Calculates minimum and maximum bound-to-point distance. - */ - template - math::RangeType RangeDistance( - const VecType& other, - typename std::enable_if_t::value>* = 0) const; - - /** - * Calculates minimum and maximum bound-to-bound distance. - * - * Example: bound1.MinDistanceSq(other) for minimum distance. - */ - math::RangeType RangeDistance(const HollowBallBound& other) const; - - /** - * Expand the bound to include the given point. The centroid will not be - * moved. - * - * @tparam MatType Type of matrix; could be arma::mat, arma::spmat, or a - * vector. - * @tparam data Data points to add. - */ - template - const HollowBallBound& operator|=(const MatType& data); - - /** - * Expand the bound to include the given bound. The centroid will not be - * moved. - * - * @tparam MatType Type of matrix; could be arma::mat, arma::spmat, or a - * vector. - * @tparam data Data points to add. - */ - const HollowBallBound& operator|=(const HollowBallBound& other); - - /** - * Returns the diameter of the ballbound. - */ - ElemType Diameter() const { return 2 * radii.Hi(); } - - //! Returns the distance metric used in this bound. - const MetricType& Metric() const { return *metric; } - //! Modify the distance metric used in this bound. - MetricType& Metric() { return *metric; } - - //! Serialize the bound. - template - void serialize(Archive& ar, const unsigned int version); -}; - -//! A specialization of BoundTraits for this bound type. -template -struct BoundTraits> -{ - //! These bounds are potentially loose in some dimensions. - const static bool HasTightBounds = false; -}; - -} // namespace bound -} // namespace mlpack - -#include "hollow_ball_bound_impl.hpp" - -#endif // MLPACK_CORE_TREE_HOLLOW_BALL_BOUND_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/hollow_ball_bound_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/hollow_ball_bound_impl.hpp deleted file mode 100644 index e6d9737ee..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/hollow_ball_bound_impl.hpp +++ /dev/null @@ -1,447 +0,0 @@ -/** - * @file hollow_ball_bound_impl.hpp - * - * Bounds that are useful for binary space partitioning trees. - * Implementation of HollowBallBound ball bound metric policy class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_HOLLOW_BALL_BOUND_IMPL_HPP -#define MLPACK_CORE_TREE_HOLLOW_BALL_BOUND_IMPL_HPP - -// In case it hasn't been included already. -#include "hollow_ball_bound.hpp" - -namespace mlpack { -namespace bound { - -//! Empty Constructor. -template -HollowBallBound::HollowBallBound() : - radii(std::numeric_limits::lowest(), - std::numeric_limits::lowest()), - metric(new MetricType()), - ownsMetric(true) -{ /* Nothing to do. */ } - -/** - * Create the hollow ball bound with the specified dimensionality. - * - * @param dimension Dimensionality of ball bound. - */ -template -HollowBallBound:: -HollowBallBound(const size_t dimension) : - radii(std::numeric_limits::lowest(), - std::numeric_limits::lowest()), - center(dimension), - hollowCenter(dimension), - metric(new MetricType()), - ownsMetric(true) -{ /* Nothing to do. */ } - -/** - * Create the hollow ball bound with the specified radii and center. - * - * @param innerRadius Inner radius of hollow ball bound. - * @param outerRadius Outer radius of hollow ball bound. - * @param center Center of hollow ball bound. - */ -template -template -HollowBallBound:: -HollowBallBound(const ElemType innerRadius, - const ElemType outerRadius, - const VecType& center) : - radii(innerRadius, - outerRadius), - center(center), - hollowCenter(center), - metric(new MetricType()), - ownsMetric(true) -{ /* Nothing to do. */ } - -//! Copy Constructor. To prevent memory leaks. -template -HollowBallBound::HollowBallBound( - const HollowBallBound& other) : - radii(other.radii), - center(other.center), - hollowCenter(other.hollowCenter), - metric(other.metric), - ownsMetric(false) -{ /* Nothing to do. */ } - -//! For the same reason as the copy constructor: to prevent memory leaks. -template -HollowBallBound& HollowBallBound:: -operator=(const HollowBallBound& other) -{ - radii = other.radii; - center = other.center; - hollowCenter = other.hollowCenter; - metric = other.metric; - ownsMetric = false; - - return *this; -} - -//! Move constructor. -template -HollowBallBound::HollowBallBound( - HollowBallBound&& other) : - radii(other.radii), - center(std::move(other.center)), - hollowCenter(std::move(other.hollowCenter)), - metric(other.metric), - ownsMetric(other.ownsMetric) -{ - // Fix the other bound. - other.radii.Hi() = 0.0; - other.radii.Lo() = 0.0; - other.center = arma::Col(); - other.hollowCenter = arma::Col(); - other.metric = NULL; - other.ownsMetric = false; -} - -//! Destructor to release allocated memory. -template -HollowBallBound::~HollowBallBound() -{ - if (ownsMetric) - delete metric; -} - -//! Get the range in a certain dimension. -template -math::RangeType HollowBallBound::operator[]( - const size_t i) const -{ - if (radii.Hi() < 0) - return math::Range(); - else - return math::Range(center[i] - radii.Hi(), center[i] + radii.Hi()); -} - -/** - * Determines if a point is within the bound. - */ -template -template -bool HollowBallBound::Contains( - const VecType& point) const -{ - if (radii.Hi() < 0) - return false; - else - { - ElemType dist = metric->Evaluate(center, point); - if (dist > radii.Hi()) - return false; // The point is situated outside the outer ball. - - // Check if the point is situated outside the hole. - dist = metric->Evaluate(hollowCenter, point); - - return (dist >= radii.Lo()); - } -} - -/** - * Determines if another bound is within this bound. - */ -template -bool HollowBallBound::Contains( - const HollowBallBound& other) const -{ - if (radii.Hi() < 0) - return false; - else - { - const ElemType dist = metric->Evaluate(center, other.center); - const ElemType hollowCenterDist = metric->Evaluate(hollowCenter, - other.center); - const ElemType hollowHollowDist = metric->Evaluate(hollowCenter, - other.hollowCenter); - - // The outer ball of the second bound does not contain the hole of the first - // bound. - bool containOnOneSide = (hollowCenterDist - other.radii.Hi() >= radii.Lo()) - && (dist + other.radii.Hi() <= radii.Hi()); - - // The hole of the second bound contains the hole of the first bound. - bool containOnEverySide = (hollowHollowDist + radii.Lo() <= - other.radii.Lo()) && (dist + other.radii.Hi() <= radii.Hi()); - - // The first bound has not got a hole. - bool containAsBall = (radii.Lo() == 0) && - (dist + other.radii.Hi() <= radii.Hi()); - - return (containOnOneSide || containOnEverySide || containAsBall); - } -} - - -/** - * Calculates minimum bound-to-point squared distance. - */ -template -template -ElemType HollowBallBound::MinDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - if (radii.Hi() < 0) - return std::numeric_limits::max(); - else - { - const ElemType outerDistance = metric->Evaluate(point, center) - radii.Hi(); - - if (outerDistance >= 0) - return outerDistance; // The outer ball does not contain the point. - - // Check if the point is situated in the hole. - const ElemType innerDistance = math::ClampNonNegative(radii.Lo() - - metric->Evaluate(point, hollowCenter)); - - return innerDistance; - } -} - -/** - * Calculates minimum bound-to-bound squared distance. - */ -template -ElemType HollowBallBound::MinDistance( - const HollowBallBound& other) - const -{ - if (radii.Hi() < 0 || other.radii.Hi() < 0) - return std::numeric_limits::max(); - else - { - const ElemType outerDistance = metric->Evaluate(center, other.center) - - radii.Hi() - other.radii.Hi(); - if (outerDistance >= 0) - return outerDistance; // The outer hollows do not overlap. - - // Check if the hole of the second bound contains the outer ball of the - // first bound. - const ElemType innerDistance1 = other.radii.Lo() - - metric->Evaluate(center, other.hollowCenter) - radii.Hi(); - if (innerDistance1 >= 0) - return innerDistance1; - - // Check if the hole of the first bound contains the outer ball of the - // second bound. - const ElemType innerDistance2 = math::ClampNonNegative(radii.Lo() - - metric->Evaluate(hollowCenter, other.center) - other.radii.Hi()); - - return innerDistance2; - } -} - -/** - * Computes maximum distance. - */ -template -template -ElemType HollowBallBound::MaxDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - if (radii.Hi() < 0) - return std::numeric_limits::max(); - else - return metric->Evaluate(point, center) + radii.Hi(); -} - -/** - * Computes maximum distance. - */ -template -ElemType HollowBallBound::MaxDistance( - const HollowBallBound& other) - const -{ - if (radii.Hi() < 0) - return std::numeric_limits::max(); - else - return metric->Evaluate(other.center, center) + radii.Hi() + - other.radii.Hi(); -} - -/** - * Calculates minimum and maximum bound-to-bound squared distance. - * - * Example: bound1.MinDistanceSq(other) for minimum squared distance. - */ -template -template -math::RangeType HollowBallBound::RangeDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - if (radii.Hi() < 0) - return math::Range(std::numeric_limits::max(), - std::numeric_limits::max()); - else - { - math::RangeType range; - const ElemType dist = metric->Evaluate(point, center); - - if (dist >= radii.Hi()) // The outer ball does not contain the point. - range.Lo() = dist - radii.Hi(); - else - { - // Check if the point is situated in the hole. - range.Lo() = math::ClampNonNegative(radii.Lo() - - metric->Evaluate(point, hollowCenter)); - } - range.Hi() = dist + radii.Hi(); - - return range; - } -} - -template -math::RangeType HollowBallBound::RangeDistance( - const HollowBallBound& other) const -{ - if (radii.Hi() < 0) - return math::Range(std::numeric_limits::max(), - std::numeric_limits::max()); - else - { - math::RangeType range; - - const ElemType dist = metric->Evaluate(center, other.center); - - const ElemType outerDistance = dist - radii.Hi() - other.radii.Hi(); - if (outerDistance >= 0) - range.Lo() = outerDistance; // The outer balls do not overlap. - else - { - const ElemType innerDistance1 = other.radii.Lo() - - metric->Evaluate(center, other.hollowCenter) - radii.Hi(); - // Check if the outer ball of the first bound is contained in the - // hole of the second bound. - if (innerDistance1 >= 0) - range.Lo() = innerDistance1; - else - { - // Check if the outer ball of the second bound is contained in the - // hole of the first bound. - range.Lo() = math::ClampNonNegative(radii.Lo() - - metric->Evaluate(hollowCenter, other.center) - other.radii.Hi()); - } - } - range.Hi() = dist + radii.Hi() + other.radii.Hi(); - return range; - } -} - -/** - * Expand the bound to include the given point. Algorithm adapted from - * Jack Ritter, "An Efficient Bounding Sphere" in Graphics Gems (1990). - * The difference lies in the way we initialize the ball bound. The way we - * expand the bound is same. - */ -template -template -const HollowBallBound& -HollowBallBound::operator|=(const MatType& data) -{ - if (radii.Hi() < 0) - { - center = data.col(0); - radii.Hi() = 0; - } - if (radii.Lo() < 0) - { - hollowCenter = data.col(0); - radii.Lo() = 0; - } - // Now iteratively add points. - for (size_t i = 0; i < data.n_cols; ++i) - { - const ElemType dist = metric->Evaluate(center, data.col(i)); - const ElemType hollowDist = metric->Evaluate(hollowCenter, data.col(i)); - - // See if the new point lies outside the bound. - if (dist > radii.Hi()) - { - // Move towards the new point and increase the radius just enough to - // accommodate the new point. - const arma::Col diff = data.col(i) - center; - center += ((dist - radii.Hi()) / (2 * dist)) * diff; - radii.Hi() = 0.5 * (dist + radii.Hi()); - } - if (hollowDist < radii.Lo()) - radii.Lo() = hollowDist; - } - - return *this; -} - -/** - * Expand the bound to include the given bound. - */ -template -const HollowBallBound& -HollowBallBound::operator|=(const HollowBallBound& other) -{ - if (radii.Hi() < 0) - { - center = other.center; - hollowCenter = other.hollowCenter; - radii.Hi() = other.radii.Hi(); - radii.Lo() = other.radii.Lo(); - return *this; - } - - const ElemType dist = metric->Evaluate(center, other.center); - // Check if the outer balls overlap. - if (radii.Hi() < dist + other.radii.Hi()) - radii.Hi() = dist + other.radii.Hi(); - - const ElemType innerDist = math::ClampNonNegative(other.radii.Lo() - - metric->Evaluate(hollowCenter, other.hollowCenter)); - // Check if the hole of the first bound is not contained in the hole of the - // second bound. - if (radii.Lo() > innerDist) - radii.Lo() = innerDist; - - return *this; -} - - -//! Serialize the BallBound. -template -template -void HollowBallBound::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(radii); - ar & BOOST_SERIALIZATION_NVP(center); - ar & BOOST_SERIALIZATION_NVP(hollowCenter); - - if (Archive::is_loading::value) - { - // If we're loading, delete the local metric since we'll have a new one. - if (ownsMetric) - delete metric; - } - - ar & BOOST_SERIALIZATION_NVP(metric); - ar & BOOST_SERIALIZATION_NVP(ownsMetric); -} - -} // namespace bound -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_HOLLOW_BALL_BOUND_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/hrectbound.hpp b/src/sdk/mlpack/include/mlpack/core/tree/hrectbound.hpp deleted file mode 100644 index a5d2974ba..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/hrectbound.hpp +++ /dev/null @@ -1,245 +0,0 @@ -/** - * @file hrectbound.hpp - * - * Bounds that are useful for binary space partitioning trees. - * - * This file describes the interface for the HRectBound class, which implements - * a hyperrectangle bound. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_HRECTBOUND_HPP -#define MLPACK_CORE_TREE_HRECTBOUND_HPP - -#include -#include -#include -#include "bound_traits.hpp" - -namespace mlpack { -namespace bound { - -namespace meta /** Metaprogramming utilities. */ { - -//! Utility struct where Value is true if and only if the argument is of type -//! LMetric. -template -struct IsLMetric -{ - static const bool Value = false; -}; - -//! Specialization for IsLMetric when the argument is of type LMetric. -template -struct IsLMetric> -{ - static const bool Value = true; -}; - -} // namespace meta - -/** - * Hyper-rectangle bound for an L-metric. This should be used in conjunction - * with the LMetric class. Be sure to use the same template parameters for - * LMetric as you do for HRectBound -- otherwise odd results may occur. - * - * @tparam MetricType Type of metric to use; must be of type LMetric. - * @tparam ElemType Element type (double/float/int/etc.). - */ -template, - typename ElemType = double> -class HRectBound -{ - // It is required that HRectBound have an LMetric as the given MetricType. - static_assert(meta::IsLMetric::Value == true, - "HRectBound can only be used with the LMetric<> metric type."); - - public: - /** - * Empty constructor; creates a bound of dimensionality 0. - */ - HRectBound(); - - /** - * Initializes to specified dimensionality with each dimension the empty - * set. - */ - HRectBound(const size_t dimension); - - //! Copy constructor; necessary to prevent memory leaks. - HRectBound(const HRectBound& other); - //! Same as copy constructor; necessary to prevent memory leaks. - HRectBound& operator=(const HRectBound& other); - - //! Move constructor: take possession of another bound's information. - HRectBound(HRectBound&& other); - - //! Destructor: clean up memory. - ~HRectBound(); - - /** - * Resets all dimensions to the empty set (so that this bound contains - * nothing). - */ - void Clear(); - - //! Gets the dimensionality. - size_t Dim() const { return dim; } - - //! Get the range for a particular dimension. No bounds checking. Be - //! careful: this may make MinWidth() invalid. - math::RangeType& operator[](const size_t i) { return bounds[i]; } - //! Modify the range for a particular dimension. No bounds checking. - const math::RangeType& operator[](const size_t i) const - { return bounds[i]; } - - //! Get the minimum width of the bound. - ElemType MinWidth() const { return minWidth; } - //! Modify the minimum width of the bound. - ElemType& MinWidth() { return minWidth; } - - /** - * Calculates the center of the range, placing it into the given vector. - * - * @param center Vector which the center will be written to. - */ - void Center(arma::Col& center) const; - - /** - * Calculate the volume of the hyperrectangle. - * - * @return Volume of the hyperrectangle. - */ - ElemType Volume() const; - - /** - * Calculates minimum bound-to-point distance. - * - * @param point Point to which the minimum distance is requested. - */ - template - ElemType MinDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const; - - /** - * Calculates minimum bound-to-bound distance. - * - * @param other Bound to which the minimum distance is requested. - */ - ElemType MinDistance(const HRectBound& other) const; - - /** - * Calculates maximum bound-to-point squared distance. - * - * @param point Point to which the maximum distance is requested. - */ - template - ElemType MaxDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const; - - /** - * Computes maximum distance. - * - * @param other Bound to which the maximum distance is requested. - */ - ElemType MaxDistance(const HRectBound& other) const; - - /** - * Calculates minimum and maximum bound-to-bound distance. - * - * @param other Bound to which the minimum and maximum distances are - * requested. - */ - math::RangeType RangeDistance(const HRectBound& other) const; - - /** - * Calculates minimum and maximum bound-to-point distance. - * - * @param point Point to which the minimum and maximum distances are - * requested. - */ - template - math::RangeType RangeDistance( - const VecType& point, - typename std::enable_if_t::value>* = 0) const; - - /** - * Expands this region to include new points. - * - * @tparam MatType Type of matrix; could be Mat, SpMat, a subview, or just a - * vector. - * @param data Data points to expand this region to include. - */ - template - HRectBound& operator|=(const MatType& data); - - /** - * Expands this region to encompass another bound. - */ - HRectBound& operator|=(const HRectBound& other); - - /** - * Determines if a point is within this bound. - */ - template - bool Contains(const VecType& point) const; - - /** - * Determines if this bound partially contains a bound. - */ - bool Contains(const HRectBound& bound) const; - - /** - * Returns the intersection of this bound and another. - */ - HRectBound operator&(const HRectBound& bound) const; - - /** - * Intersects this bound with another. - */ - HRectBound& operator&=(const HRectBound& bound); - - /** - * Returns the volume of overlap of this bound and another. - */ - ElemType Overlap(const HRectBound& bound) const; - - /** - * Returns the diameter of the hyperrectangle (that is, the longest diagonal). - */ - ElemType Diameter() const; - - /** - * Serialize the bound object. - */ - template - void serialize(Archive& ar, const unsigned int version); - - private: - //! The dimensionality of the bound. - size_t dim; - //! The bounds for each dimension. - math::RangeType* bounds; - //! Cached minimum width of bound. - ElemType minWidth; -}; - -// A specialization of BoundTraits for this class. -template -struct BoundTraits> -{ - //! These bounds are always tight for each dimension. - const static bool HasTightBounds = true; -}; - -} // namespace bound -} // namespace mlpack - -#include "hrectbound_impl.hpp" - -#endif // MLPACK_CORE_TREE_HRECTBOUND_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/hrectbound_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/hrectbound_impl.hpp deleted file mode 100644 index d9c7da24b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/hrectbound_impl.hpp +++ /dev/null @@ -1,685 +0,0 @@ -/** - * @file hrectbound_impl.hpp - * - * Implementation of hyper-rectangle bound policy class. - * Template parameter Power is the metric to use; use 2 for Euclidean (L2). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP -#define MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP - -#include - -// In case it has not been included yet. -#include "hrectbound.hpp" - -namespace mlpack { -namespace bound { - -/** - * Empty constructor. - */ -template -inline HRectBound::HRectBound() : - dim(0), - bounds(NULL), - minWidth(0) -{ /* Nothing to do. */ } - -/** - * Initializes to specified dimensionality with each dimension the empty - * set. - */ -template -inline HRectBound::HRectBound(const size_t dimension) : - dim(dimension), - bounds(new math::RangeType[dim]), - minWidth(0) -{ /* Nothing to do. */ } - -/** - * Copy constructor necessary to prevent memory leaks. - */ -template -inline HRectBound::HRectBound( - const HRectBound& other) : - dim(other.Dim()), - bounds(new math::RangeType[dim]), - minWidth(other.MinWidth()) -{ - // Copy other bounds over. - for (size_t i = 0; i < dim; i++) - bounds[i] = other[i]; -} - -/** - * Same as the copy constructor. - */ -template -inline HRectBound< - MetricType, - ElemType>& HRectBound::operator=(const HRectBound& other) -{ - if (dim != other.Dim()) - { - // Reallocation is necessary. - if (bounds) - delete[] bounds; - - dim = other.Dim(); - bounds = new math::RangeType[dim]; - } - - // Now copy each of the bound values. - for (size_t i = 0; i < dim; i++) - bounds[i] = other[i]; - - minWidth = other.MinWidth(); - - return *this; -} - -/** - * Move constructor: take possession of another bound's information. - */ -template -inline HRectBound::HRectBound( - HRectBound&& other) : - dim(other.dim), - bounds(other.bounds), - minWidth(other.minWidth) -{ - // Fix the other bound. - other.dim = 0; - other.bounds = NULL; - other.minWidth = 0.0; -} - -/** - * Destructor: clean up memory. - */ -template -inline HRectBound::~HRectBound() -{ - if (bounds) - delete[] bounds; -} - -/** - * Resets all dimensions to the empty set. - */ -template -inline void HRectBound::Clear() -{ - for (size_t i = 0; i < dim; i++) - bounds[i] = math::RangeType(); - minWidth = 0; -} - -/*** - * Calculates the centroid of the range, placing it into the given vector. - * - * @param centroid Vector which the centroid will be written to. - */ -template -inline void HRectBound::Center( - arma::Col& center) const -{ - // Set size correctly if necessary. - if (!(center.n_elem == dim)) - center.set_size(dim); - - for (size_t i = 0; i < dim; i++) - center(i) = bounds[i].Mid(); -} - -/** - * Calculate the volume of the hyperrectangle. - * - * @return Volume of the hyperrectangle. - */ -template -inline ElemType HRectBound::Volume() const -{ - ElemType volume = 1.0; - for (size_t i = 0; i < dim; ++i) - { - if (bounds[i].Lo() >= bounds[i].Hi()) - return 0; - - volume *= (bounds[i].Hi() - bounds[i].Lo()); - } - - return volume; -} - -/** - * Calculates minimum bound-to-point squared distance. - */ -template -template -inline ElemType HRectBound::MinDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - Log::Assert(point.n_elem == dim); - - ElemType sum = 0; - - ElemType lower, higher; - for (size_t d = 0; d < dim; d++) - { - lower = bounds[d].Lo() - point[d]; - higher = point[d] - bounds[d].Hi(); - - // Since only one of 'lower' or 'higher' is negative, if we add each's - // absolute value to itself and then sum those two, our result is the - // nonnegative half of the equation times two; then we raise to power Power. - if (MetricType::Power == 1) - sum += (lower + std::fabs(lower)) + (higher + std::fabs(higher)); - else if (MetricType::Power == 2) - { - ElemType dist = (lower + std::fabs(lower)) + (higher + std::fabs(higher)); - sum += dist * dist; - } - else - { - sum += pow((lower + fabs(lower)) + (higher + fabs(higher)), - (ElemType) MetricType::Power); - } - } - - // Now take the Power'th root (but make sure our result is squared if it needs - // to be); then cancel out the constant of 2 (which may have been squared now) - // that was introduced earlier. The compiler should optimize out the if - // statement entirely. - if (MetricType::Power == 1) - return sum * 0.5; - else if (MetricType::Power == 2) - { - if (MetricType::TakeRoot) - return (ElemType) std::sqrt(sum) * 0.5; - else - return sum * 0.25; - } - else - { - if (MetricType::TakeRoot) - return (ElemType) pow((double) sum, - 1.0 / (double) MetricType::Power) / 2.0; - else - return sum / pow(2.0, MetricType::Power); - } -} - -/** - * Calculates minimum bound-to-bound squared distance. - */ -template -ElemType HRectBound::MinDistance(const HRectBound& other) - const -{ - Log::Assert(dim == other.dim); - - ElemType sum = 0; - const math::RangeType* mbound = bounds; - const math::RangeType* obound = other.bounds; - - ElemType lower, higher; - for (size_t d = 0; d < dim; d++) - { - lower = obound->Lo() - mbound->Hi(); - higher = mbound->Lo() - obound->Hi(); - // We invoke the following: - // x + fabs(x) = max(x * 2, 0) - // (x * 2)^2 / 4 = x^2 - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - sum += (lower + std::fabs(lower)) + (higher + std::fabs(higher)); - else if (MetricType::Power == 2) - { - ElemType dist = (lower + std::fabs(lower)) + (higher + std::fabs(higher)); - sum += dist * dist; - } - else - { - sum += pow((lower + fabs(lower)) + (higher + fabs(higher)), - (ElemType) MetricType::Power); - } - - // Move bound pointers. - mbound++; - obound++; - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - return sum * 0.5; - else if (MetricType::Power == 2) - { - if (MetricType::TakeRoot) - return (ElemType) std::sqrt(sum) * 0.5; - else - return sum * 0.25; - } - else - { - if (MetricType::TakeRoot) - return (ElemType) pow((double) sum, - 1.0 / (double) MetricType::Power) / 2.0; - else - return sum / pow(2.0, MetricType::Power); - } -} - -/** - * Calculates maximum bound-to-point squared distance. - */ -template -template -inline ElemType HRectBound::MaxDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - ElemType sum = 0; - - Log::Assert(point.n_elem == dim); - - for (size_t d = 0; d < dim; d++) - { - ElemType v = std::max(fabs(point[d] - bounds[d].Lo()), - fabs(bounds[d].Hi() - point[d])); - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - sum += v; // v is non-negative. - else if (MetricType::Power == 2) - sum += v * v; - else - sum += std::pow(v, (ElemType) MetricType::Power); - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::TakeRoot) - { - if (MetricType::Power == 1) - return sum; - else if (MetricType::Power == 2) - return (ElemType) std::sqrt(sum); - else - return (ElemType) pow((double) sum, 1.0 / (double) MetricType::Power); - } - else - return sum; -} - -/** - * Computes maximum distance. - */ -template -inline ElemType HRectBound::MaxDistance( - const HRectBound& other) - const -{ - ElemType sum = 0; - - Log::Assert(dim == other.dim); - - ElemType v; - for (size_t d = 0; d < dim; d++) - { - v = std::max(fabs(other.bounds[d].Hi() - bounds[d].Lo()), - fabs(bounds[d].Hi() - other.bounds[d].Lo())); - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - sum += v; // v is non-negative. - else if (MetricType::Power == 2) - sum += v * v; - else - sum += std::pow(v, (ElemType) MetricType::Power); - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::TakeRoot) - { - if (MetricType::Power == 1) - return sum; - else if (MetricType::Power == 2) - return (ElemType) std::sqrt(sum); - else - return (ElemType) pow((double) sum, 1.0 / (double) MetricType::Power); - } - else - return sum; -} - -/** - * Calculates minimum and maximum bound-to-bound squared distance. - */ -template -inline math::RangeType -HRectBound::RangeDistance( - const HRectBound& other) const -{ - ElemType loSum = 0; - ElemType hiSum = 0; - - Log::Assert(dim == other.dim); - - ElemType v1, v2, vLo, vHi; - for (size_t d = 0; d < dim; d++) - { - v1 = other.bounds[d].Lo() - bounds[d].Hi(); - v2 = bounds[d].Lo() - other.bounds[d].Hi(); - // One of v1 or v2 is negative. - if (v1 >= v2) - { - vHi = -v2; // Make it nonnegative. - vLo = (v1 > 0) ? v1 : 0; // Force to be 0 if negative. - } - else - { - vHi = -v1; // Make it nonnegative. - vLo = (v2 > 0) ? v2 : 0; // Force to be 0 if negative. - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - { - loSum += vLo; // vLo is non-negative. - hiSum += vHi; // vHi is non-negative. - } - else if (MetricType::Power == 2) - { - loSum += vLo * vLo; - hiSum += vHi * vHi; - } - else - { - loSum += std::pow(vLo, (ElemType) MetricType::Power); - hiSum += std::pow(vHi, (ElemType) MetricType::Power); - } - } - - if (MetricType::TakeRoot) - { - if (MetricType::Power == 1) - return math::RangeType(loSum, hiSum); - else if (MetricType::Power == 2) - return math::RangeType((ElemType) std::sqrt(loSum), - (ElemType) std::sqrt(hiSum)); - else - { - return math::RangeType( - (ElemType) pow((double) loSum, 1.0 / (double) MetricType::Power), - (ElemType) pow((double) hiSum, 1.0 / (double) MetricType::Power)); - } - } - else - return math::RangeType(loSum, hiSum); -} - -/** - * Calculates minimum and maximum bound-to-point squared distance. - */ -template -template -inline math::RangeType -HRectBound::RangeDistance( - const VecType& point, - typename std::enable_if_t::value>* /* junk */) const -{ - ElemType loSum = 0; - ElemType hiSum = 0; - - Log::Assert(point.n_elem == dim); - - ElemType v1, v2, vLo, vHi; - for (size_t d = 0; d < dim; d++) - { - v1 = bounds[d].Lo() - point[d]; // Negative if point[d] > lo. - v2 = point[d] - bounds[d].Hi(); // Negative if point[d] < hi. - // One of v1 or v2 (or both) is negative. - if (v1 >= 0) // point[d] <= bounds_[d].Lo(). - { - vHi = -v2; // v2 will be larger but must be negated. - vLo = v1; - } - else // point[d] is between lo and hi, or greater than hi. - { - if (v2 >= 0) - { - vHi = -v1; // v1 will be larger, but must be negated. - vLo = v2; - } - else - { - vHi = -std::min(v1, v2); // Both are negative, but we need the larger. - vLo = 0; - } - } - - // The compiler should optimize out this if statement entirely. - if (MetricType::Power == 1) - { - loSum += vLo; // vLo is non-negative. - hiSum += vHi; // vHi is non-negative. - } - else if (MetricType::Power == 2) - { - loSum += vLo * vLo; - hiSum += vHi * vHi; - } - else - { - loSum += std::pow(vLo, (ElemType) MetricType::Power); - hiSum += std::pow(vHi, (ElemType) MetricType::Power); - } - } - - if (MetricType::TakeRoot) - { - if (MetricType::Power == 1) - return math::RangeType(loSum, hiSum); - else if (MetricType::Power == 2) - return math::RangeType((ElemType) std::sqrt(loSum), - (ElemType) std::sqrt(hiSum)); - else - { - return math::RangeType( - (ElemType) pow((double) loSum, 1.0 / (double) MetricType::Power), - (ElemType) pow((double) hiSum, 1.0 / (double) MetricType::Power)); - } - } - else - return math::RangeType(loSum, hiSum); -} - -/** - * Expands this region to include a new point. - */ -template -template -inline HRectBound& -HRectBound::operator|=(const MatType& data) -{ - Log::Assert(data.n_rows == dim); - - arma::Col mins(min(data, 1)); - arma::Col maxs(max(data, 1)); - - minWidth = std::numeric_limits::max(); - for (size_t i = 0; i < dim; i++) - { - bounds[i] |= math::RangeType(mins[i], maxs[i]); - const ElemType width = bounds[i].Width(); - if (width < minWidth) - minWidth = width; - } - - return *this; -} - -/** - * Expands this region to encompass another bound. - */ -template -inline HRectBound& -HRectBound::operator|=(const HRectBound& other) -{ - assert(other.dim == dim); - - minWidth = std::numeric_limits::max(); - for (size_t i = 0; i < dim; i++) - { - bounds[i] |= other.bounds[i]; - const ElemType width = bounds[i].Width(); - if (width < minWidth) - minWidth = width; - } - - return *this; -} - -/** - * Determines if a point is within this bound. - */ -template -template -inline bool HRectBound::Contains( - const VecType& point) const -{ - for (size_t i = 0; i < point.n_elem; i++) - { - if (!bounds[i].Contains(point(i))) - return false; - } - - return true; -} - -/** - * Determines if this bound partially contains a bound. - */ -template -inline bool HRectBound::Contains( - const HRectBound& bound) const -{ - for (size_t i = 0; i < dim; i++) - { - const math::RangeType& r_a = bounds[i]; - const math::RangeType& r_b = bound.bounds[i]; - - // If a does not overlap b at all. - if (r_a.Hi() <= r_b.Lo() || r_a.Lo() >= r_b.Hi()) - return false; - } - - return true; -} - -/** - * Returns the intersection of this bound and another. - */ -template -inline HRectBound -HRectBound::operator&(const HRectBound& bound) const -{ - HRectBound result(dim); - - for (size_t k = 0; k < dim; k++) - { - result[k].Lo() = std::max(bounds[k].Lo(), bound.bounds[k].Lo()); - result[k].Hi() = std::min(bounds[k].Hi(), bound.bounds[k].Hi()); - } - return result; -} - -/** - * Intersects this bound with another. - */ -template -inline HRectBound& -HRectBound::operator&=(const HRectBound& bound) -{ - for (size_t k = 0; k < dim; k++) - { - bounds[k].Lo() = std::max(bounds[k].Lo(), bound.bounds[k].Lo()); - bounds[k].Hi() = std::min(bounds[k].Hi(), bound.bounds[k].Hi()); - } - return *this; -} - -/** - * Returns the volume of overlap of this bound and another. - */ -template -inline ElemType HRectBound::Overlap( - const HRectBound& bound) const -{ - ElemType volume = 1.0; - - for (size_t k = 0; k < dim; k++) - { - ElemType lo = std::max(bounds[k].Lo(), bound.bounds[k].Lo()); - ElemType hi = std::min(bounds[k].Hi(), bound.bounds[k].Hi()); - - if ( hi <= lo) - return 0; - - volume *= hi - lo; - } - return volume; -} - -/** - * Returns the diameter of the hyperrectangle (that is, the longest diagonal). - */ -template -inline ElemType HRectBound::Diameter() const -{ - ElemType d = 0; - for (size_t i = 0; i < dim; ++i) - d += std::pow(bounds[i].Hi() - bounds[i].Lo(), - (ElemType) MetricType::Power); - - if (MetricType::TakeRoot) - return (ElemType) std::pow((double) d, 1.0 / (double) MetricType::Power); - else - return d; -} - -//! Serialize the bound object. -template -template -void HRectBound::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(dim); - - // Allocate memory for the bounds, if necessary. - if (Archive::is_loading::value) - { - if (bounds) - delete[] bounds; - bounds = new math::RangeType[dim]; - } - - // We can't serialize a raw array directly, so wrap it. - auto boundsArray = boost::serialization::make_array(bounds, dim); - ar & BOOST_SERIALIZATION_NVP(boundsArray); - ar & BOOST_SERIALIZATION_NVP(minWidth); -} - -} // namespace bound -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_HRECTBOUND_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/octree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/octree.hpp deleted file mode 100644 index 4b7514d2b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/octree.hpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * @file octree.hpp - * @author Ryan Curtin - * - * Include all the necessary files to use the Octree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_OCTREE_HPP -#define MLPACK_CORE_TREE_OCTREE_HPP - -#include -#include "bounds.hpp" -#include "octree/octree.hpp" -#include "octree/traits.hpp" -#include "octree/single_tree_traverser.hpp" -#include "octree/dual_tree_traverser.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/octree/dual_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/octree/dual_tree_traverser.hpp deleted file mode 100644 index a69fbb4a8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/octree/dual_tree_traverser.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @file dual_tree_traverser.hpp - * @author Ryan Curtin - * - * Define the dual-tree traverser for the Octree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_OCTREE_DUAL_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_OCTREE_DUAL_TREE_TRAVERSER_HPP - -#include -#include "octree.hpp" - -namespace mlpack { -namespace tree { - -template -template -class Octree::DualTreeTraverser -{ - public: - /** - * Instantiate the given dual-tree traverser with the given rule set. - */ - DualTreeTraverser(RuleType& rule); - - /** - * Traverse the two trees. This does not reset the statistics of the - * traversals (it just adds to them). - */ - void Traverse(Octree& queryNode, Octree& referenceNode); - - //! Get the number of pruned nodes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of pruned nodes (i.e. to reset it). - size_t& NumPrunes() { return numPrunes; } - - //! Get the number of visited node combinations. - size_t NumVisited() const { return numVisited; } - //! Modify the number of visited node combinations. - size_t& NumVistied() { return numVisited; } - - //! Get the number of times a node was scored. - size_t NumScores() const { return numScores; } - //! Modify the number of times a node was scored. - size_t& NumScores() { return numScores; } - - //! Get the number of times a base case was computed. - size_t NumBaseCases() const { return numBaseCases; } - //! Modify the number of times a base case was computed. - size_t& NumBaseCases() { return numBaseCases; } - - private: - //! The rule type to use. - RuleType& rule; - - //! The number of prunes. - size_t numPrunes; - //! The number of visited node combinations. - size_t numVisited; - //! The number of times a node was scored. - size_t numScores; - //! The number of times a base case was calculated. - size_t numBaseCases; - - //! Traversal information, held in the class so that it isn't continually - //! being reallocated. - typename RuleType::TraversalInfoType traversalInfo; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "dual_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/octree/dual_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/octree/dual_tree_traverser_impl.hpp deleted file mode 100644 index 81eeec315..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/octree/dual_tree_traverser_impl.hpp +++ /dev/null @@ -1,154 +0,0 @@ -/** - * @file dual_tree_traverser_impl.hpp - * @author Ryan Curtin - * - * Implementation of the dual-tree traverser for the octree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_OCTREE_DUAL_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_OCTREE_DUAL_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "dual_tree_traverser.hpp" - -namespace mlpack { -namespace tree { - -template -template -Octree::DualTreeTraverser:: - DualTreeTraverser(RuleType& rule) : - rule(rule), - numPrunes(0), - numVisited(0), - numScores(0), - numBaseCases(0) -{ - // Nothing to do. -} - -template -template -void Octree::DualTreeTraverser:: - Traverse(Octree& queryNode, Octree& referenceNode) -{ - // Increment the visit counter. - ++numVisited; - - // Store the current traversal info. - traversalInfo = rule.TraversalInfo(); - - if (queryNode.IsLeaf() && referenceNode.IsLeaf()) - { - const size_t begin = queryNode.Point(0); - const size_t end = begin + queryNode.NumPoints(); - for (size_t q = begin; q < end; ++q) - { - // First, see if we can prune the reference node for this query point. - rule.TraversalInfo() = traversalInfo; - const double score = rule.Score(q, referenceNode); - if (score == DBL_MAX) - { - ++numPrunes; - continue; - } - - const size_t rBegin = referenceNode.Point(0); - const size_t rEnd = rBegin + referenceNode.NumPoints(); - for (size_t r = rBegin; r < rEnd; ++r) - rule.BaseCase(q, r); - - numBaseCases += referenceNode.NumPoints(); - } - } - else if (!queryNode.IsLeaf() && referenceNode.IsLeaf()) - { - // We have to recurse down the query node. Order does not matter. - for (size_t i = 0; i < queryNode.NumChildren(); ++i) - { - rule.TraversalInfo() = traversalInfo; - const double score = rule.Score(queryNode.Child(i), referenceNode); - if (score == DBL_MAX) - { - ++numPrunes; - continue; - } - - Traverse(queryNode.Child(i), referenceNode); - } - } - else if (queryNode.IsLeaf() && !referenceNode.IsLeaf()) - { - // We have to recurse down the reference node, so we need to do it in an - // ordered manner. - arma::vec scores(referenceNode.NumChildren()); - std::vector - tis(referenceNode.NumChildren()); - for (size_t i = 0; i < referenceNode.NumChildren(); ++i) - { - rule.TraversalInfo() = traversalInfo; - scores[i] = rule.Score(queryNode, referenceNode.Child(i)); - tis[i] = rule.TraversalInfo(); - } - - // Sort the scores. - arma::uvec scoreOrder = arma::sort_index(scores); - for (size_t i = 0; i < scoreOrder.n_elem; ++i) - { - if (scores[scoreOrder[i]] == DBL_MAX) - { - // We don't need to check any more---all children past here are pruned. - numPrunes += scoreOrder.n_elem - i; - break; - } - - rule.TraversalInfo() = tis[scoreOrder[i]]; - Traverse(queryNode, referenceNode.Child(scoreOrder[i])); - } - } - else - { - // We have to recurse down both the query and reference nodes. Query order - // does not matter, so we will do that in sequence. However we will - // allocate the arrays for recursion at this level. - arma::vec scores(referenceNode.NumChildren()); - std::vector - tis(referenceNode.NumChildren()); - for (size_t j = 0; j < queryNode.NumChildren(); ++j) - { - // Now we have to recurse down the reference node, which we will do in a - // prioritized manner. - for (size_t i = 0; i < referenceNode.NumChildren(); ++i) - { - rule.TraversalInfo() = traversalInfo; - scores[i] = rule.Score(queryNode.Child(j), referenceNode.Child(i)); - tis[i] = rule.TraversalInfo(); - } - - // Sort the scores. - arma::uvec scoreOrder = arma::sort_index(scores); - for (size_t i = 0; i < scoreOrder.n_elem; ++i) - { - if (scores[scoreOrder[i]] == DBL_MAX) - { - // We don't need to check any more - // All children past here are pruned. - numPrunes += scoreOrder.n_elem - i; - break; - } - - rule.TraversalInfo() = tis[scoreOrder[i]]; - Traverse(queryNode.Child(j), referenceNode.Child(scoreOrder[i])); - } - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/octree/octree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/octree/octree.hpp deleted file mode 100644 index 78184d30f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/octree/octree.hpp +++ /dev/null @@ -1,458 +0,0 @@ -/** - * @file octree.hpp - * @author Ryan Curtin - * - * Definition of generalized octree (Octree). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_OCTREE_OCTREE_HPP -#define MLPACK_CORE_TREE_OCTREE_OCTREE_HPP - -#include -#include "../hrectbound.hpp" -#include "../statistic.hpp" - -namespace mlpack { -namespace tree { - -template -class Octree -{ - public: - //! So other classes can use TreeType::Mat. - typedef MatType Mat; - //! The type of element held in MatType. - typedef typename MatType::elem_type ElemType; - - //! A single-tree traverser; see single_tree_traverser.hpp. - template - class SingleTreeTraverser; - - //! A dual-tree traverser; see dual_tree_traverser.hpp. - template - class DualTreeTraverser; - - private: - //! The children held by this node. - std::vector children; - - //! The index of the first point in the dataset contained in this node (and - //! its children). - size_t begin; - //! The number of points of the dataset contained in this node (and its - //! children). - size_t count; - //! The minimum bounding rectangle of the points held in the node (and its - //! children). - bound::HRectBound bound; - //! The dataset. - MatType* dataset; - //! The parent (NULL if this node is the root). - Octree* parent; - //! The statistic. - StatisticType stat; - //! The distance from the center of this node to the center of the parent. - ElemType parentDistance; - //! The distance to the furthest descendant, cached to speed things up. - ElemType furthestDescendantDistance; - //! An instantiated metric. - MetricType metric; - - public: - /** - * Construct this as the root node of an octree on the given dataset. This - * copies the dataset. If you don't want to copy the input dataset, consider - * using the constructor that takes an rvalue reference and use std::move(). - * - * @param data Dataset to create tree from. This will be copied! - * @param maxLeafSize Maximum number of points in a leaf node. - */ - Octree(const MatType& data, const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of an octree on the given dataset. This - * copies the dataset and modifies its ordering; a mapping of the old point - * indices to the new point indices is filled. If you don't want the matrix - * to be copied, consider using the constructor that takes an rvalue reference - * and use std::move(). - * - * @param data Dataset to create tree from. This will be copied! - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param maxLeafSize Maximum number of points in a leaf node. - */ - Octree(const MatType& data, - std::vector& oldFromNew, - const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of an octree on the given dataset. This - * copies the dataset and modifies its ordering; a mapping of the old point - * indices to the new point indices is filled, and a mapping of the new point - * indices to the old point indices is filled. If you don't want the matrix - * to be copied, consider using the constructor that takes an rvalue reference - * and use std::move(). - * - * @param data Dataset to create tree from. This will be copied! - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param newFromOld Vector which will be filled with the new positions for - * each old point. - * @param maxLeafSize Maximum number of points in a leaf node. - */ - Octree(const MatType& data, - std::vector& oldFromNew, - std::vector& newFromOld, - const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of an octree on the given dataset. This - * will take ownership of the dataset; if you don't want this, consider using - * the constructor that takes a const reference to the dataset. - * - * @param data Dataset to create tree from. This will be copied! - * @param maxLeafSize Maximum number of points in a leaf node. - */ - Octree(MatType&& data, const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of an octree on the given dataset. This - * will take ownership of the dataset; if you don't want this, consider using - * the constructor that takes a const reference to the dataset. This modifies - * the ordering of the dataset; a mapping of the old point indices to the new - * point indices is filled. - * - * @param data Dataset to create tree from. This will be copied! - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param maxLeafSize Maximum number of points in a leaf node. - */ - Octree(MatType&& data, - std::vector& oldFromNew, - const size_t maxLeafSize = 20); - - /** - * Construct this as the root node of an octree on the given dataset. This - * will take ownership of the dataset; if you don't want this, consider using - * the constructor that takes a const reference to the dataset. This modifies - * the ordering of the dataset; a mapping of the old point indices to the new - * point indices is filled, and a mapping of the new point indices to the old - * point indices is filled. - * - * @param data Dataset to create tree from. This will be copied! - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param newFromOld Vector which will be filled with the new positions for - * each old point. - * @param maxLeafSize Maximum number of points in a leaf node. - */ - Octree(MatType&& data, - std::vector& oldFromNew, - std::vector& newFromOld, - const size_t maxLeafSize = 20); - - /** - * Construct this node as a child of the given parent, starting at column - * begin and using count points. The ordering of that subset of points in the - * parent's data matrix will be modified! This is used for recursive - * tree-building by the other constructors that don't specify point indices. - * - * @param parent Parent of this node. Its dataset will be modified! - * @param begin Index of point to start tree construction with. - * @param count Number of points to use to construct tree. - * @param center Center of the node (for splitting). - * @param width Width of the node in each dimension. - * @param maxLeafSize Maximum number of points in a leaf node. - */ - Octree(Octree* parent, - const size_t begin, - const size_t count, - const arma::vec& center, - const double width, - const size_t maxLeafSize = 20); - - /** - * Construct this node as a child of the given parent, starting at column - * begin and using count points. The ordering of that subset of points in the - * parent's data matrix will be modified! This is used for recursive - * tree-building by the other constructors that don't specify point indices. - * - * A mapping of the old point indices to the new point indices is filled, but - * it is expected that the vector is already allocated with size greater than - * or equal to (begin + count), and if that is not true, invalid memory reads - * (and writes) will occur. - * - * @param parent Parent of this node. Its dataset will be modified! - * @param begin Index of point to start tree construction with. - * @param count Number of points to use to construct tree. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - * @param center Center of the node (for splitting). - * @param width Width of the node in each dimension. - * @param maxLeafSize Maximum number of points in a leaf node. - */ - Octree(Octree* parent, - const size_t begin, - const size_t count, - std::vector& oldFromNew, - const arma::vec& center, - const double width, - const size_t maxLeafSize = 20); - - /** - * Copy the given tree. Be careful! This may use a lot of memory. - * - * @param other Tree to copy from. - */ - Octree(const Octree& other); - - /** - * Move the given tree. The tree passed as a parameter will be emptied and - * will not be usable after this call. - * - * @param other Tree to move. - */ - Octree(Octree&& other); - - /** - * Initialize the tree from a boost::serialization archive. - * - * @param ar Archive to load tree from. Must be an iarchive, not an oarchive. - */ - template - Octree( - Archive& ar, - const typename std::enable_if_t* = 0); - - /** - * Destroy the tree. - */ - ~Octree(); - - //! Return the dataset used by this node. - const MatType& Dataset() const { return *dataset; } - - //! Get the pointer to the parent. - Octree* Parent() const { return parent; } - //! Modify the pointer to the parent (be careful!). - Octree*& Parent() { return parent; } - - //! Return the bound object for this node. - const bound::HRectBound& Bound() const { return bound; } - //! Modify the bound object for this node. - bound::HRectBound& Bound() { return bound; } - - //! Return the statistic object for this node. - const StatisticType& Stat() const { return stat; } - //! Modify the statistic object for this node. - StatisticType& Stat() { return stat; } - - //! Return the number of children in this node. - size_t NumChildren() const; - - //! Return the metric that this tree uses. - MetricType Metric() const { return MetricType(); } - - /** - * Return the index of the nearest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ - template - size_t GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0) const; - - /** - * Return the index of the furthest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ - template - size_t GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0) const; - - /** - * Return whether or not the node is a leaf. - */ - bool IsLeaf() const { return NumChildren() == 0; } - - /** - * Return the index of the nearest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ - size_t GetNearestChild(const Octree& queryNode) const; - - /** - * Return the index of the furthest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ - size_t GetFurthestChild(const Octree& queryNode) const; - - /** - * Return the furthest distance to a point held in this node. If this is not - * a leaf node, then the distance is 0 because the node holds no points. - */ - ElemType FurthestPointDistance() const; - - /** - * Return the furthest possible descendant distance. This returns the maximum - * distance from the centroid to the edge of the bound and not the empirical - * quantity which is the actual furthest descendant distance. So the actual - * furthest descendant distance may be less than what this method returns (but - * it will never be greater than this). - */ - ElemType FurthestDescendantDistance() const; - - //! Return the minimum distance from the center of the node to any bound edge. - ElemType MinimumBoundDistance() const; - - //! Return the distance from the center of this node to the center of the - //! parent node. - ElemType ParentDistance() const { return parentDistance; } - //! Modify the distance from the center of this node to the center of the - //! parent node. - ElemType& ParentDistance() { return parentDistance; } - - /** - * Return the specified child. If the index is out of bounds, unspecified - * behavior will occur. - */ - const Octree& Child(const size_t child) const { return *children[child]; } - - /** - * Return the specified child. If the index is out of bounds, unspecified - * behavior will occur. - */ - Octree& Child(const size_t child) { return *children[child]; } - - /** - * Return the pointer to the given child. This allows the child itself to be - * modified. - */ - Octree*& ChildPtr(const size_t child) { return children[child]; } - - //! Return the number of points in this node (0 if not a leaf). - size_t NumPoints() const; - - //! Return the number of descendants of this node. - size_t NumDescendants() const; - - /** - * Return the index (with reference to the dataset) of a particular - * descendant. - */ - size_t Descendant(const size_t index) const; - - /** - * Return the index (with reference to the dataset) of a particular point in - * this node. If the given index is invalid (i.e. if it is greater than - * NumPoints()), the indices returned will be invalid. - */ - size_t Point(const size_t index) const; - - //! Return the minimum distance to another node. - ElemType MinDistance(const Octree& other) const; - //! Return the maximum distance to another node. - ElemType MaxDistance(const Octree& other) const; - //! Return the minimum and maximum distance to another node. - math::RangeType RangeDistance(const Octree& other) const; - - //! Return the minimum distance to the given point. - template - ElemType MinDistance( - const VecType& point, - typename std::enable_if_t::value>* = 0) const; - //! Return the maximum distance to the given point. - template - ElemType MaxDistance( - const VecType& point, - typename std::enable_if_t::value>* = 0) const; - //! Return the minimum and maximum distance to another node. - template - math::RangeType RangeDistance( - const VecType& point, - typename std::enable_if_t::value>* = 0) const; - - //! Store the center of the bounding region in the given vector. - void Center(arma::vec& center) const { bound.Center(center); } - - //! Serialize the tree. - template - void serialize(Archive& ar, const unsigned int /* version */); - - protected: - /** - * A default constructor. This is meant to only be used with - * boost::serialization, which is allowed with the friend declaration below. - * This does not return a valid treee! The method must be protected, so that - * the serialization shim can work with the default constructor. - */ - Octree(); - - //! Friend access is given for the default constructor. - friend class boost::serialization::access; - - private: - /** - * Split the node, using the given center and the given maximum width of this - * node. - * - * @param center Center of the node. - * @param width Width of the current node. - * @param maxLeafSize Maximum number of points allowed in a leaf. - */ - void SplitNode(const arma::vec& center, - const double width, - const size_t maxLeafSize); - - /** - * Split the node, using the given center and the given maximum width of this - * node, and fill the mappings vector. - * - * @param center Center of the node. - * @param width Width of the current node. - * @param oldFromNew Mappings from old to new. - * @param maxLeafSize Maximum number of points allowed in a leaf. - */ - void SplitNode(const arma::vec& center, - const double width, - std::vector& oldFromNew, - const size_t maxLeafSize); - - /** - * This is used for sorting points while splitting. - */ - struct SplitType - { - struct SplitInfo - { - //! Create the SplitInfo object. - SplitInfo(const size_t d, const arma::vec& c) : d(d), center(c) {} - - //! The dimension we are splitting on. - size_t d; - //! The center of the node. - const arma::vec& center; - }; - - template - static bool AssignToLeftNode(const VecType& point, const SplitInfo& s) - { - return point[s.d] < s.center[s.d]; - } - }; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "octree_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/octree/octree_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/octree/octree_impl.hpp deleted file mode 100644 index 7477d1e4b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/octree/octree_impl.hpp +++ /dev/null @@ -1,873 +0,0 @@ -/** - * @file octree_impl.hpp - * @author Ryan Curtin - * - * Implementation of generalized octree (Octree). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_OCTREE_OCTREE_IMPL_HPP -#define MLPACK_CORE_TREE_OCTREE_OCTREE_IMPL_HPP - -#include "octree.hpp" -#include -#include - -namespace mlpack { -namespace tree { - -//! Construct the tree. -template -Octree::Octree(const MatType& dataset, - const size_t maxLeafSize) : - begin(0), - count(dataset.n_cols), - bound(dataset.n_rows), - dataset(new MatType(dataset)), - parent(NULL), - parentDistance(0.0) -{ - if (count > 0) - { - // Calculate empirical center of data. - bound |= *this->dataset; - arma::vec center; - bound.Center(center); - - double maxWidth = 0.0; - for (size_t i = 0; i < bound.Dim(); ++i) - if (bound[i].Hi() - bound[i].Lo() > maxWidth) - maxWidth = bound[i].Hi() - bound[i].Lo(); - - SplitNode(center, maxWidth, maxLeafSize); - - furthestDescendantDistance = 0.5 * bound.Diameter(); - } - else - { - furthestDescendantDistance = 0.0; - } - - // Initialize the statistic. - stat = StatisticType(*this); -} - -//! Construct the tree. -template -Octree::Octree( - const MatType& dataset, - std::vector& oldFromNew, - const size_t maxLeafSize) : - begin(0), - count(dataset.n_cols), - bound(dataset.n_rows), - dataset(new MatType(dataset)), - parent(NULL), - parentDistance(0.0) -{ - oldFromNew.resize(this->dataset->n_cols); - for (size_t i = 0; i < this->dataset->n_cols; ++i) - oldFromNew[i] = i; - - if (count > 0) - { - // Calculate empirical center of data. - bound |= *this->dataset; - arma::vec center; - bound.Center(center); - - double maxWidth = 0.0; - for (size_t i = 0; i < bound.Dim(); ++i) - if (bound[i].Hi() - bound[i].Lo() > maxWidth) - maxWidth = bound[i].Hi() - bound[i].Lo(); - - SplitNode(center, maxWidth, oldFromNew, maxLeafSize); - - furthestDescendantDistance = 0.5 * bound.Diameter(); - } - else - { - furthestDescendantDistance = 0.0; - } - - // Initialize the statistic. - stat = StatisticType(*this); -} - -//! Construct the tree. -template -Octree::Octree( - const MatType& dataset, - std::vector& oldFromNew, - std::vector& newFromOld, - const size_t maxLeafSize) : - begin(0), - count(dataset.n_cols), - bound(dataset.n_rows), - dataset(new MatType(dataset)), - parent(NULL), - parentDistance(0.0) -{ - oldFromNew.resize(this->dataset->n_cols); - for (size_t i = 0; i < this->dataset->n_cols; ++i) - oldFromNew[i] = i; - - if (count > 0) - { - // Calculate empirical center of data. - bound |= *this->dataset; - arma::vec center; - bound.Center(center); - - double maxWidth = 0.0; - for (size_t i = 0; i < bound.Dim(); ++i) - if (bound[i].Hi() - bound[i].Lo() > maxWidth) - maxWidth = bound[i].Hi() - bound[i].Lo(); - - SplitNode(center, maxWidth, oldFromNew, maxLeafSize); - - furthestDescendantDistance = 0.5 * bound.Diameter(); - } - else - { - furthestDescendantDistance = 0.0; - } - - // Initialize the statistic. - stat = StatisticType(*this); - - // Map the newFromOld indices correctly. - newFromOld.resize(this->dataset->n_cols); - for (size_t i = 0; i < this->dataset->n_cols; i++) - newFromOld[oldFromNew[i]] = i; -} - -//! Construct the tree. -template -Octree::Octree(MatType&& dataset, - const size_t maxLeafSize) : - begin(0), - count(dataset.n_cols), - bound(dataset.n_rows), - dataset(new MatType(std::move(dataset))), - parent(NULL), - parentDistance(0.0) -{ - if (count > 0) - { - // Calculate empirical center of data. - bound |= *this->dataset; - arma::vec center; - bound.Center(center); - - double maxWidth = 0.0; - for (size_t i = 0; i < bound.Dim(); ++i) - if (bound[i].Hi() - bound[i].Lo() > maxWidth) - maxWidth = bound[i].Hi() - bound[i].Lo(); - - SplitNode(center, maxWidth, maxLeafSize); - - furthestDescendantDistance = 0.5 * bound.Diameter(); - } - else - { - furthestDescendantDistance = 0.0; - } - - // Initialize the statistic. - stat = StatisticType(*this); -} - -//! Construct the tree. -template -Octree::Octree( - MatType&& dataset, - std::vector& oldFromNew, - const size_t maxLeafSize) : - begin(0), - count(dataset.n_cols), - bound(dataset.n_rows), - dataset(new MatType(std::move(dataset))), - parent(NULL), - parentDistance(0.0) -{ - oldFromNew.resize(this->dataset->n_cols); - for (size_t i = 0; i < this->dataset->n_cols; ++i) - oldFromNew[i] = i; - - if (count > 0) - { - // Calculate empirical center of data. - bound |= *this->dataset; - arma::vec center; - bound.Center(center); - - double maxWidth = 0.0; - for (size_t i = 0; i < bound.Dim(); ++i) - if (bound[i].Hi() - bound[i].Lo() > maxWidth) - maxWidth = bound[i].Hi() - bound[i].Lo(); - - SplitNode(center, maxWidth, oldFromNew, maxLeafSize); - - furthestDescendantDistance = 0.5 * bound.Diameter(); - } - else - { - furthestDescendantDistance = 0.0; - } - - // Initialize the statistic. - stat = StatisticType(*this); -} - -//! Construct the tree. -template -Octree::Octree( - MatType&& dataset, - std::vector& oldFromNew, - std::vector& newFromOld, - const size_t maxLeafSize) : - begin(0), - count(dataset.n_cols), - bound(dataset.n_rows), - dataset(new MatType(std::move(dataset))), - parent(NULL), - parentDistance(0.0) -{ - oldFromNew.resize(this->dataset->n_cols); - for (size_t i = 0; i < this->dataset->n_cols; ++i) - oldFromNew[i] = i; - - if (count > 0) - { - // Calculate empirical center of data. - bound |= *this->dataset; - arma::vec center; - bound.Center(center); - - double maxWidth = 0.0; - for (size_t i = 0; i < bound.Dim(); ++i) - if (bound[i].Hi() - bound[i].Lo() > maxWidth) - maxWidth = bound[i].Hi() - bound[i].Lo(); - - SplitNode(center, maxWidth, oldFromNew, maxLeafSize); - - furthestDescendantDistance = 0.5 * bound.Diameter(); - } - else - { - furthestDescendantDistance = 0.0; - } - - // Initialize the statistic. - stat = StatisticType(*this); - - // Map the newFromOld indices correctly. - newFromOld.resize(this->dataset->n_cols); - for (size_t i = 0; i < this->dataset->n_cols; i++) - newFromOld[oldFromNew[i]] = i; -} - -//! Construct a child node. -template -Octree::Octree( - Octree* parent, - const size_t begin, - const size_t count, - const arma::vec& center, - const double width, - const size_t maxLeafSize) : - begin(begin), - count(count), - bound(parent->dataset->n_rows), - dataset(parent->dataset), - parent(parent) -{ - // Calculate empirical center of data. - bound |= dataset->cols(begin, begin + count - 1); - - // Now split the node. - SplitNode(center, width, maxLeafSize); - - // Calculate the distance from the empirical center of this node to the - // empirical center of the parent. - arma::vec trueCenter, parentCenter; - bound.Center(trueCenter); - parent->Bound().Center(parentCenter); - parentDistance = metric.Evaluate(trueCenter, parentCenter); - - furthestDescendantDistance = 0.5 * bound.Diameter(); - - // Initialize the statistic. - stat = StatisticType(*this); -} - -//! Construct a child node. -template -Octree::Octree( - Octree* parent, - const size_t begin, - const size_t count, - std::vector& oldFromNew, - const arma::vec& center, - const double width, - const size_t maxLeafSize) : - begin(begin), - count(count), - bound(parent->dataset->n_rows), - dataset(parent->dataset), - parent(parent) -{ - // Calculate empirical center of data. - bound |= dataset->cols(begin, begin + count - 1); - - // Now split the node. - SplitNode(center, width, oldFromNew, maxLeafSize); - - // Calculate the distance from the empirical center of this node to the - // empirical center of the parent. - arma::vec trueCenter, parentCenter; - bound.Center(trueCenter); - parent->Bound().Center(parentCenter); - parentDistance = metric.Evaluate(trueCenter, parentCenter); - - furthestDescendantDistance = 0.5 * bound.Diameter(); - - // Initialize the statistic. - stat = StatisticType(*this); -} - -//! Copy the given tree. -template -Octree::Octree(const Octree& other) : - begin(other.begin), - count(other.count), - bound(other.bound), - dataset((other.parent == NULL) ? new MatType(*other.dataset) : NULL), - parent(NULL), - stat(other.stat), - parentDistance(other.parentDistance), - furthestDescendantDistance(other.furthestDescendantDistance), - metric(other.metric) -{ - // If we have any children, we need to create them, and then ensure that their - // parent links are set right. - for (size_t i = 0; i < other.NumChildren(); ++i) - { - children.push_back(new Octree(other.Child(i))); - children[i]->parent = this; - children[i]->dataset = this->dataset; - } -} - -//! Move the given tree. -template -Octree::Octree(Octree&& other) : - children(std::move(other.children)), - begin(other.begin), - count(other.count), - bound(std::move(other.bound)), - dataset(other.dataset), - parent(other.parent), - stat(std::move(other.stat)), - parentDistance(other.parentDistance), - furthestDescendantDistance(other.furthestDescendantDistance), - metric(std::move(other.metric)) -{ - // Update the parent pointers of the direct children. - for (size_t i = 0; i < children.size(); ++i) - children[i]->parent = this; - - other.begin = 0; - other.count = 0; - other.dataset = new MatType(); - other.parentDistance = 0.0; - other.furthestDescendantDistance = 0.0; - other.parent = NULL; -} - -template -Octree::Octree() : - begin(0), - count(0), - bound(0), - dataset(new MatType()), - parent(NULL), - parentDistance(0.0), - furthestDescendantDistance(0.0) -{ - // Nothing to do. -} - -template -template -Octree::Octree( - Archive& ar, - const typename std::enable_if_t*) : - Octree() // Create an empty tree. -{ - // De-serialize the tree into this object. - ar >> BOOST_SERIALIZATION_NVP(*this); -} - -template -Octree::~Octree() -{ - // Delete the dataset if we aren't the parent. - if (!parent) - delete dataset; - - // Now delete each of the children. - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); -} - -template -size_t Octree::NumChildren() const -{ - return children.size(); -} - -template -template -size_t Octree::GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>*) const -{ - // It's possible that this could be improved by caching which children we have - // and which we don't, but for now this is just a brute force search. - ElemType bestDistance = DBL_MAX; - size_t bestIndex = NumChildren(); - for (size_t i = 0; i < NumChildren(); ++i) - { - const double dist = children[i]->MinDistance(point); - if (dist < bestDistance) - { - bestDistance = dist; - bestIndex = i; - } - } - - return bestIndex; -} - -template -template -size_t Octree::GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>*) const -{ - // It's possible that this could be improved by caching which children we have - // and which we don't, but for now this is just a brute force search. - ElemType bestDistance = -1.0; // Initialize to invalid distance. - size_t bestIndex = NumChildren(); - for (size_t i = 0; i < NumChildren(); ++i) - { - const double dist = children[i]->MaxDistance(point); - if (dist > bestDistance) - { - bestDistance = dist; - bestIndex = i; - } - } - - return bestIndex; -} - -template -size_t Octree::GetNearestChild( - const Octree& queryNode) const -{ - // It's possible that this could be improved by caching which children we have - // and which we don't, but for now this is just a brute force search. - ElemType bestDistance = DBL_MAX; - size_t bestIndex = NumChildren(); - for (size_t i = 0; i < NumChildren(); ++i) - { - const double dist = children[i]->MinDistance(queryNode); - if (dist < bestDistance) - { - bestDistance = dist; - bestIndex = i; - } - } - - return bestIndex; -} - -template -size_t Octree::GetFurthestChild( - const Octree& queryNode) const -{ - // It's possible that this could be improved by caching which children we have - // and which we don't, but for now this is just a brute force search. - ElemType bestDistance = -1.0; // Initialize to invalid distance. - size_t bestIndex = NumChildren(); - for (size_t i = 0; i < NumChildren(); ++i) - { - const double dist = children[i]->MaxDistance(queryNode); - if (dist > bestDistance) - { - bestDistance = dist; - bestIndex = i; - } - } - - return bestIndex; -} - -template -typename Octree::ElemType -Octree::FurthestPointDistance() - const -{ - // If we are not a leaf, then this distance is 0. Otherwise, return the - // furthest descendant distance. - return (children.size() > 0) ? 0.0 : furthestDescendantDistance; -} - -template -typename Octree::ElemType -Octree::FurthestDescendantDistance() const -{ - return furthestDescendantDistance; -} - -template -typename Octree::ElemType -Octree::MinimumBoundDistance() const -{ - return bound.MinWidth() / 2.0; -} - -template -size_t Octree::NumPoints() const -{ - // We have no points unless we are a leaf; - return (children.size() > 0) ? 0 : count; -} - -template -size_t Octree::NumDescendants() const -{ - return count; -} - -template -size_t Octree::Descendant( - const size_t index) const -{ - return begin + index; -} - -template -size_t Octree::Point(const size_t index) - const -{ - return begin + index; -} - -template -typename Octree::ElemType -Octree::MinDistance(const Octree& other) - const -{ - return bound.MinDistance(other.Bound()); -} - -template -typename Octree::ElemType -Octree::MaxDistance(const Octree& other) - const -{ - return bound.MaxDistance(other.Bound()); -} - -template -math::RangeType::ElemType> -Octree::RangeDistance(const Octree& other) - const -{ - return bound.RangeDistance(other.Bound()); -} - -template -template -typename Octree::ElemType -Octree::MinDistance( - const VecType& point, - typename std::enable_if_t::value>*) const -{ - return bound.MinDistance(point); -} - -template -template -typename Octree::ElemType -Octree::MaxDistance( - const VecType& point, - typename std::enable_if_t::value>*) const -{ - return bound.MaxDistance(point); -} - - -template -template -math::RangeType::ElemType> -Octree::RangeDistance( - const VecType& point, - typename std::enable_if_t::value>*) const -{ - return bound.RangeDistance(point); -} - -//! Serialize the tree. -template -template -void Octree::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // If we're loading and we have children, they need to be deleted. - if (Archive::is_loading::value) - { - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); - - if (!parent) - delete dataset; - - parent = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(begin); - ar & BOOST_SERIALIZATION_NVP(count); - ar & BOOST_SERIALIZATION_NVP(bound); - ar & BOOST_SERIALIZATION_NVP(stat); - ar & BOOST_SERIALIZATION_NVP(parentDistance); - ar & BOOST_SERIALIZATION_NVP(furthestDescendantDistance); - ar & BOOST_SERIALIZATION_NVP(metric); - ar & BOOST_SERIALIZATION_NVP(dataset); - - ar & BOOST_SERIALIZATION_NVP(children); - - if (Archive::is_loading::value) - { - for (size_t i = 0; i < children.size(); ++i) - children[i]->parent = this; - } -} - -//! Split the node. -template -void Octree::SplitNode( - const arma::vec& center, - const double width, - const size_t maxLeafSize) -{ - // No need to split if we have fewer than the maximum number of points in this - // node. - if (count <= maxLeafSize) - return; - - // This will hold the index of the first point in each child. - arma::Col childBegins(((size_t) 1 << dataset->n_rows) + 1); - childBegins[0] = begin; - childBegins[childBegins.n_elem - 1] = begin + count; - - // We will make log2(dim) passes, splitting along the last down to the first - // dimension. The tuple holds { dim, begin, count, leftChildIndex }. - std::stack> stack; - stack.push(std::tuple(dataset->n_rows - 1, - begin, count, 0)); - - while (!stack.empty()) - { - std::tuple t = stack.top(); - stack.pop(); - - const size_t d = std::get<0>(t); - const size_t childBegin = std::get<1>(t); - const size_t childCount = std::get<2>(t); - const size_t leftChildIndex = std::get<3>(t); - - // Perform a "half-split": after this split, all points belonging to - // children of index 2^(d - 1) - 1 and less will be on the left side, and - // all points belonging to children of index 2^(d - 1) and above will be on - // the right side. - typename SplitType::SplitInfo s(d, center); - const size_t firstRight = split::PerformSplit(*dataset, - childBegin, childCount, s); - - // We can set the first index of the right child. The first index of the - // left child is already set. - const size_t rightChildIndex = leftChildIndex + ((size_t) 1 << d); - childBegins[rightChildIndex] = firstRight; - - // Now we have to recurse, if this was not the last dimension. - if (d != 0) - { - if (firstRight > childBegin) - { - stack.push(std::tuple(d - 1, childBegin, - firstRight - childBegin, leftChildIndex)); - } - else - { - // Set beginning indices correctly for all children below this level. - for (size_t c = leftChildIndex + 1; c < rightChildIndex; ++c) - childBegins[c] = childBegins[leftChildIndex]; - } - - if (firstRight < childBegin + childCount) - { - stack.push(std::tuple(d - 1, firstRight, - childCount - (firstRight - childBegin), rightChildIndex)); - } - else - { - // Set beginning indices correctly for all children below this level. - for (size_t c = rightChildIndex + 1; - c < rightChildIndex + (rightChildIndex - leftChildIndex); ++c) - childBegins[c] = childBegins[rightChildIndex]; - } - } - } - - // Now that the dataset is reordered, we can create the children. - arma::vec childCenter(center.n_elem); - const double childWidth = width / 2.0; - for (size_t i = 0; i < childBegins.n_elem - 1; ++i) - { - // If the child has no points, don't create it. - if (childBegins[i + 1] - childBegins[i] == 0) - continue; - - // Create the correct center. - for (size_t d = 0; d < center.n_elem; ++d) - { - // Is the dimension "right" (1) or "left" (0)? - if (((i >> d) & 1) == 0) - childCenter[d] = center[d] - childWidth; - else - childCenter[d] = center[d] + childWidth; - } - - children.push_back(new Octree(this, childBegins[i], - childBegins[i + 1] - childBegins[i], childCenter, childWidth, - maxLeafSize)); - } -} - -//! Split the node, and store mappings. -template -void Octree::SplitNode( - const arma::vec& center, - const double width, - std::vector& oldFromNew, - const size_t maxLeafSize) -{ - // No need to split if we have fewer than the maximum number of points in this - // node. - if (count <= maxLeafSize) - return; - - // This will hold the index of the first point in each child. - arma::Col childBegins(((size_t) 1 << dataset->n_rows) + 1); - childBegins[0] = begin; - childBegins[childBegins.n_elem - 1] = begin + count; - - // We will make log2(dim) passes, splitting along the last down to the first - // dimension. The tuple holds { dim, begin, count, leftChildIndex }. - std::stack> stack; - stack.push(std::tuple(dataset->n_rows - 1, - begin, count, 0)); - - while (!stack.empty()) - { - std::tuple t = stack.top(); - stack.pop(); - - const size_t d = std::get<0>(t); - const size_t childBegin = std::get<1>(t); - const size_t childCount = std::get<2>(t); - const size_t leftChildIndex = std::get<3>(t); - - // Perform a "half-split": after this split, all points belonging to - // children of index 2^(d - 1) - 1 and less will be on the left side, and - // all points belonging to children of index 2^(d - 1) and above will be on - // the right side. - typename SplitType::SplitInfo s(d, center); - const size_t firstRight = split::PerformSplit(*dataset, - childBegin, childCount, s, oldFromNew); - - // We can set the first index of the right child. The first index of the - // left child is already set. - const size_t rightChildIndex = leftChildIndex + ((size_t) 1 << d); - childBegins[rightChildIndex] = firstRight; - - // Now we have to recurse, if this was not the last dimension. - if (d != 0) - { - if (firstRight > childBegin) - { - stack.push(std::tuple(d - 1, childBegin, - firstRight - childBegin, leftChildIndex)); - } - else - { - // Set beginning indices correctly for all children below this level. - for (size_t c = leftChildIndex + 1; c < rightChildIndex; ++c) - childBegins[c] = childBegins[leftChildIndex]; - } - - if (firstRight < childBegin + childCount) - { - stack.push(std::tuple(d - 1, firstRight, - childCount - (firstRight - childBegin), rightChildIndex)); - } - else - { - // Set beginning indices correctly for all children below this level. - for (size_t c = rightChildIndex + 1; - c < rightChildIndex + (rightChildIndex - leftChildIndex); ++c) - childBegins[c] = childBegins[rightChildIndex]; - } - } - } - - // Now that the dataset is reordered, we can create the children. - arma::vec childCenter(center.n_elem); - const double childWidth = width / 2.0; - for (size_t i = 0; i < childBegins.n_elem - 1; ++i) - { - // If the child has no points, don't create it. - if (childBegins[i + 1] - childBegins[i] == 0) - continue; - - // Create the correct center. - for (size_t d = 0; d < center.n_elem; ++d) - { - // Is the dimension "right" (1) or "left" (0)? - if (((i >> d) & 1) == 0) - childCenter[d] = center[d] - childWidth; - else - childCenter[d] = center[d] + childWidth; - } - - children.push_back(new Octree(this, childBegins[i], - childBegins[i + 1] - childBegins[i], oldFromNew, childCenter, - childWidth, maxLeafSize)); - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/octree/single_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/octree/single_tree_traverser.hpp deleted file mode 100644 index 6eeb2f4cb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/octree/single_tree_traverser.hpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file single_tree_traverser.hpp - * @author Ryan Curtin - * - * Definition of the single tree traverser for the octree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_OCTREE_SINGLE_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_OCTREE_SINGLE_TREE_TRAVERSER_HPP - -#include -#include "octree.hpp" - -namespace mlpack { -namespace tree { - -template -template -class Octree::SingleTreeTraverser -{ - public: - /** - * Instantiate the traverser with the given rule set. - */ - SingleTreeTraverser(RuleType& rule); - - /** - * Traverse the reference tree with the given query point. This does not - * reset the number of pruned nodes. - * - * @param queryIndex Index of query point. - * @param referenceNode Node in reference tree. - */ - void Traverse(const size_t queryIndex, Octree& referenceNode); - - //! Get the number of pruned nodes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of pruned nodes. - size_t& NumPrunes() { return numPrunes; } - - private: - //! The instantiated rule. - RuleType& rule; - //! The number of reference nodes that have been pruned. - size_t numPrunes; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "single_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/octree/single_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/octree/single_tree_traverser_impl.hpp deleted file mode 100644 index 3e0ce8a31..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/octree/single_tree_traverser_impl.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file single_tree_traverser_impl.hpp - * @author Ryan Curtin - * - * Implementation of the single tree traverser for octrees. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_OCTREE_SINGLE_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_OCTREE_SINGLE_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "single_tree_traverser.hpp" - -namespace mlpack { -namespace tree { - -template -template -Octree::SingleTreeTraverser:: - SingleTreeTraverser(RuleType& rule) : - rule(rule) -{ - // Nothing to do. -} - -template -template -void Octree::SingleTreeTraverser:: - Traverse(const size_t queryIndex, Octree& referenceNode) -{ - // If we are a leaf, run the base cases. - if (referenceNode.NumChildren() == 0) - { - const size_t refBegin = referenceNode.Point(0); - const size_t refEnd = refBegin + referenceNode.NumPoints(); - for (size_t r = refBegin; r < refEnd; ++r) - rule.BaseCase(queryIndex, r); - } - else - { - // Do a prioritized recursion, by scoring all candidates and then sorting - // them. - arma::vec scores(referenceNode.NumChildren()); - for (size_t i = 0; i < scores.n_elem; ++i) - scores[i] = rule.Score(queryIndex, referenceNode.Child(i)); - - // Sort the scores. - arma::uvec sortedIndices = arma::sort_index(scores); - - for (size_t i = 0; i < sortedIndices.n_elem; ++i) - { - // If the node is pruned, all subsequent nodes in sorted order will also - // be pruned. - if (scores[sortedIndices[i]] == DBL_MAX) - { - numPrunes += (sortedIndices.n_elem - i); - break; - } - - Traverse(queryIndex, referenceNode.Child(sortedIndices[i])); - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/octree/traits.hpp b/src/sdk/mlpack/include/mlpack/core/tree/octree/traits.hpp deleted file mode 100644 index 6273739cf..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/octree/traits.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @file traits.hpp - * @author Ryan Curtin - * - * Specialization of the TreeTraits class for the Octree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_OCTREE_TRAITS_HPP -#define MLPACK_CORE_TREE_OCTREE_TRAITS_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * This is a specialization of the TreeTraits class to the Octree tree type. It - * defines characteristics of the octree, and is used to help write - * tree-independent (but still optimized) tree-based algorithms. See - * mlpack/core/tree/tree_traits.hpp for more information. - */ -template -class TreeTraits> -{ - public: - /** - * No octree nodes will overlap. - */ - static const bool HasOverlappingChildren = false; - - /** - * Points are not shared across nodes in the octree. - */ - static const bool HasDuplicatedPoints = false; - - /** - * There is no guarantee that the first point in a node is its centroid. - */ - static const bool FirstPointIsCentroid = false; - - /** - * Points are not contained at multiple levels of the octree. - */ - static const bool HasSelfChildren = false; - - /** - * Points are rearranged during building of the tree. - */ - static const bool RearrangesDataset = true; - - /** - * This is not necessarily a binary tree. - */ - static const bool BinaryTree = false; - - /** - * NumDescendants() represents the number of unique descendant points. - */ - static const bool UniqueNumDescendants = true; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/perform_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/perform_split.hpp deleted file mode 100644 index f8449dd64..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/perform_split.hpp +++ /dev/null @@ -1,160 +0,0 @@ -/** - * @file perform_split.hpp - * @author Mikhail Lozhnikov - * - * This file contains functions that implement the default binary split - * behavior. The functions perform the actual splitting. This will order - * the dataset such that points that belong to the left subtree are on the left - * of the split column, and points from the right subtree are on the right side - * of the split column. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_PERFORM_SPLIT_HPP -#define MLPACK_CORE_TREE_PERFORM_SPLIT_HPP - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { -namespace split { - -/** - * This function implements the default split behavior i.e. it rearranges - * points according to the split information. The SplitType::AssignToLeftNode() - * function is used in order to determine the child that contains any particular - * point. - * - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - */ -template -size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const typename SplitType::SplitInfo& splitInfo) -{ - // This method modifies the input dataset. We loop both from the left and - // right sides of the points contained in this node. - size_t left = begin; - size_t right = begin + count - 1; - - // First half-iteration of the loop is out here because the termination - // condition is in the middle. - while ((left <= right) && - (SplitType::AssignToLeftNode(data.col(left), splitInfo))) - left++; - while ((!SplitType::AssignToLeftNode(data.col(right), splitInfo)) && - (left <= right) && (right > 0)) - right--; - - // Shortcut for when all points are on the right. - if (left == right && right == 0) - return left; - - while (left <= right) - { - // Swap columns. - data.swap_cols(left, right); - - // See how many points on the left are correct. When they are correct, - // increase the left counter accordingly. When we encounter one that isn't - // correct, stop. We will switch it later. - while (SplitType::AssignToLeftNode(data.col(left), splitInfo) && - (left <= right)) - left++; - - // Now see how many points on the right are correct. When they are correct, - // decrease the right counter accordingly. When we encounter one that isn't - // correct, stop. We will switch it with the wrong point we found in the - // previous loop. - while ((!SplitType::AssignToLeftNode(data.col(right), splitInfo)) && - (left <= right)) - right--; - } - - Log::Assert(left == right + 1); - - return left; -} - -/** - * This function implements the default split behavior i.e. it rearranges - * points according to the split information. The SplitType::AssignToLeftNode() - * function is used in order to determine the child that contains any particular - * point. The function takes care of indices and returns the list of changed - * indices. - * - * @param data The dataset used by the binary space tree. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param splitInfo The information about the split. - * @param oldFromNew Vector which will be filled with the old positions for - * each new point. - */ -template -size_t PerformSplit(MatType& data, - const size_t begin, - const size_t count, - const typename SplitType::SplitInfo& splitInfo, - std::vector& oldFromNew) -{ - // This method modifies the input dataset. We loop both from the left and - // right sides of the points contained in this node. - size_t left = begin; - size_t right = begin + count - 1; - - // First half-iteration of the loop is out here because the termination - // condition is in the middle. - while ((left <= right) && - (SplitType::AssignToLeftNode(data.col(left), splitInfo))) - left++; - while ((!SplitType::AssignToLeftNode(data.col(right), splitInfo)) && - (left <= right) && (right > 0)) - right--; - - // Shortcut for when all points are on the right. - if (left == right && right == 0) - return left; - - while (left <= right) - { - // Swap columns. - data.swap_cols(left, right); - - // Update the indices for what we changed. - size_t t = oldFromNew[left]; - oldFromNew[left] = oldFromNew[right]; - oldFromNew[right] = t; - - // See how many points on the left are correct. When they are correct, - // increase the left counter accordingly. When we encounter one that isn't - // correct, stop. We will switch it later. - while (SplitType::AssignToLeftNode(data.col(left), splitInfo) && - (left <= right)) - left++; - - // Now see how many points on the right are correct. When they are correct, - // decrease the right counter accordingly. When we encounter one that isn't - // correct, stop. We will switch it with the wrong point we found in the - // previous loop. - while ((!SplitType::AssignToLeftNode(data.col(right), splitInfo)) && - (left <= right)) - right--; - } - - Log::Assert(left == right + 1); - return left; -} - -} // namespace split -} // namespace tree -} // namespace mlpack - - -#endif // MLPACK_CORE_TREE_BINARY_SPACE_TREE_PERFORM_SPLIT_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree.hpp deleted file mode 100644 index f6530ee38..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree.hpp +++ /dev/null @@ -1,47 +0,0 @@ -/** - * @file rectangle_tree.hpp - * @author Andrew Wells - * - * Include all the necessary files to use the Rectangle Type Trees (RTree, - * RStarTree, XTree, and HilbertRTree). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_HPP - -/* We include bounds.hpp since it gives us the necessary files. - * However, we will not use the "ballbounds" option. - */ -#include "bounds.hpp" -#include "rectangle_tree/rectangle_tree.hpp" -#include "rectangle_tree/single_tree_traverser.hpp" -#include "rectangle_tree/single_tree_traverser_impl.hpp" -#include "rectangle_tree/dual_tree_traverser.hpp" -#include "rectangle_tree/dual_tree_traverser_impl.hpp" -#include "rectangle_tree/r_tree_split.hpp" -#include "rectangle_tree/r_star_tree_split.hpp" -#include "rectangle_tree/no_auxiliary_information.hpp" -#include "rectangle_tree/r_tree_descent_heuristic.hpp" -#include "rectangle_tree/r_star_tree_descent_heuristic.hpp" -#include "rectangle_tree/x_tree_split.hpp" -#include "rectangle_tree/x_tree_auxiliary_information.hpp" -#include "rectangle_tree/hilbert_r_tree_descent_heuristic.hpp" -#include "rectangle_tree/hilbert_r_tree_split.hpp" -#include "rectangle_tree/hilbert_r_tree_auxiliary_information.hpp" -#include "rectangle_tree/discrete_hilbert_value.hpp" -#include "rectangle_tree/r_plus_tree_descent_heuristic.hpp" -#include "rectangle_tree/r_plus_tree_split_policy.hpp" -#include "rectangle_tree/minimal_coverage_sweep.hpp" -#include "rectangle_tree/minimal_splits_number_sweep.hpp" -#include "rectangle_tree/r_plus_tree_split.hpp" -#include "rectangle_tree/r_plus_plus_tree_auxiliary_information.hpp" -#include "rectangle_tree/r_plus_plus_tree_descent_heuristic.hpp" -#include "rectangle_tree/r_plus_plus_tree_split_policy.hpp" -#include "rectangle_tree/traits.hpp" -#include "rectangle_tree/typedef.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/discrete_hilbert_value.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/discrete_hilbert_value.hpp deleted file mode 100644 index 2f7eddb42..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/discrete_hilbert_value.hpp +++ /dev/null @@ -1,292 +0,0 @@ -/** - * @file discrete_hilbert_value.hpp - * @author Mikhail Lozhnikov - * - * Definition of the DiscreteHilbertValue class, a class that calculates - * the ordering of points using the Hilbert curve. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_DISCRETE_HILBERT_VALUE_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_DISCRETE_HILBERT_VALUE_HPP - -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * The DiscreteHilbertValue class stores Hilbert values for all of the points in - * a RectangleTree node, and calculates Hilbert values for new points. This - * implementation calculates the full discrete Hilbert value; for a - * d-dimensional vector filled with elements of size E, each Hilbert value will - * take dE space. - */ -template -class DiscreteHilbertValue -{ - public: - //! Depending on the precision of the tree element type, we may need to use - //! uint32_t or uint64_t. - typedef typename std::conditional::type HilbertElemType; - - //! Default constructor. - DiscreteHilbertValue(); - - /** - * Construct this for the node tree. If the node is the root this method - * computes the Hilbert value for each point in the tree's dataset. - * - * @param node The node that stores this Hilbert value. - */ - template - DiscreteHilbertValue(const TreeType* tree); - - /** - * Create a Hilbert value object by copying from another one. - * - * @param other The object from which the value will be copied. - * @param tree The node that holds the Hilbert value. - * @param deepCopy If false, the dataset will not be copied. - */ - template - DiscreteHilbertValue(const DiscreteHilbertValue& other, - TreeType* tree, - bool deepCopy); - - /** - * Create a Hilbert value object by moving another one. - * - * @param other The Hilbert value object from which the value will be moved. - */ - DiscreteHilbertValue(DiscreteHilbertValue&& other); - - //! Free memory - ~DiscreteHilbertValue(); - - /** - * Compare two points. It returns 1 if the first point is greater than the - * second one, -1 if the first point is less than the second one and 0 if the - * Hilbert values of the points are equal. In order to do it this method - * computes the Hilbert values of the points. - * - * @param pt1 The first point. - * @param pt2 The second point. - */ - template - static int ComparePoints( - const VecType1& pt1, - const VecType2& pt2, - typename std::enable_if_t::value>* = 0, - typename std::enable_if_t::value>* = 0); - - /** - * Compare two Hilbert values. It returns 1 if the first value is greater than - * the second one, -1 if the first value is less than the second one and 0 if - * the values are equal. This method does not compute the Hilbert values. - * - * @param val1 The first point. - * @param val2 The second point. - */ - static int CompareValues(const DiscreteHilbertValue& val1, - const DiscreteHilbertValue& val2); - - /** - * Compare the largest Hilbert value of the node with the val value. It - * returns 1 if the value of the node is greater than val, -1 if the value of - * the node is less than val and 0 if the values are equal. This method does - * not compute the Hilbert values. - * - * @param val The Hilbert value to compare with. - */ - int CompareWith(const DiscreteHilbertValue& val) const; - - /** - * Compare the largest Hilbert value of the node with the Hilbert value of the - * point. It returns 1 if the value of the node is greater than the value of - * the point, -1 if the value of the node is less than the value of the point - * and 0 if the values are equal. This method computes the Hilbert value of - * the point. - * - * @param pt The point to compare with. - */ - template - int CompareWith( - const VecType& pt, - typename std::enable_if_t::value>* = 0) const; - - /** - * Compare the Hilbert value of the cached point with the Hilbert value of the - * given point. It returns 1 if the value of the node is greater than the - * value of the point, -1 if the value of the node is less than the value of - * the point and 0 if the values are equal. This method computes the Hilbert - * value of the point. - * - * @param pt The point to compare with. - */ - - template - int CompareWithCachedPoint( - const VecType& pt, - typename std::enable_if_t::value>* = 0) const; - - /** - * Update the largest Hilbert value of the node and insert the point in the - * local dataset if the node is a leaf. - * - * @param node The node in which the point is being inserted. - * @param point The number of the point being inserted. - */ - template - size_t InsertPoint(TreeType *node, - const VecType& pt, - typename std::enable_if_t::value>* = 0); - - /** - * Update the largest Hilbert value of the node. - * - * @param node The node being inserted. - */ - template - void InsertNode(TreeType* node); - - /** - * Update the largest Hilbert value of the node and delete the point from the - * local dataset. - * - * @param node The node from which the point is being deleted. - * @param localIndex The index of the point in the local dataset. - */ - template - void DeletePoint(TreeType* node, const size_t localIndex); - - /** - * Update the largest Hilbert value of the node. - * - * @param node The node from which another node is being deleted. - * @param nodeIndex The index of the node being deleted. - */ - template - void RemoveNode(TreeType* node, const size_t nodeIndex); - - /** - * Copy the local Hilbert value's pointer. - * - * @param val The DiscreteHilbertValue object from which the dataset - * will be copied. - */ - DiscreteHilbertValue& operator=(const DiscreteHilbertValue& val); - - /** - * Nullify the localHilbertValues pointer in order to prevent an invalid free. - */ - void NullifyData(); - - /** - * Update the largest Hilbert value and the local Hilbert values of an - * intermediate node. The children of the node (or the points that the node - * contains) should be arranged according to their Hilbert values. - * - * @param node The node in which the information should be updated. - */ - template - void UpdateLargestValue(TreeType* node); - - /** - * This method updates the largest Hilbert value of a leaf node and - * redistributes the Hilbert values of points according to their new position - * after the split algorithm. - * - * @param parent The parent of the node that was split. - * @param firstSibling The first cooperating sibling. - * @param lastSibling The last cooperating sibling. - */ - template - void RedistributeHilbertValues(TreeType* parent, - const size_t firstSibling, - const size_t lastSibling); - - /** - * Calculate the Hilbert value of the point pt. - * - * @param pt The point for which the Hilbert value should be calculated. - */ - template - static arma::Col CalculateValue( - const VecType& pt, - typename std::enable_if_t::value>* = 0); - - /** - * Compare two Hilbert values. It returns 1 if the first value is greater than - * the second one, -1 if the first value is less than the second one and 0 if - * the values are equal. This method does not compute the Hilbert values. - * - * @param value1 The first value. - * @param value2 The second value. - */ - static int CompareValues(const arma::Col& value1, - const arma::Col& value2); - - //! Return the number of values. - size_t NumValues() const { return numValues; } - //! Modify the number of values. - size_t& NumValues() { return numValues; } - - //! Return the Hilbert values. - const arma::Mat* LocalHilbertValues() const - { return localHilbertValues; } - //! Modify the Hilbert values. - arma::Mat*& LocalHilbertValues() - { return localHilbertValues; } - - //! Return the ownsLocalHilbertValues variable. - bool OwnsLocalHilbertValues() const { return ownsLocalHilbertValues; } - //! Modify the ownsLocalHilbertValues variable. - bool& OwnsLocalHilbertValues() { return ownsLocalHilbertValues; } - - //! Return the cached point (valueToInsert). - const arma::Col* ValueToInsert() const - { return valueToInsert; } - //! Modify the cached point (valueToInsert). - arma::Col* ValueToInsert() { return valueToInsert; } - - //! Return the ownsValueToInsert variable. - bool OwnsValueToInsert() const { return ownsValueToInsert; } - //! Modify the ownsValueToInsert variable. - bool& OwnsValueToInsert() { return ownsValueToInsert; } - private: - //! The number of bits that we can store. - static constexpr size_t order = sizeof(HilbertElemType) * CHAR_BIT; - //! The local Hilbert values. - arma::Mat* localHilbertValues; - //! Indicates that the node owns the localHilbertValues variable. - bool ownsLocalHilbertValues; - //! The number of values in the localHilbertValues dataset. - size_t numValues; - /** The Hilbert value of the point that is being inserted. - * The pointer is the same in all nodes. The value is updated in InsertPoint() - * if it is invoked at the root level. This variable helps to avoid - * multiple computation of the Hilbert value of a point in the insertion - * process. - */ - arma::Col* valueToInsert; - //! Indicates that the node owns the valueToInsert. - bool ownsValueToInsert; - - public: - template - void serialize(Archive& ar, const unsigned int /* version */); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "discrete_hilbert_value_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_DISCRETE_HILBERT_VALUE_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/discrete_hilbert_value_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/discrete_hilbert_value_impl.hpp deleted file mode 100644 index c3af2d79a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/discrete_hilbert_value_impl.hpp +++ /dev/null @@ -1,531 +0,0 @@ -/** - * @file discrete_hilbert_value.hpp - * @author Mikhail Lozhnikov - * - * Definition of the DiscreteHilbertValue class, a class that calculates - * the ordering of points using the Hilbert curve. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_DISCRETE_HILBERT_VALUE_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_DISCRETE_HILBERT_VALUE_IMPL_HPP - -#include "discrete_hilbert_value.hpp" - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -template -DiscreteHilbertValue::DiscreteHilbertValue() : - localHilbertValues(NULL), - ownsLocalHilbertValues(false), - numValues(0), - valueToInsert(NULL), - ownsValueToInsert(false) -{ } - -template -DiscreteHilbertValue::~DiscreteHilbertValue() -{ - if (ownsLocalHilbertValues) - delete localHilbertValues; - if (ownsValueToInsert) - delete valueToInsert; -} - -template -template -DiscreteHilbertValue::DiscreteHilbertValue(const TreeType* tree) : - localHilbertValues(NULL), - ownsLocalHilbertValues(false), - numValues(0), - valueToInsert(tree->Parent() ? - tree->Parent()->AuxiliaryInfo().HilbertValue().ValueToInsert() : - new arma::Col(tree->Dataset().n_rows)), - ownsValueToInsert(tree->Parent() ? false : true) -{ - // Calculate the Hilbert value for all points. - if (!tree->Parent()) // This is the root node. - ownsLocalHilbertValues = true; - else if (tree->Parent()->Child(0).IsLeaf()) - { - // This is a leaf node. - assert(tree->Parent()->NumChildren() > 0); - ownsLocalHilbertValues = true; - } - - if (ownsLocalHilbertValues) - { - localHilbertValues = new arma::Mat(tree->Dataset().n_rows, - tree->MaxLeafSize() + 1); - } -} - -template -template -DiscreteHilbertValue:: -DiscreteHilbertValue(const DiscreteHilbertValue& other, - TreeType* tree, - bool deepCopy) : - localHilbertValues(NULL), - ownsLocalHilbertValues(other.ownsLocalHilbertValues), - numValues(other.NumValues()), - valueToInsert(NULL), - ownsValueToInsert(other.ownsValueToInsert) -{ - if (deepCopy) - { - // Only leaf nodes own the localHilbertValues dataset. - // Intermediate nodes store the pointer to the corresponding dataset. - if (ownsLocalHilbertValues) - localHilbertValues = new arma::Mat( - *other.LocalHilbertValues()); - else - localHilbertValues = NULL; - - // Only the root owns ownsValueToInsert. Other nodes the pointer. - if (ownsValueToInsert) - valueToInsert = new arma::Col( - *other.ValueToInsert()); - else - { - assert(tree->Parent() != NULL); - // Copy the pointer from the parent node. - valueToInsert = const_cast*> - (tree->Parent()->AuxiliaryInfo().HilbertValue().ValueToInsert()); - } - - if (tree->NumChildren() == 0) - { - // We have to update pointers to the localHilbertValues dataset in - // intermediate nodes. - TreeType* node = tree; - - while (node->Parent() != NULL) - { - if (node->Parent()->NumChildren() > 1) - { - const std::vector parentChildren = - node->AuxiliaryInfo().Children(node->Parent()); - // If node is not the last child of its parent, we shouldn't copy - // the localHilbertValues pointer. - if (parentChildren[node->Parent()->NumChildren() - 2] == NULL) - break; - } - node->Parent()->AuxiliaryInfo().HilbertValue().LocalHilbertValues() = - localHilbertValues; - node = node->Parent(); - } - } - } - else - { - localHilbertValues = const_cast*> - (other.LocalHilbertValues()); - valueToInsert = const_cast*> - (other.ValueToInsert()); - } -} - -template -DiscreteHilbertValue:: -DiscreteHilbertValue(DiscreteHilbertValue&& other) : - localHilbertValues(other.localHilbertValues), - ownsLocalHilbertValues(other.ownsLocalHilbertValues), - numValues(other.numValues), - valueToInsert(other.valueToInsert), - ownsValueToInsert(other.ownsValueToInsert) -{ - other.localHilbertValues = NULL; - other.ownsLocalHilbertValues = false; - other.numValues = 0; - other.valueToInsert = NULL; - other.ownsValueToInsert = false; -} - -template -template -arma::Col::HilbertElemType> -DiscreteHilbertValue:: -CalculateValue(const VecType& pt, - typename std::enable_if_t::value>*) -{ - typedef typename VecType::elem_type VecElemType; - arma::Col res(pt.n_rows); - // Calculate the number of bits for the exponent. - const int numExpBits = std::ceil(std::log2( - std::numeric_limits::max_exponent - - std::numeric_limits::min_exponent + 1.0)); - - // Calculate the number of bits for the mantissa. - const int numMantBits = order - numExpBits - 1; - - for (size_t i = 0; i < pt.n_rows; i++) - { - int e; - VecElemType normalizedVal = std::frexp(pt(i), &e); - bool sgn = std::signbit(normalizedVal); - - if (pt(i) == 0) - e = std::numeric_limits::min_exponent; - - if (sgn) - normalizedVal = -normalizedVal; - - if (e < std::numeric_limits::min_exponent) - { - HilbertElemType tmp = (HilbertElemType) 1 << - (std::numeric_limits::min_exponent - e); - - e = std::numeric_limits::min_exponent; - normalizedVal /= tmp; - } - - // Extract the mantissa. - HilbertElemType tmp = (HilbertElemType) 1 << numMantBits; - res(i) = std::floor(normalizedVal * tmp); - - // Add the exponent. - assert(res(i) < ((HilbertElemType) 1 << numMantBits)); - res(i) |= ((HilbertElemType) - (e - std::numeric_limits::min_exponent)) << numMantBits; - - assert(res(i) < ((HilbertElemType) 1 << (order - 1)) - 1); - - // Negative values should be inverted. - if (sgn) - { - res(i) = ((HilbertElemType) 1 << (order - 1)) - 1 - res(i); - assert((res(i) >> (order - 1)) == 0); - } - else - { - res(i) |= (HilbertElemType) 1 << (order - 1); - assert((res(i) >> (order - 1)) == 1); - } - } - - HilbertElemType M = (HilbertElemType) 1 << (order - 1); - - // Since the Hilbert curve is continuous we should permutate and intend - // coordinate axes depending on the position of the point. - for (HilbertElemType Q = M; Q > 1; Q >>= 1) - { - HilbertElemType P = Q - 1; - - for (size_t i = 0; i < pt.n_rows; i++) - { - if (res(i) & Q) // Invert. - res(0) ^= P; - else // Permutate. - { - HilbertElemType t = (res(0) ^ res(i)) & P; - res(0) ^= t; - res(i) ^= t; - } - } - } - - // Gray encode. - for (size_t i = 1; i < pt.n_rows; i++) - res(i) ^= res(i - 1); - - HilbertElemType t = 0; - - // Some coordinate axes should be inverted. - for (HilbertElemType Q = M; Q > 1; Q >>= 1) - if (res(pt.n_rows - 1) & Q) - t ^= Q - 1; - - for (size_t i = 0; i < pt.n_rows; i++) - res(i) ^= t; - - // We should rearrange bits in order to compare two Hilbert values faster. - arma::Col rearrangedResult(pt.n_rows, arma::fill::zeros); - - for (size_t i = 0; i < order; i++) - for (size_t j = 0; j < pt.n_rows; j++) - { - size_t bit = (i * pt.n_rows + j) % order; - size_t row = (i * pt.n_rows + j) / order; - - rearrangedResult(row) |= (((res(j) >> (order - 1 - i)) & 1) << - (order - 1 - bit)); - } - - return rearrangedResult; -} - -template -int DiscreteHilbertValue:: -CompareValues(const arma::Col& value1, - const arma::Col& value2) -{ - for (size_t i = 0; i < value1.n_rows; i++) - { - if (value1(i) > value2(i)) - return 1; - else if (value1(i) < value2(i)) - return -1; - } - - return 0; -} - - - -template -template -int DiscreteHilbertValue:: -ComparePoints(const VecType1& pt1, - const VecType2& pt2, - typename std::enable_if_t::value>*, - typename std::enable_if_t::value>*) -{ - arma::Col val1 = CalculateValue(pt1); - arma::Col val2 = CalculateValue(pt2); - - return CompareValues(val1, val2); -} - -template -int DiscreteHilbertValue:: -CompareValues(const DiscreteHilbertValue& val1, - const DiscreteHilbertValue& val2) -{ - if (val1.NumValues() > 0 && val2.NumValues() == 0) - return 1; - else if (val1.NumValues() == 0 && val2.NumValues() > 0) - return -1; - else if (val1.NumValues() == 0 && val2.NumValues() == 0) - return 0; - - return CompareValues(val1.LocalHilbertValues()->col(val1.NumValues() - 1), - val2.LocalHilbertValues()->col(val2.NumValues() - 1)); -} - -template -int DiscreteHilbertValue:: -CompareWith(const DiscreteHilbertValue& val) const -{ - return CompareValues(*this, val); -} - -template -template -int DiscreteHilbertValue:: -CompareWith(const VecType& pt, - typename std::enable_if_t::value>*) const -{ - arma::Col val = CalculateValue(pt); - - if (numValues == 0) - return -1; - - return CompareValues(localHilbertValues->col(numValues - 1), val); -} - -template -template -int DiscreteHilbertValue:: -CompareWithCachedPoint(const VecType& , - typename std::enable_if_t::value>*) const -{ - if (numValues == 0) - return -1; - - return CompareValues(localHilbertValues->col(numValues - 1), *valueToInsert); -} - -template -template -size_t DiscreteHilbertValue:: -InsertPoint(TreeType *node, - const VecType& pt, - typename std::enable_if_t::value>*) -{ - size_t i = 0; - - // All points are inserted to the root node. - if (!node->Parent()) - *valueToInsert = CalculateValue(pt); - if (node->IsLeaf()) - { - // Find an appropriate place. - for (i = 0; i < numValues; i++) - if (CompareValues(localHilbertValues->col(i), *valueToInsert) > 0) - break; - - for (size_t j = numValues; j > i; j--) - localHilbertValues->col(j) = localHilbertValues->col(j-1); - - localHilbertValues->col(i) = *valueToInsert; - numValues++; - // Propagate changes of the largest Hilbert value downward. - TreeType* root = node->Parent(); - - while (root != NULL) - { - root->AuxiliaryInfo().HilbertValue().UpdateLargestValue(root); - - root = root->Parent(); - } - } - - return i; -} - -template -template -void DiscreteHilbertValue::InsertNode(TreeType* node) -{ - DiscreteHilbertValue &val = node->AuxiliaryInfo().HilbertValue(); - - if (CompareWith(node, val) < 0) - { - localHilbertValues = val.LocalHilbertValues(); - numValues = val.NumValues(); - } -} - -template -template -void DiscreteHilbertValue:: -DeletePoint(TreeType* /* node */, const size_t localIndex) -{ - // Delete the Hilbert value from the local dataset - for (size_t i = numValues - 1; i > localIndex; i--) - localHilbertValues->col(i - 1) = localHilbertValues->col(i); - - numValues--; -} - -template -template -void DiscreteHilbertValue:: -RemoveNode(TreeType* node, const size_t nodeIndex) -{ - if (node->NumChildren() <= 1) - { - localHilbertValues = NULL; - numValues = 0; - return; - } - if (nodeIndex + 1 == node->NumChildren()) - { - // Update the largest Hilbert value if the value exists - TreeType& child = node->Child(nodeIndex - 1); - if (child.AuxiliaryInfo.HilbertValue().NumValues() != 0) - { - numValues = child.AuxiliaryInfo.HilbertValue().NumValues(); - localHilbertValues = - child.AuxiliaryInfo.HilbertValue().LocalHilbertValues(); - } - else - { - localHilbertValues = NULL; - numValues = 0; - } - } -} - -template -DiscreteHilbertValue& DiscreteHilbertValue:: -operator=(const DiscreteHilbertValue& val) -{ - localHilbertValues = const_cast* > - (val.LocalHilbertValues()); - ownsLocalHilbertValues = false; - numValues = val.NumValues(); - - return *this; -} - -template -void DiscreteHilbertValue::NullifyData() -{ - ownsLocalHilbertValues = false; -} - -template -template -void DiscreteHilbertValue::UpdateLargestValue(TreeType* node) -{ - if (!node->IsLeaf()) - { - // Update the largest Hilbert value - localHilbertValues = node->Child(node->NumChildren() - - 1).AuxiliaryInfo().HilbertValue().LocalHilbertValues(); - numValues = node->Child(node->NumChildren() - - 1).AuxiliaryInfo().HilbertValue().NumValues(); - } -} - -template -template -void DiscreteHilbertValue::RedistributeHilbertValues( - TreeType* parent, - const size_t firstSibling, - const size_t lastSibling) -{ - // We need to update the local dataset if points were redistributed. - size_t numPoints = 0; - for (size_t i = firstSibling; i <= lastSibling; i++) - numPoints += parent->Child(i).NumPoints(); - - // Copy the local Hilbert values. - arma::Mat tmp(localHilbertValues->n_rows, numPoints); - - size_t iPoint = 0; - for (size_t i = firstSibling; i<= lastSibling; i++) - { - DiscreteHilbertValue &value = - parent->Child(i).AuxiliaryInfo().HilbertValue(); - - for (size_t j = 0; j < value.NumValues(); j++) - { - tmp.col(iPoint) = value.LocalHilbertValues()->col(j); - iPoint++; - } - } - assert(iPoint == numPoints); - - iPoint = 0; - - // Redistribute the Hilbert values. - for (size_t i = firstSibling; i <= lastSibling; i++) - { - DiscreteHilbertValue &value = - parent->Child(i).AuxiliaryInfo().HilbertValue(); - - for (size_t j = 0; j < parent->Child(i).NumPoints(); j++) - { - value.LocalHilbertValues()->col(j) = tmp.col(iPoint); - iPoint++; - } - value.NumValues() = parent->Child(i).NumPoints(); - } - - assert(iPoint == numPoints); -} - -template -template -void DiscreteHilbertValue::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(localHilbertValues); - ar & BOOST_SERIALIZATION_NVP(ownsLocalHilbertValues); - ar & BOOST_SERIALIZATION_NVP(numValues); - ar & BOOST_SERIALIZATION_NVP(valueToInsert); - ar & BOOST_SERIALIZATION_NVP(ownsValueToInsert); -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_DISCRETE_HILBERT_VALUE_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/dual_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/dual_tree_traverser.hpp deleted file mode 100644 index 8f4607c72..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/dual_tree_traverser.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file dual_tree_traverser.hpp - * @author Andrew Wells - * - * A nested class of Rectangle Tree for traversing rectangle type trees - * with a given set of rules which indicate the branches to prune and the - * order in which to recurse. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_DUAL_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_DUAL_TREE_TRAVERSER_HPP - -#include - -#include "rectangle_tree.hpp" - -namespace mlpack { -namespace tree { - -template class AuxiliaryInformationType> -template -class RectangleTree::DualTreeTraverser -{ - public: - /** - * Instantiate the dual-tree traverser with the given rule set. - */ - DualTreeTraverser(RuleType& rule); - - /** - * Traverse the two trees. This does not reset the number of prunes. - * - * @param queryNode The query node to be traversed. - * @param referenceNode The reference node to be traversed. - * @param score The score of the current node combination. - */ - void Traverse(RectangleTree& queryNode, RectangleTree& referenceNode); - - //! Get the number of prunes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of prunes. - size_t& NumPrunes() { return numPrunes; } - - //! Get the number of visited combinations. - size_t NumVisited() const { return numVisited; } - //! Modify the number of visited combinations. - size_t& NumVisited() { return numVisited; } - - //! Get the number of times a node combination was scored. - size_t NumScores() const { return numScores; } - //! Modify the number of times a node combination was scored. - size_t& NumScores() { return numScores; } - - //! Get the number of times a base case was calculated. - size_t NumBaseCases() const { return numBaseCases; } - //! Modify the number of times a base case was calculated. - size_t& NumBaseCases() { return numBaseCases; } - - private: - // We use this struct and this function to make the sorting and scoring easy - // and efficient: - struct NodeAndScore - { - RectangleTree* node; - double score; - typename RuleType::TraversalInfoType travInfo; - }; - - static bool nodeComparator(const NodeAndScore& obj1, - const NodeAndScore& obj2) - { - return obj1.score < obj2.score; - } - - //! Reference to the rules with which the trees will be traversed. - RuleType& rule; - - //! The number of prunes. - size_t numPrunes; - - //! The number of node combinations that have been visited during traversal. - size_t numVisited; - - //! The number of times a node combination was scored. - size_t numScores; - - //! The number of times a base case was calculated. - size_t numBaseCases; - - //! Traversal information, held in the class so that it isn't continually - //! being reallocated. - typename RuleType::TraversalInfoType traversalInfo; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "dual_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/dual_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/dual_tree_traverser_impl.hpp deleted file mode 100644 index be0e8ea3d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/dual_tree_traverser_impl.hpp +++ /dev/null @@ -1,175 +0,0 @@ -/** - * @file dual_tree_traverser_impl.hpp - * @author Andrew Wells - * - * A class for traversing rectangle type trees with a given set of rules - * which indicate the branches to prune and the order in which to recurse. - * This is a depth-first traverser. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPAC_CORE_TREE_RECTANGLE_TREE_DUAL_TREE_TRAVERSER_IMPL_HPP -#define MLPAC_CORE_TREE_RECTANGLE_TREE_DUAL_TREE_TRAVERSER_IMPL_HPP - -#include "dual_tree_traverser.hpp" - -#include -#include - -namespace mlpack { -namespace tree { - -template class AuxiliaryInformationType> -template -RectangleTree:: -DualTreeTraverser::DualTreeTraverser(RuleType& rule) : - rule(rule), - numPrunes(0), - numVisited(0), - numScores(0), - numBaseCases(0) -{ /* Nothing to do */ } - -template class AuxiliaryInformationType> -template -void RectangleTree:: -DualTreeTraverser::Traverse(RectangleTree& queryNode, - RectangleTree& referenceNode) -{ - // Increment the visit counter. - ++numVisited; - - // Store the current traversal info. - traversalInfo = rule.TraversalInfo(); - - // We now have four options. - // 1) Both nodes are leaf nodes. - // 2) Only the reference node is a leaf node. - // 3) Only the query node is a leaf node. - // 4) Niether node is a leaf node. - // We go through those options in that order. - - if (queryNode.IsLeaf() && referenceNode.IsLeaf()) - { - // Evaluate the base case. Do the query points on the outside so we can - // possibly prune the reference node for that particular point. - for (size_t query = 0; query < queryNode.Count(); ++query) - { - // Restore the traversal information. - rule.TraversalInfo() = traversalInfo; - const double childScore = rule.Score(queryNode.Point(query), - referenceNode); - - if (childScore == DBL_MAX) - continue; // We don't require a search in this reference node. - - for (size_t ref = 0; ref < referenceNode.Count(); ++ref) - rule.BaseCase(queryNode.Point(query), referenceNode.Point(ref)); - - numBaseCases += referenceNode.Count(); - } - } - else if (!queryNode.IsLeaf() && referenceNode.IsLeaf()) - { - // We only need to traverse down the query node. Order doesn't matter here. - for (size_t i = 0; i < queryNode.NumChildren(); ++i) - { - // Before recursing, we have to set the traversal information correctly. - rule.TraversalInfo() = traversalInfo; - ++numScores; - if (rule.Score(queryNode.Child(i), referenceNode) < DBL_MAX) - Traverse(queryNode.Child(i), referenceNode); - else - numPrunes++; - } - } - else if (queryNode.IsLeaf() && !referenceNode.IsLeaf()) - { - // We only need to traverse down the reference node. Order does matter - // here. - - // We sort the children of the reference node by their scores. - std::vector nodesAndScores(referenceNode.NumChildren()); - for (size_t i = 0; i < referenceNode.NumChildren(); i++) - { - rule.TraversalInfo() = traversalInfo; - nodesAndScores[i].node = &(referenceNode.Child(i)); - nodesAndScores[i].score = rule.Score(queryNode, - *(nodesAndScores[i].node)); - nodesAndScores[i].travInfo = rule.TraversalInfo(); - } - std::sort(nodesAndScores.begin(), nodesAndScores.end(), nodeComparator); - numScores += nodesAndScores.size(); - - for (size_t i = 0; i < nodesAndScores.size(); i++) - { - rule.TraversalInfo() = nodesAndScores[i].travInfo; - if (rule.Rescore(queryNode, *(nodesAndScores[i].node), - nodesAndScores[i].score) < DBL_MAX) - { - Traverse(queryNode, *(nodesAndScores[i].node)); - } - else - { - numPrunes += nodesAndScores.size() - i; - break; - } - } - } - else - { - // We need to traverse down both the reference and the query trees. - // We loop through all of the query nodes, and for each of them, we - // loop through the reference nodes to see where we need to descend. - for (size_t j = 0; j < queryNode.NumChildren(); j++) - { - // We sort the children of the reference node by their scores. - std::vector nodesAndScores(referenceNode.NumChildren()); - for (size_t i = 0; i < referenceNode.NumChildren(); i++) - { - rule.TraversalInfo() = traversalInfo; - nodesAndScores[i].node = &(referenceNode.Child(i)); - nodesAndScores[i].score = rule.Score(queryNode.Child(j), - *nodesAndScores[i].node); - nodesAndScores[i].travInfo = rule.TraversalInfo(); - } - std::sort(nodesAndScores.begin(), nodesAndScores.end(), nodeComparator); - numScores += nodesAndScores.size(); - - for (size_t i = 0; i < nodesAndScores.size(); i++) - { - rule.TraversalInfo() = nodesAndScores[i].travInfo; - if (rule.Rescore(queryNode.Child(j), *(nodesAndScores[i].node), - nodesAndScores[i].score) < DBL_MAX) - { - Traverse(queryNode.Child(j), *(nodesAndScores[i].node)); - } - else - { - numPrunes += nodesAndScores.size() - i; - break; - } - } - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_auxiliary_information.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_auxiliary_information.hpp deleted file mode 100644 index 99e4fb6e0..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_auxiliary_information.hpp +++ /dev/null @@ -1,150 +0,0 @@ -/** - * @file hilbert_r_tree_auxiliary_information.hpp - * @author Mikhail Lozhnikov - * - * Definition of the HilbertRTreeAuxiliaryInformation class, - * a class that provides some Hilbert r-tree specific information - * about the nodes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_AUXILIARY_INFO_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_AUXILIARY_INFO_HPP - -namespace mlpack { -namespace tree { - -template class HilbertValueType> -class HilbertRTreeAuxiliaryInformation -{ - public: - //! The element type held by the tree. - typedef typename TreeType::ElemType ElemType; - //! Default constructor - HilbertRTreeAuxiliaryInformation(); - - /** - * Construct this as an auxiliary information for the given node. - * - * @param node The node that stores this auxiliary information. - */ - HilbertRTreeAuxiliaryInformation(const TreeType* node); - - /** - * Create an auxiliary information object by copying from another object. - * - * @param other Another auxiliary information object from which the - * information will be copied. - * @param tree The node that holds the auxiliary information. - * @param deepCopy If false, the new object uses the same memory - * (not used here). - */ - HilbertRTreeAuxiliaryInformation( - const HilbertRTreeAuxiliaryInformation& other, - TreeType* tree = NULL, - bool deepCopy = true); - - /** - * Create an auxiliary information object by moving from the other node. - * - * @param other The object from which the information will be moved. - */ - HilbertRTreeAuxiliaryInformation(HilbertRTreeAuxiliaryInformation&& other); - - /** - * Copy the auxiliary information. - * - * @param other The object from which the information will be moved. - */ - HilbertRTreeAuxiliaryInformation& operator=( - const HilbertRTreeAuxiliaryInformation& other); - - /** - * The Hilbert R tree requires to insert points according to their Hilbert - * value. This method should take care of it. It returns false if it does - * nothing and true if it handles the insertion process. - * - * @param node The node in which the point is being inserted. - * @param point The number of the point being inserted. - */ - bool HandlePointInsertion(TreeType* node, const size_t point); - - /** - * The Hilbert R tree requires to insert nodes according to their Hilbert - * value. This method should take care of it. It returns false if it does - * nothing and true if it handles the insertion process. - * - * @param node The node in which the nodeToInsert is being inserted. - * @param nodeToInsert The node being inserted. - * @param insertionLevel The level of the tree at which the nodeToInsert - * should be inserted. - */ - bool HandleNodeInsertion(TreeType* node, - TreeType* nodeToInsert, - bool insertionLevel); - - /** - * The Hilbert R tree requires all points to be arranged according to their - * Hilbert value. This method should take care of saving this property after - * the deletion process. It returns false if it does nothing and true if it - * handles the deletion process. - * - * @param node The node from which the point is being deleted. - * @param localIndex The index of the point being deleted. - */ - bool HandlePointDeletion(TreeType* node, const size_t localIndex); - - /** - * The Hilbert R tree requires all nodes to be arranged according to their - * Hilbert value. This method should take care of saving this property after - * the deletion process. It returns false if it does nothing and true if it - * handles the deletion process. - * - * @param node The node from which the node is being deleted. - * @param nodeIndex The index of the node being deleted. - */ - bool HandleNodeRemoval(TreeType* node, const size_t nodeIndex); - - /** - * Update the auxiliary information in the node. The method returns true if - * the update should be propagated downward. - * - * @param node The node in which the auxiliary information being update. - */ - bool UpdateAuxiliaryInfo(TreeType* node); - - //! Clear memory. - void NullifyData(); - - //! Return the children vector of the tree. - static const std::vector Children(const TreeType* tree) - { return tree->children; } - - private: - //! The largest Hilbert value of a point enclosed by the node. - HilbertValueType hilbertValue; - - public: - //! Return the largest Hilbert value of a point covered by the node. - const HilbertValueType& HilbertValue() const - { return hilbertValue; } - //! Modify the largest Hilbert value of a point covered by the node. - HilbertValueType& HilbertValue() { return hilbertValue; } - - /** - * Serialize the information. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); -}; - -} // namespace tree -} // namespace mlpack - -#include "hilbert_r_tree_auxiliary_information_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_AUXILIARY_INFO_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_auxiliary_information_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_auxiliary_information_impl.hpp deleted file mode 100644 index d7eea0543..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_auxiliary_information_impl.hpp +++ /dev/null @@ -1,192 +0,0 @@ -/** - * @file hilbert_r_tree_auxiliary_information.hpp - * @author Mikhail Lozhnikov - * - * Implementation of the HilbertRTreeAuxiliaryInformation class, a class that - * provides some Hilbert r-tree specific information about the nodes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_AUXILIARY_INFO_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_AUXILIARY_INFO_IMPL_HPP - -#include "hilbert_r_tree_auxiliary_information.hpp" - -namespace mlpack { -namespace tree { - -template class HilbertValueType> -HilbertRTreeAuxiliaryInformation:: -HilbertRTreeAuxiliaryInformation() -{ } - -template class HilbertValueType> -HilbertRTreeAuxiliaryInformation:: -HilbertRTreeAuxiliaryInformation(const TreeType* node) : - hilbertValue(node) -{ } - -template class HilbertValueType> -HilbertRTreeAuxiliaryInformation:: -HilbertRTreeAuxiliaryInformation( - const HilbertRTreeAuxiliaryInformation& other, - TreeType* tree, - bool deepCopy) : - hilbertValue(other.HilbertValue(), tree, deepCopy) -{ } - -template class HilbertValueType> -HilbertRTreeAuxiliaryInformation:: -HilbertRTreeAuxiliaryInformation(HilbertRTreeAuxiliaryInformation&& other) : - hilbertValue(std::move(other.hilbertValue)) -{ } - -template class HilbertValueType> -HilbertRTreeAuxiliaryInformation& -HilbertRTreeAuxiliaryInformation::operator=( - const HilbertRTreeAuxiliaryInformation& other) -{ - hilbertValue = other.hilbertValue; - return *this; -} - -template class HilbertValueType> -bool HilbertRTreeAuxiliaryInformation:: -HandlePointInsertion(TreeType* node, const size_t point) -{ - if (node->IsLeaf()) - { - // Get the position at which the point should be inserted, and then update - // the largest Hilbert value of the node. - size_t pos = hilbertValue.InsertPoint(node, node->Dataset().col(point)); - - // Move points. - for (size_t i = node->NumPoints(); i > pos; i--) - node->Point(i) = node->Point(i - 1); - - // Insert the point. - node->Point(pos) = point; - node->Count()++; - } - else - { - // Calculate the Hilbert value. - hilbertValue.InsertPoint(node, node->Dataset().col(point)); - } - - return true; -} - -template class HilbertValueType> -bool HilbertRTreeAuxiliaryInformation:: -HandleNodeInsertion(TreeType* node, TreeType* nodeToInsert, bool insertionLevel) -{ - if (insertionLevel) - { - size_t pos; - - // Find the best position for the node being inserted. - // The node should be inserted according to its Hilbert value. - for (pos = 0; pos < node->NumChildren(); pos++) - if (HilbertValueType::CompareValues( - node->Child(pos).AuxiliaryInfo().HilbertValue(), - nodeToInsert->AuxiliaryInfo().HilbertValue()) < 0) - break; - - // Move nodes. - for (size_t i = node->NumChildren(); i > pos; i--) - node->children[i] = node->children[i - 1]; - - // Insert the node. - node->children[pos] = nodeToInsert; - nodeToInsert->Parent() = node; - - // Update the largest Hilbert value. - hilbertValue.InsertNode(nodeToInsert); - } - else - hilbertValue.InsertNode(nodeToInsert); // Update the largest Hilbert value. - - return true; -} - -template class HilbertValueType> -bool HilbertRTreeAuxiliaryInformation:: -HandlePointDeletion(TreeType* node, const size_t localIndex) -{ - // Update the largest Hilbert value. - hilbertValue.DeletePoint(node, localIndex); - - for (size_t i = localIndex + 1; localIndex < node->NumPoints(); i++) - node->Point(i - 1) = node->Point(i); - - node->NumPoints()--; - return true; -} - -template class HilbertValueType> -bool HilbertRTreeAuxiliaryInformation:: -HandleNodeRemoval(TreeType* node, const size_t nodeIndex) -{ - // Update the largest Hilbert value. - hilbertValue.RemoveNode(node, nodeIndex); - - for (size_t i = nodeIndex + 1; nodeIndex < node->NumChildren(); i++) - node->children[i - 1] = node->children[i]; - - node->NumChildren()--; - return true; -} - -template class HilbertValueType> -bool HilbertRTreeAuxiliaryInformation:: -UpdateAuxiliaryInfo(TreeType* node) -{ - if (node->IsLeaf()) // Should already be updated - return true; - - TreeType& child = node->Child(node->NumChildren() - 1); - if (hilbertValue.CompareWith(child.AuxiliaryInfo().HilbertValue()) < 0) - { - hilbertValue = child.AuxiliaryInfo().HilbertValue(); - return true; - } - return false; -} - -template class HilbertValueType> -void HilbertRTreeAuxiliaryInformation:: -NullifyData() -{ - hilbertValue.NullifyData(); -} - -template class HilbertValueType> -template -void HilbertRTreeAuxiliaryInformation::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(hilbertValue); -} - - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_AUXILIARY_INFO_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_descent_heuristic.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_descent_heuristic.hpp deleted file mode 100644 index 74086715f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_descent_heuristic.hpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file hilbert_r_tree_descent_heuristic.hpp - * @author Mikhail Lozhnikov - * - * Definition of HilbertRTreeDescentHeuristic, a class that chooses the best - * child of a node in an R tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_DESCENT_HEURISTIC_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_DESCENT_HEURISTIC_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * This class chooses the best child of a node in a Hilbert R tree when - * inserting a new point. This is done, in this class, by using the Hilbert - * value of the point to be inserted. - */ -class HilbertRTreeDescentHeuristic -{ - public: - /** - * Evaluate the node using a heuristic. Returns the number of the node with - * minimum largest Hilbert value that is greater than the Hilbert value of the - * point being inserted. - * - * @param node The node that is being evaluated. - * @param point The number of the point that is being inserted. - */ - template - static size_t ChooseDescentNode(const TreeType* node, const size_t point); - - /** - * Evaluate the node using a heuristic. Returns the number of the node with - * minimum largest Hilbert value that is greater than the largest Hilbert - * value of the point being inserted. - * - * @param node The node that is being evaluated. - * @param insertedNode The node that is being inserted. - */ - template - static size_t ChooseDescentNode(const TreeType* node, - const TreeType* insertedNode); -}; - -} // namespace tree -} // namespace mlpack - -#include "hilbert_r_tree_descent_heuristic_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_DESCENT_HEURISTIC_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_descent_heuristic_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_descent_heuristic_impl.hpp deleted file mode 100644 index 64a337552..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_descent_heuristic_impl.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @file hilbert_r_tree_descent_heuristic_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of HilbertRTreeDescentHeuristic, a class that chooses the best - * child of a node in an R tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_DESCENT_HEURISTIC_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_DESCENT_HEURISTIC_IMPL_HPP - -#include "hilbert_r_tree_descent_heuristic.hpp" - -namespace mlpack { -namespace tree { - -template -size_t HilbertRTreeDescentHeuristic::ChooseDescentNode( - const TreeType* node, - const size_t point) -{ - size_t bestIndex = 0; - - for (bestIndex = 0; bestIndex < node->NumChildren() - 1; bestIndex++) - if (node->Child(bestIndex).AuxiliaryInfo().HilbertValue(). - CompareWithCachedPoint(node->Dataset().col(point)) > 0) - break; - - return bestIndex; -} - -template -size_t HilbertRTreeDescentHeuristic::ChooseDescentNode( - const TreeType* node, - const TreeType* /* insertedNode */) -{ - size_t bestIndex = 0; - - for (bestIndex = 0; bestIndex < node->NumChildren() - 1; bestIndex++) - if (node->Child(bestIndex).AuxiliaryInfo().HilbertValue(). - CompareWith(node, node->AuxiliaryInfo().HilbertValue()) > 0) - break; - - return bestIndex; -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_HR_TREE_DESCENT_HEURISTIC_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_split.hpp deleted file mode 100644 index dca557b43..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_split.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @file hilbert_r_tree_split.hpp - * @author Mikhail Lozhnikov - * - * Definition of the HilbertRTreeSplit class, a class that splits the nodes of an R - * tree, starting at a leaf node and moving upwards if necessary. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_HILBERT_R_TREE_SPLIT_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_HILBERT_R_TREE_SPLIT_HPP - -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * The splitting procedure for the Hilbert R tree. The template parameter - * splitOrder is the order of the splitting policy. The Hilbert R tree splits a - * node on overflow, turning splitOrder nodes into (splitOrder + 1) nodes. - * - * @tparam splitOrder Number of nodes to split. - */ -template -class HilbertRTreeSplit -{ - public: - /** - * Split a leaf node using the "default" algorithm. If necessary, this split - * will propagate upwards through the tree. - * - * @param node The node that is being split. - * @param relevels Not used. - */ - template - static void SplitLeafNode(TreeType* tree, std::vector& relevels); - - /** - * Split a non-leaf node using the "default" algorithm. If this is a root - * node, the tree increases in depth. - * - * @param node The node that is being split. - * @param relevels Not used. - */ - template - static bool SplitNonLeafNode(TreeType* tree, std::vector& relevels); - - private: - /** - * Try to find splitOrder cooperating siblings in order to redistribute their - * children evenly. Returns true on success. - * - * @param parent The parent of of the overflowing node. - * @param iTree The number of the overflowing node. - * @param firstSibling The first cooperating sibling. - * @param lastSibling The last cooperating sibling. - */ - template - static bool FindCooperatingSiblings(TreeType* parent, - const size_t iTree, - size_t& firstSibling, - size_t& lastSibling); - - /** - * Redistribute the children of the cooperating siblings evenly among them. - * - * @param parent The parent of of the overflowing node. - * @param firstSibling The first cooperating sibling. - * @param lastSibling The last cooperating sibling. - */ - template - static void RedistributeNodesEvenly(const TreeType* parent, - const size_t firstSibling, - const size_t lastSibling); - - /** - * Redistribute the points of the cooperating siblings evenly among them. - * - * @param parent The parent of of the overflowing node. - * @param firstSibling The first cooperating sibling. - * @param lastSibling The last cooperating sibling. - */ - template - static void RedistributePointsEvenly(TreeType* parent, - const size_t firstSibling, - const size_t lastSibling); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "hilbert_r_tree_split_impl.hpp" - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_split_impl.hpp deleted file mode 100644 index 600665c7b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/hilbert_r_tree_split_impl.hpp +++ /dev/null @@ -1,353 +0,0 @@ -/** - * @file hilbert_r_tree_split_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of class (HilbertRTreeSplit) to split a RectangleTree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_HILBERT_R_TREE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_HILBERT_R_TREE_SPLIT_IMPL_HPP - -#include "hilbert_r_tree_split.hpp" -#include "rectangle_tree.hpp" -#include - -namespace mlpack { -namespace tree { - -template -template -void HilbertRTreeSplit::SplitLeafNode(TreeType* tree, - std::vector& relevels) -{ - if (tree->Count() <= tree->MaxLeafSize()) - return; - // If we are splitting the root node, we need will do things differently so - // that the constructor and other methods don't confuse the end user by giving - // an address of another node. - if (tree->Parent() == NULL) - { - // We actually want to copy this way. Pointers and everything. - TreeType* copy = new TreeType(*tree, false); - // Only the root node owns this variable. - copy->AuxiliaryInfo().HilbertValue().OwnsValueToInsert() = false; - // Only leaf nodes own this variable. - tree->AuxiliaryInfo().HilbertValue().OwnsLocalHilbertValues() = false; - copy->Parent() = tree; - tree->Count() = 0; - tree->NullifyData(); - // Because this was a leaf node, numChildren must be 0. - tree->children[(tree->NumChildren())++] = copy; - SplitLeafNode(copy, relevels); - return; - } - - TreeType* parent = tree->Parent(); - size_t iTree = 0; - for (iTree = 0; parent->children[iTree] != tree; iTree++) { } - - // Try to find splitOrder cooperating siblings in order to redistribute points - // among them and avoid split. - size_t firstSibling, lastSibling; - if (FindCooperatingSiblings(parent, iTree, firstSibling, lastSibling)) - { - RedistributePointsEvenly(parent, firstSibling, lastSibling); - return; - } - - // We can not find splitOrder cooperating siblings since they are all full. - // We introduce new one instead. - size_t iNewSibling = (iTree + splitOrder < parent->NumChildren() ? - iTree + splitOrder : parent->NumChildren()); - - for (size_t i = parent->NumChildren(); i > iNewSibling ; i--) - parent->children[i] = parent->children[i - 1]; - - parent->NumChildren()++; - - parent->children[iNewSibling] = new TreeType(parent); - - lastSibling = (iTree + splitOrder < parent->NumChildren() ? - iTree + splitOrder : parent->NumChildren() - 1); - firstSibling = (lastSibling > splitOrder ? lastSibling - splitOrder : 0); - - assert(lastSibling - firstSibling <= splitOrder); - assert(firstSibling >= 0); - assert(lastSibling < parent->NumChildren()); - - // Redistribute the points among (splitOrder + 1) cooperating siblings evenly. - RedistributePointsEvenly(parent, firstSibling, lastSibling); - - if (parent->NumChildren() == parent->MaxNumChildren() + 1) - SplitNonLeafNode(parent, relevels); -} - -template -template -bool HilbertRTreeSplit:: -SplitNonLeafNode(TreeType* tree, std::vector& relevels) -{ - // If we are splitting the root node, we need will do things differently so - // that the constructor and other methods don't confuse the end user by giving - // an address of another node. - if (tree->Parent() == NULL) - { - // We actually want to copy this way. Pointers and everything. - TreeType* copy = new TreeType(*tree, false); - // Only the root node owns this variable. - copy->AuxiliaryInfo().HilbertValue().OwnsValueToInsert() = false; - copy->Parent() = tree; - tree->NumChildren() = 0; - tree->NullifyData(); - tree->children[(tree->NumChildren())++] = copy; - - SplitNonLeafNode(copy, relevels); - return true; - } - - TreeType* parent = tree->Parent(); - - size_t iTree = 0; - for (iTree = 0; parent->children[iTree] != tree; iTree++) { } - - // Try to find splitOrder cooperating siblings in order to redistribute - // children among them and avoid split. - size_t firstSibling, lastSibling; - if (FindCooperatingSiblings(parent, iTree, firstSibling, lastSibling)) - { - RedistributeNodesEvenly(parent, firstSibling, lastSibling); - return false; - } - - // We can not find splitOrder cooperating siblings since they are all full. - // We introduce new one instead. - size_t iNewSibling = (iTree + splitOrder < parent->NumChildren() ? - iTree + splitOrder : parent->NumChildren()); - - for (size_t i = parent->NumChildren(); i > iNewSibling ; i--) - parent->children[i] = parent->children[i - 1]; - - parent->NumChildren()++; - - parent->children[iNewSibling] = new TreeType(parent); - - lastSibling = (iTree + splitOrder < parent->NumChildren() ? - iTree + splitOrder : parent->NumChildren() - 1); - firstSibling = (lastSibling > splitOrder ? - lastSibling - splitOrder : 0); - - assert(lastSibling - firstSibling <= splitOrder); - assert(firstSibling >= 0); - assert(lastSibling < parent->NumChildren()); - - // Redistribute children among (splitOrder + 1) cooperating siblings evenly. - RedistributeNodesEvenly(parent, firstSibling, lastSibling); - - if (parent->NumChildren() == parent->MaxNumChildren() + 1) - SplitNonLeafNode(parent, relevels); - return false; -} - -template -template -bool HilbertRTreeSplit::FindCooperatingSiblings( - TreeType* parent, - const size_t iTree, - size_t& firstSibling, - size_t& lastSibling) -{ - size_t start = (iTree > splitOrder - 1 ? iTree - splitOrder + 1 : 0); - size_t end = (iTree + splitOrder <= parent->NumChildren() ? - iTree + splitOrder : parent->NumChildren()); - - size_t iUnderfullSibling; - - // Try to find empty space among cooperating siblings. - if (parent->Child(iTree).NumChildren() != 0) - { - for (iUnderfullSibling = start; iUnderfullSibling < end; - iUnderfullSibling++) - if (parent->Child(iUnderfullSibling).NumChildren() < - parent->Child(iUnderfullSibling).MaxNumChildren() - 1) - break; - } - else - { - for (iUnderfullSibling = start; iUnderfullSibling < end; - iUnderfullSibling++) - if (parent->Child(iUnderfullSibling).NumPoints() < - parent->Child(iUnderfullSibling).MaxLeafSize() - 1) - break; - } - - if (iUnderfullSibling == end) // All nodes are full. - return false; - - if (iUnderfullSibling > iTree) - { - lastSibling = (iTree + splitOrder - 1 < parent->NumChildren() ? - iTree + splitOrder - 1 : parent->NumChildren() - 1); - firstSibling = (lastSibling > splitOrder - 1 ? - lastSibling - splitOrder + 1 : 0); - } - else - { - lastSibling = (iUnderfullSibling + splitOrder - 1 < parent->NumChildren() ? - iUnderfullSibling + splitOrder - 1 : parent->NumChildren() - 1); - firstSibling = (lastSibling > splitOrder - 1 ? - lastSibling - splitOrder + 1 : 0); - } - - assert(lastSibling - firstSibling <= splitOrder - 1); - assert(firstSibling >= 0); - assert(lastSibling < parent->NumChildren()); - - return true; -} - -template -template -void HilbertRTreeSplit:: -RedistributeNodesEvenly(const TreeType *parent, - size_t firstSibling, size_t lastSibling) -{ - size_t numChildren = 0; - size_t numChildrenPerNode, numRestChildren; - - for (size_t i = firstSibling; i <= lastSibling; i++) - numChildren += parent->Child(i).NumChildren(); - - numChildrenPerNode = numChildren / (lastSibling - firstSibling + 1); - numRestChildren = numChildren % (lastSibling - firstSibling + 1); - - std::vector children(numChildren); - - // Copy children's children in order to redistribute them. - size_t iChild = 0; - for (size_t i = firstSibling; i <= lastSibling; i++) - { - for (size_t j = 0; j < parent->Child(i).NumChildren(); j++) - { - children[iChild] = parent->Child(i).children[j]; - iChild++; - } - } - - iChild = 0; - for (size_t i = firstSibling; i <= lastSibling; i++) - { - // Since we redistribute children of a sibling we should recalculate the - // bound. - parent->Child(i).Bound().Clear(); - parent->Child(i).numDescendants = 0; - - for (size_t j = 0; j < numChildrenPerNode; j++) - { - parent->Child(i).Bound() |= children[iChild]->Bound(); - parent->Child(i).numDescendants += children[iChild]->numDescendants; - parent->Child(i).children[j] = children[iChild]; - children[iChild]->Parent() = parent->children[i]; - iChild++; - } - if (numRestChildren > 0) - { - parent->Child(i).Bound() |= children[iChild]->Bound(); - parent->Child(i).numDescendants += children[iChild]->numDescendants; - parent->Child(i).children[numChildrenPerNode] = children[iChild]; - children[iChild]->Parent() = parent->children[i]; - parent->Child(i).NumChildren() = numChildrenPerNode + 1; - numRestChildren--; - iChild++; - } - else - { - parent->Child(i).NumChildren() = numChildrenPerNode; - } - assert(parent->Child(i).NumChildren() <= - parent->Child(i).MaxNumChildren()); - - // Fix the largest Hilbert value of the sibling. - parent->Child(i).AuxiliaryInfo().HilbertValue().UpdateLargestValue( - parent->children[i]); - } -} - -template -template -void HilbertRTreeSplit:: -RedistributePointsEvenly(TreeType* parent, - const size_t firstSibling, - const size_t lastSibling) -{ - size_t numPoints = 0; - size_t numPointsPerNode, numRestPoints; - - for (size_t i = firstSibling; i <= lastSibling; i++) - numPoints += parent->Child(i).NumPoints(); - - numPointsPerNode = numPoints / (lastSibling - firstSibling + 1); - numRestPoints = numPoints % (lastSibling - firstSibling + 1); - - std::vector points(numPoints); - - // Copy children's points in order to redistribute them. - size_t iPoint = 0; - for (size_t i = firstSibling; i <= lastSibling; i++) - { - for (size_t j = 0; j < parent->Child(i).NumPoints(); j++) - points[iPoint++] = parent->Child(i).Point(j); - } - - iPoint = 0; - for (size_t i = firstSibling; i <= lastSibling; i++) - { - // Since we redistribute points of a sibling we should recalculate the - // bound. - parent->Child(i).Bound().Clear(); - - size_t j; - for (j = 0; j < numPointsPerNode; j++) - { - parent->Child(i).Bound() |= parent->Dataset().col(points[iPoint]); - parent->Child(i).Point(j) = points[iPoint]; - iPoint++; - } - if (numRestPoints > 0) - { - parent->Child(i).Bound() |= parent->Dataset().col(points[iPoint]); - parent->Child(i).Point(j) = points[iPoint]; - parent->Child(i).Count() = numPointsPerNode + 1; - numRestPoints--; - iPoint++; - } - else - { - parent->Child(i).Count() = numPointsPerNode; - } - parent->Child(i).numDescendants = parent->Child(i).Count(); - - assert(parent->Child(i).NumPoints() <= - parent->Child(i).MaxLeafSize()); - } - - // Fix the largest Hilbert values of the siblings. - parent->AuxiliaryInfo().HilbertValue().RedistributeHilbertValues(parent, - firstSibling, lastSibling); - - TreeType* root = parent; - - while (root != NULL) - { - root->AuxiliaryInfo().HilbertValue().UpdateLargestValue(root); - root = root->Parent(); - } -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_HILBERT_R_TREE_SPLIT_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_coverage_sweep.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_coverage_sweep.hpp deleted file mode 100644 index af4385693..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_coverage_sweep.hpp +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @file minimal_coverage_sweep.hpp - * @author Mikhail Lozhnikov - * - * Definition of the MinimalCoverageSweep class, a class that finds a partition - * of a node along an axis. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_COVERAGE_SWEEP_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_COVERAGE_SWEEP_HPP - -namespace mlpack { -namespace tree { - -/** - * The MinimalCoverageSweep class finds a partition along which we - * can split a node according to the coverage of two resulting nodes. The class - * finds a partition along a given axis. Moreover, the class evaluates the cost - * of each split. The cost is proportional to the total coverage of resulting - * nodes. If the resulting nodes are overflowed the maximum cost is returned. - * - * @tparam SplitPolicy The class that provides rules for inserting children of - * a node that is being split into two new subtrees. - */ -template -class MinimalCoverageSweep -{ - public: - //! A struct that provides the type of the sweep cost. - template - struct SweepCost - { - typedef typename TreeType::ElemType type; - }; - - /** - * Find a suitable partition of a non-leaf node along the provided axis. - * The method returns the cost of the split. - * - * @param axis The axis along which we are finding a partition. - * @param node The node that is being split. - * @param axisCut The coordinate at which the node may be split. - */ - template - static typename TreeType::ElemType SweepNonLeafNode( - const size_t axis, - const TreeType* node, - typename TreeType::ElemType& axisCut); - - /** - * Find a suitable partition of a leaf node along the provided axis. - * The method returns the cost of the split. - * - * @param axis The axis along which we are finding a partition. - * @param node The node that is being split. - * @param axisCut The coordinate at which the node may be split. - */ - template - static typename TreeType::ElemType SweepLeafNode( - const size_t axis, - const TreeType* node, - typename TreeType::ElemType& axisCut); - - /** - * Check if an intermediate node can be split along the axis at the provided - * coordinate. - * - * @param node The node that is being split. - * @param cutAxis The axis that we want to check. - * @param cut The coordinate that we want to check. - */ - template - static bool CheckNonLeafSweep(const TreeType* node, - const size_t cutAxis, - const ElemType cut); - - /** - * Check if a leaf node can be split along the axis at the provided - * coordinate. - * - * @param node The node that is being split. - * @param cutAxis The axis that we want to check. - * @param cut The coordinate that we want to check. - */ - template - static bool CheckLeafSweep(const TreeType* node, - const size_t cutAxis, - const ElemType cut); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation -#include "minimal_coverage_sweep_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_COVERAGE_SWEEP_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_coverage_sweep_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_coverage_sweep_impl.hpp deleted file mode 100644 index a9efbcecd..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_coverage_sweep_impl.hpp +++ /dev/null @@ -1,199 +0,0 @@ -/** - * @file minimal_coverage_sweep_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of the MinimalCoverageSweep class, a class that finds a - * partition of a node along an axis. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_COVERAGE_SWEEP_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_COVERAGE_SWEEP_IMPL_HPP - -#include "minimal_coverage_sweep.hpp" - -namespace mlpack { -namespace tree { - -template -template -typename TreeType::ElemType MinimalCoverageSweep:: -SweepNonLeafNode(const size_t axis, - const TreeType* node, - typename TreeType::ElemType& axisCut) -{ - typedef typename TreeType::ElemType ElemType; - typedef bound::HRectBound BoundType; - - std::vector> sorted(node->NumChildren()); - - for (size_t i = 0; i < node->NumChildren(); i++) - { - sorted[i].first = SplitPolicy::Bound(node->Child(i))[axis].Hi(); - sorted[i].second = i; - } - // Sort high bounds of children. - std::sort(sorted.begin(), sorted.end(), - [] (const std::pair& s1, - const std::pair& s2) - { - return s1.first < s2.first; - }); - - size_t splitPointer = node->NumChildren() / 2; - - axisCut = sorted[splitPointer - 1].first; - - // Check if the midpoint split is suitable. - if (!CheckNonLeafSweep(node, axis, axisCut)) - { - // Find any suitable partition if the default partition is not acceptable. - for (splitPointer = 1; splitPointer < sorted.size(); splitPointer++) - { - axisCut = sorted[splitPointer - 1].first; - if (CheckNonLeafSweep(node, axis, axisCut)) - break; - } - - if (splitPointer == node->NumChildren()) - return std::numeric_limits::max(); - } - - BoundType bound1(node->Bound().Dim()); - BoundType bound2(node->Bound().Dim()); - - // Find bounds of two resulting nodes. - for (size_t i = 0; i < splitPointer; i++) - bound1 |= node->Child(sorted[i].second).Bound(); - - for (size_t i = splitPointer; i < node->NumChildren(); i++) - bound2 |= node->Child(sorted[i].second).Bound(); - - - // Evaluate the cost of the split i.e. calculate the total coverage - // of two resulting nodes. - - ElemType area1 = bound1.Volume(); - ElemType area2 = bound2.Volume(); - - return area1 + area2; -} - -template -template -typename TreeType::ElemType MinimalCoverageSweep:: -SweepLeafNode(const size_t axis, - const TreeType* node, - typename TreeType::ElemType& axisCut) -{ - typedef typename TreeType::ElemType ElemType; - typedef bound::HRectBound BoundType; - - std::vector> sorted(node->Count()); - - sorted.resize(node->Count()); - - for (size_t i = 0; i < node->NumPoints(); i++) - { - sorted[i].first = node->Dataset().col(node->Point(i))[axis]; - sorted[i].second = i; - } - - // Sort high bounds of children. - std::sort(sorted.begin(), sorted.end(), - [] (const std::pair& s1, - const std::pair& s2) - { - return s1.first < s2.first; - }); - - size_t splitPointer = node->Count() / 2; - - axisCut = sorted[splitPointer - 1].first; - - // Check if the partition is suitable. - if (!CheckLeafSweep(node, axis, axisCut)) - return std::numeric_limits::max(); - - BoundType bound1(node->Bound().Dim()); - BoundType bound2(node->Bound().Dim()); - - // Find bounds of two resulting nodes. - for (size_t i = 0; i < splitPointer; i++) - bound1 |= node->Dataset().col(node->Point(sorted[i].second)); - - for (size_t i = splitPointer; i < node->NumChildren(); i++) - bound2 |= node->Dataset().col(node->Point(sorted[i].second)); - - // Evaluate the cost of the split i.e. calculate the total coverage - // of two resulting nodes. - - return bound1.Volume() + bound2.Volume(); -} - -template -template -bool MinimalCoverageSweep:: -CheckNonLeafSweep(const TreeType* node, - const size_t cutAxis, - const ElemType cut) -{ - size_t numTreeOneChildren = 0; - size_t numTreeTwoChildren = 0; - - // Calculate the number of children in the resulting nodes. - for (size_t i = 0; i < node->NumChildren(); i++) - { - const TreeType& child = node->Child(i); - int policy = SplitPolicy::GetSplitPolicy(child, cutAxis, cut); - if (policy == SplitPolicy::AssignToFirstTree) - numTreeOneChildren++; - else if (policy == SplitPolicy::AssignToSecondTree) - numTreeTwoChildren++; - else - { - // The split is required. - numTreeOneChildren++; - numTreeTwoChildren++; - } - } - - if (numTreeOneChildren <= node->MaxNumChildren() && numTreeOneChildren > 0 && - numTreeTwoChildren <= node->MaxNumChildren() && numTreeTwoChildren > 0) - return true; - return false; -} - -template -template -bool MinimalCoverageSweep:: -CheckLeafSweep(const TreeType* node, - const size_t cutAxis, - const ElemType cut) -{ - size_t numTreeOnePoints = 0; - size_t numTreeTwoPoints = 0; - - // Calculate the number of points in the resulting nodes. - for (size_t i = 0; i < node->NumPoints(); i++) - { - if (node->Dataset().col(node->Point(i))[cutAxis] <= cut) - numTreeOnePoints++; - else - numTreeTwoPoints++; - } - - if (numTreeOnePoints <= node->MaxLeafSize() && numTreeOnePoints > 0 && - numTreeTwoPoints <= node->MaxLeafSize() && numTreeTwoPoints > 0) - return true; - return false; -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_COVERAGE_SWEEP_IMPL_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_splits_number_sweep.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_splits_number_sweep.hpp deleted file mode 100644 index c8b99030d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_splits_number_sweep.hpp +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @file minimal_splits_number_sweep.hpp - * @author Mikhail Lozhnikov - * - * Definition of the MinimalSplitsNumberSweep class, a class that finds a - * partition of a node along an axis. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_SPLITS_NUMBER_SWEEP_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_SPLITS_NUMBER_SWEEP_HPP - -namespace mlpack { -namespace tree { - -/** - * The MinimalSplitsNumberSweep class finds a partition along which we - * can split a node according to the number of required splits of the node. - * The class finds a partition along a given axis. Moreover, the class evaluates - * the cost of each split. The cost is proportional to the number of required - * splits and the difference of sizes of resulting nodes. If the resulting nodes - * are overflowed the maximum cost is returned. - * - * @tparam SplitPolicy The class that provides rules for inserting children of - * a node that is being split into two new subtrees. - */ -template -class MinimalSplitsNumberSweep -{ - public: - //! A struct that provides the type of the sweep cost. - template - struct SweepCost - { - typedef size_t type; - }; - - /** - * Find a suitable partition of a non-leaf node along the provided axis. - * The method returns the cost of the split. - * - * @param axis The axis along which we are finding a partition. - * @param node The node that is being split. - * @param axisCut The coordinate at which the node may be split. - */ - template - static size_t SweepNonLeafNode( - const size_t axis, - const TreeType* node, - typename TreeType::ElemType& axisCut); - - /** - * Find a suitable partition of a leaf node along the provided axis. - * The method returns the cost of the split. - * - * @param axis The axis along which we are finding a partition. - * @param node The node that is being split. - * @param axisCut The coordinate at which the node may be split. - */ - template - static size_t SweepLeafNode( - const size_t axis, - const TreeType* node, - typename TreeType::ElemType& axisCut); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation -#include "minimal_splits_number_sweep_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_SPLITS_NUMBER_SWEEP_HPP - - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_splits_number_sweep_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_splits_number_sweep_impl.hpp deleted file mode 100644 index 9d3e8c28f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/minimal_splits_number_sweep_impl.hpp +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @file minimal_splits_number_sweep_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of the MinimalSplitsNumberSweep class, a class that finds a - * partition of a node along an axis. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_SPLITS_NUMBER_SWEEP_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_SPLITS_NUMBER_SWEEP_IMPL_HPP - -#include "minimal_splits_number_sweep.hpp" - -namespace mlpack { -namespace tree { - -template -template -size_t MinimalSplitsNumberSweep::SweepNonLeafNode( - const size_t axis, - const TreeType* node, - typename TreeType::ElemType& axisCut) -{ - typedef typename TreeType::ElemType ElemType; - - std::vector> sorted(node->NumChildren()); - - for (size_t i = 0; i < node->NumChildren(); i++) - { - sorted[i].first = SplitPolicy::Bound(node->Child(i))[axis].Hi(); - sorted[i].second = i; - } - - // Sort candidates in order to check balancing. - std::sort(sorted.begin(), sorted.end(), - [] (const std::pair& s1, - const std::pair& s2) - { - return s1.first < s2.first; - }); - - size_t minCost = SIZE_MAX; - - // Find a split with the minimal cost. - for (size_t i = 0; i < sorted.size(); i++) - { - size_t numTreeOneChildren = 0; - size_t numTreeTwoChildren = 0; - size_t numSplits = 0; - - // Calculate the number of splits. - for (size_t j = 0; j < node->NumChildren(); j++) - { - const TreeType& child = node->Child(j); - int policy = SplitPolicy::GetSplitPolicy(child, axis, sorted[i].first); - if (policy == SplitPolicy::AssignToFirstTree) - numTreeOneChildren++; - else if (policy == SplitPolicy::AssignToSecondTree) - numTreeTwoChildren++; - else - { - numTreeOneChildren++; - numTreeTwoChildren++; - numSplits++; - } - } - - // Check if the split is possible. - if (numTreeOneChildren <= node->MaxNumChildren() && - numTreeOneChildren > 0 && numTreeTwoChildren <= node->MaxNumChildren() - && numTreeTwoChildren > 0) - { - // Evaluate the cost using the number of splits and balancing. - size_t balance; - - if (sorted.size() / 2 > i ) - balance = sorted.size() / 2 - i; - else - balance = i - sorted.size() / 2; - - size_t cost = numSplits * balance; - if (cost < minCost) - { - minCost = cost; - axisCut = sorted[i].first; - } - } - } - return minCost; -} - -template -template -size_t MinimalSplitsNumberSweep::SweepLeafNode( - const size_t axis, - const TreeType* node, - typename TreeType::ElemType& axisCut) -{ - // Split along the median. - axisCut = (node->Bound()[axis].Lo() + node->Bound()[axis].Hi()) * 0.5; - - if (node->Bound()[axis].Lo() == axisCut) - return SIZE_MAX; - - return 0; -} - - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_MINIMAL_SPLITS_NUMBER_SWEEP_IMPL_HPP - - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/no_auxiliary_information.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/no_auxiliary_information.hpp deleted file mode 100644 index f2c2ca878..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/no_auxiliary_information.hpp +++ /dev/null @@ -1,150 +0,0 @@ -/** - * @file no_auxiliary_information.hpp - * @author Mikhail Lozhnikov - * - * Definition of the NoAuxiliaryInformation class, a class that provides - * no additional information about the nodes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_NO_AUXILIARY_INFORMATION_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_NO_AUXILIARY_INFORMATION_HPP - -namespace mlpack { -namespace tree { - -template -class NoAuxiliaryInformation -{ - public: - //! Construct the auxiliary information object. - NoAuxiliaryInformation() { } - //! Construct the auxiliary information object. - NoAuxiliaryInformation(const TreeType* /* node */) { } - //! Construct the auxiliary information object. - NoAuxiliaryInformation(const NoAuxiliaryInformation& /* other */, - TreeType* /* tree */, - bool /* deepCopy */ = true) { } - //! Construct the auxiliary information object. - NoAuxiliaryInformation(NoAuxiliaryInformation&& /* other */) { } - - //! Copy the auxiliary information object. - NoAuxiliaryInformation& operator=(const NoAuxiliaryInformation& /* other */) - { - return *this; - } - - /** - * Some tree types require to save some properties at the insertion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the insertion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node in which the point is being inserted. - * @param point The global number of the point being inserted. - */ - bool HandlePointInsertion(TreeType* /* node */, const size_t /* point */) - { - return false; - } - - /** - * Some tree types require to save some properties at the insertion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the insertion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node in which the nodeToInsert is being inserted. - * @param nodeToInsert The node being inserted. - * @param insertionLevel The level of the tree at which the nodeToInsert - * should be inserted. - */ - bool HandleNodeInsertion(TreeType* /* node */, - TreeType* /* nodeToInsert */, - bool /* insertionLevel */) - { - return false; - } - - /** - * Some tree types require to save some properties at the deletion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the deletion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node from which the point is being deleted. - * @param localIndex The local index of the point being deleted. - */ - bool HandlePointDeletion(TreeType* /* node */, const size_t /* localIndex */) - { - return false; - } - - /** - * Some tree types require to save some properties at the deletion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the deletion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node from which the node is being deleted. - * @param nodeIndex The local index of the node being deleted. - */ - bool HandleNodeRemoval(TreeType* /* node */, const size_t /* nodeIndex */) - { - return false; - } - - /** - * Some tree types require to propagate the information upward. - * This method should return false if this is not the case. If true is - * returned, the update will be propagated upward. - * - * @param node The node in which the auxiliary information being update. - */ - bool UpdateAuxiliaryInfo(TreeType* /* node */) - { - return false; - } - - /** - * The R++ tree requires to split the maximum bounding rectangle of a node - * that is being split. This method is intended for that. This method is only - * necessary for an AuxiliaryInformationType that is being used in conjunction - * with RPlusTreeSplit. - * - * @param treeOne The first subtree. - * @param treeTwo The second subtree. - * @param axis The axis along which the split is performed. - * @param cut The coordinate at which the node is split. - */ - void SplitAuxiliaryInfo(TreeType* /* treeOne */, - TreeType* /* treeTwo */, - size_t /* axis */, - typename TreeType::ElemType /* cut */) - { } - - - /** - * Nullify the auxiliary information in order to prevent an invalid free. - */ - void NullifyData() - { } - - /** - * Serialize the information. - */ - template - void serialize(Archive &, const unsigned int /* version */) { } -}; - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_NO_AUXILIARY_INFORMATION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_auxiliary_information.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_auxiliary_information.hpp deleted file mode 100644 index f4f3f8a1b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_auxiliary_information.hpp +++ /dev/null @@ -1,168 +0,0 @@ -/** - * @file r_plus_plus_tree_auxiliary_information.hpp - * @author Mikhail Lozhnikov - * - * Definition of the RPlusPlusTreeAuxiliaryInformation class, - * a class that provides some r++-tree specific information - * about the nodes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_AUXILIARY_INFO_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_AUXILIARY_INFO_HPP - -#include -#include "../hrectbound.hpp" - -namespace mlpack { -namespace tree { - -template -class RPlusPlusTreeAuxiliaryInformation -{ - public: - //! The element type held by the tree. - typedef typename TreeType::ElemType ElemType; - //! The bound type held by the auxiliary information. - typedef bound::HRectBound BoundType; - - //! Construct the auxiliary information object. - RPlusPlusTreeAuxiliaryInformation(); - - /** - * Construct this as an auxiliary information for the given node. - * - * @param node The node that stores this auxiliary information. - */ - RPlusPlusTreeAuxiliaryInformation(const TreeType* /* node */); - - /** - * Create an auxiliary information object by copying from another object. - * - * @param other Another auxiliary information object from which the - * information will be copied. - * @param tree The node that holds the auxiliary information. - * @param deepCopy If false, the new object uses the same memory - * (not used here). - */ - RPlusPlusTreeAuxiliaryInformation( - const RPlusPlusTreeAuxiliaryInformation& other, - TreeType* tree, - bool /* deepCopy */ = true); - - /** - * Create an auxiliary information object by moving from another node. - * - * @param other The auxiliary information object from which the information - * will be moved. - */ - RPlusPlusTreeAuxiliaryInformation(RPlusPlusTreeAuxiliaryInformation&& other); - - /** - * Some tree types require to save some properties at the insertion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the insertion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node in which the point is being inserted. - * @param point The global number of the point being inserted. - */ - bool HandlePointInsertion(TreeType* /* node */, const size_t /* point */); - - /** - * Some tree types require to save some properties at the insertion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the insertion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node in which the nodeToInsert is being inserted. - * @param nodeToInsert The node being inserted. - * @param insertionLevel The level of the tree at which the nodeToInsert - * should be inserted. - */ - bool HandleNodeInsertion(TreeType* /* node */, - TreeType* /* nodeToInsert */, - bool /* insertionLevel */); - - /** - * Some tree types require to save some properties at the deletion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the deletion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node from which the point is being deleted. - * @param localIndex The local index of the point being deleted. - */ - bool HandlePointDeletion(TreeType* /* node */, const size_t /* localIndex */); - - /** - * Some tree types require to save some properties at the deletion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the deletion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node from which the node is being deleted. - * @param nodeIndex The local index of the node being deleted. - */ - bool HandleNodeRemoval(TreeType* /* node */, const size_t /* nodeIndex */); - - - /** - * Some tree types require to propagate the information upward. - * This method should return false if this is not the case. If true is - * returned, the update will be propagated upward. - * - * @param node The node in which the auxiliary information being update. - */ - bool UpdateAuxiliaryInfo(TreeType* /* node */); - - /** - * The R++ tree requires to split the maximum bounding rectangle of a node - * that is being split. This method is intended for that. - * - * @param treeOne The first subtree. - * @param treeTwo The second subtree. - * @param axis The axis along which the split is performed. - * @param cut The coordinate at which the node is split. - */ - void SplitAuxiliaryInfo(TreeType* treeOne, - TreeType* treeTwo, - const size_t axis, - const ElemType cut); - - /** - * Nullify the auxiliary information in order to prevent an invalid free. - */ - void NullifyData(); - - //! Return the maximum bounding rectangle. - BoundType& OuterBound() { return outerBound; } - - //! Modify the maximum bounding rectangle. - const BoundType& OuterBound() const { return outerBound; } - - private: - //! The maximum bounding rectangle. - BoundType outerBound; - - public: - /** - * Serialize the information. - */ - template - void serialize(Archive &, const unsigned int /* version */); -}; - -} // namespace tree -} // namespace mlpack - -#include "r_plus_plus_tree_auxiliary_information_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_AUXILIARY_INFO_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_auxiliary_information_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_auxiliary_information_impl.hpp deleted file mode 100644 index e1e965955..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_auxiliary_information_impl.hpp +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @file r_plus_plus_tree_auxiliary_information.hpp - * @author Mikhail Lozhnikov - * - * Implementation of the RPlusPlusTreeAuxiliaryInformation class, - * a class that provides some r++-tree specific information - * about the nodes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_AUXILIARY_INFO_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_AUXILIARY_INFO_IMPL_HPP - -#include "r_plus_plus_tree_auxiliary_information.hpp" - -namespace mlpack { -namespace tree { - -template -RPlusPlusTreeAuxiliaryInformation:: -RPlusPlusTreeAuxiliaryInformation() : - outerBound(0) -{ /* Nothing to do. */ } - -template -RPlusPlusTreeAuxiliaryInformation:: -RPlusPlusTreeAuxiliaryInformation(const TreeType* tree) : - outerBound(tree->Parent() ? - tree->Parent()->AuxiliaryInfo().OuterBound() : - tree->Bound().Dim()) -{ - // Initialize the maximum bounding rectangle if the node is the root - if (!tree->Parent()) - { - for (size_t k = 0; k < outerBound.Dim(); k++) - { - outerBound[k].Lo() = std::numeric_limits::lowest(); - outerBound[k].Hi() = std::numeric_limits::max(); - } - } -} - -template -RPlusPlusTreeAuxiliaryInformation:: -RPlusPlusTreeAuxiliaryInformation( - const RPlusPlusTreeAuxiliaryInformation& other, - TreeType* /* tree */, - bool /* deepCopy */) : - outerBound(other.OuterBound()) -{ /* Nothing to do. */ } - -template -RPlusPlusTreeAuxiliaryInformation:: -RPlusPlusTreeAuxiliaryInformation(RPlusPlusTreeAuxiliaryInformation&& other) : - outerBound(std::move(other.outerBound)) -{ /* Nothing to do. */ } - -template -bool RPlusPlusTreeAuxiliaryInformation::HandlePointInsertion( - TreeType* /* node */, const size_t /* point */) -{ - return false; -} - -template -bool RPlusPlusTreeAuxiliaryInformation::HandleNodeInsertion( - TreeType* /* node */, - TreeType* /* nodeToInsert */, - bool /* insertionLevel */) -{ - assert(false); - return false; -} - -template -bool RPlusPlusTreeAuxiliaryInformation::HandlePointDeletion( - TreeType* /* node */, const size_t /* localIndex */) -{ - return false; -} - -template -bool RPlusPlusTreeAuxiliaryInformation::HandleNodeRemoval( - TreeType* /* node */, const size_t /* nodeIndex */) -{ - return false; -} - -template -bool RPlusPlusTreeAuxiliaryInformation::UpdateAuxiliaryInfo( - TreeType* /* node */) -{ - return false; -} - -template -void RPlusPlusTreeAuxiliaryInformation::SplitAuxiliaryInfo( - TreeType* treeOne, - TreeType* treeTwo, - const size_t axis, - const typename TreeType::ElemType cut) -{ - typedef bound::HRectBound Bound; - Bound& treeOneBound = treeOne->AuxiliaryInfo().OuterBound(); - Bound& treeTwoBound = treeTwo->AuxiliaryInfo().OuterBound(); - - // Copy the maximum bounding rectangle. - treeOneBound = outerBound; - treeTwoBound = outerBound; - - // Set proper limits. - treeOneBound[axis].Hi() = cut; - treeTwoBound[axis].Lo() = cut; -} - -template -void RPlusPlusTreeAuxiliaryInformation::NullifyData() -{ /* Nothing to do */ } - -/** - * Serialize the information. - */ -template -template -void RPlusPlusTreeAuxiliaryInformation::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(outerBound); -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_AUXILIARY_INFO_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_descent_heuristic.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_descent_heuristic.hpp deleted file mode 100644 index e5efc491b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_descent_heuristic.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file r_plus_plus_tree_descent_heuristic.hpp - * @author Mikhail Lozhnikov - * - * Definition of RPlusPlusTreeDescentHeuristic, a class that chooses the best - * child of a node in an R++ tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_DESCENT_HEURISTIC_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_DESCENT_HEURISTIC_HPP - -#include - -namespace mlpack { -namespace tree { - -class RPlusPlusTreeDescentHeuristic -{ - public: - /** - * Evaluate the node using a heuristic. Returns the number of the node - * with minimum largest Hilbert value is greater than the Hilbert value of - * the point being inserted. - * - * @param node The node that is being evaluated. - * @param point The number of the point that is being inserted. - */ - template - static size_t ChooseDescentNode(TreeType* node, const size_t point); - - /** - * Evaluate the node using a heuristic. Returns the number of the node - * with minimum largest Hilbert value is greater than the largest - * Hilbert value of the point being inserted. - * - * @param node The node that is being evaluated. - * @param insertedNode The node that is being inserted. - */ - template - static size_t ChooseDescentNode(const TreeType* node, - const TreeType* insertedNode); -}; - -} // namespace tree -} // namespace mlpack - -#include "r_plus_plus_tree_descent_heuristic_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_DESCENT_HEURISTIC_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_descent_heuristic_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_descent_heuristic_impl.hpp deleted file mode 100644 index 66f47c136..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_descent_heuristic_impl.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file r_plus_plus_tree_descent_heuristic_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of RPlusPlusTreeDescentHeuristic, a class that chooses the - * best child of a node in an R++ tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_DESCENT_HEURISTIC_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_DESCENT_HEURISTIC_IMPL_HPP - -#include "r_plus_plus_tree_descent_heuristic.hpp" -#include "../hrectbound.hpp" - -namespace mlpack { -namespace tree { - -template -size_t RPlusPlusTreeDescentHeuristic::ChooseDescentNode( - TreeType* node, const size_t point) -{ - // Find the node whose maximum bounding rectangle contains the point. - for (size_t bestIndex = 0; bestIndex < node->NumChildren(); bestIndex++) - { - if (node->Child(bestIndex).AuxiliaryInfo().OuterBound().Contains( - node->Dataset().col(point))) - return bestIndex; - } - - // We should never reach this point. - assert(false); - - return 0; -} - -template -size_t RPlusPlusTreeDescentHeuristic::ChooseDescentNode( - const TreeType* /* node */, const TreeType* /* insertedNode */) -{ - // Should never be used. - assert(false); - - return 0; -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_RPP_TREE_DESCENT_HEURISTIC_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_split_policy.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_split_policy.hpp deleted file mode 100644 index d2c1bb1d1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_plus_tree_split_policy.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file r_plus_plus_tree_split_policy.hpp - * @author Mikhail Lozhnikov - * - * Definition and implementation of the RPlusPlusTreeSplitPolicy class, a class - * that helps to determine the subtree into which we should insert an - * intermediate node. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_PLUS_TREE_SPLIT_POLICY_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_PLUS_TREE_SPLIT_POLICY_HPP - -namespace mlpack { -namespace tree { - -/** - * The RPlusPlusTreeSplitPolicy helps to determine the subtree into which - * we should insert a child of an intermediate node that is being split. - * This class is designed for the R++ tree. - */ -class RPlusPlusTreeSplitPolicy -{ - public: - //! Indicate that the child should be split. - static const int SplitRequired = 0; - //! Indicate that the child should be inserted to the first subtree. - static const int AssignToFirstTree = 1; - //! Indicate that the child should be inserted to the second subtree. - static const int AssignToSecondTree = 2; - - /** - * This method returns SplitRequired if a child of an intermediate node should - * be split, AssignToFirstTree if the child should be inserted to the first - * subtree, AssignToSecondTree if the child should be inserted to the second - * subtree. The method makes desicion according to the maximum bounding - * rectangle of the child, the axis along which the intermediate node is being - * split and the coordinate at which the node is being split. - * - * @param child A child of the node that is being split. - * @param axis The axis along which the node is being split. - * @param cut The coordinate at which the node is being split. - */ - template - static int GetSplitPolicy(const TreeType& child, - const size_t axis, - const typename TreeType::ElemType cut) - { - if (child.AuxiliaryInfo().OuterBound()[axis].Hi() <= cut) - return AssignToFirstTree; - else if (child.AuxiliaryInfo().OuterBound()[axis].Lo() >= cut) - return AssignToSecondTree; - - return SplitRequired; - } - - /** - * Return the maximum bounding rectangle of the node. - * This method should always return the bound that is used for the - * decision-making in GetSplitPolicy(). - * - * @param node The node whose bound is requested. - */ - template - static const - bound::HRectBound& - Bound(const TreeType& node) - { - return node.AuxiliaryInfo().OuterBound(); - } -}; - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_PLUS_TREE_SPLIT_POLICY_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_descent_heuristic.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_descent_heuristic.hpp deleted file mode 100644 index 717b9698a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_descent_heuristic.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file r_plus_tree_descent_heuristic.hpp - * @author Mikhail Lozhnikov - * - * Definition of RPlusTreeDescentHeuristic, a class that chooses the best child - * of a node in an R+ tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_DESCENT_HEURISTIC_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_DESCENT_HEURISTIC_HPP - -#include - -namespace mlpack { -namespace tree { - -class RPlusTreeDescentHeuristic -{ - public: - /** - * Evaluate the node using a heuristic. Returns the number of the node - * with minimum largest Hilbert value is greater than the Hilbert value of - * the point being inserted. - * - * @param node The node that is being evaluated. - * @param point The number of the point that is being inserted. - */ - template - static size_t ChooseDescentNode(TreeType* node, const size_t point); - - /** - * Evaluate the node using a heuristic. Returns the number of the node - * with minimum largest Hilbert value is greater than the largest - * Hilbert value of the point being inserted. - * - * @param node The node that is being evaluated. - * @param insertedNode The node that is being inserted. - */ - template - static size_t ChooseDescentNode(const TreeType* /* node */, - const TreeType* /*insertedNode */); -}; - -} // namespace tree -} // namespace mlpack - -#include "r_plus_tree_descent_heuristic_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_DESCENT_HEURISTIC_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_descent_heuristic_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_descent_heuristic_impl.hpp deleted file mode 100644 index fd27a270c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_descent_heuristic_impl.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @file hilbert_r_tree_descent_heuristic_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of HilbertRTreeDescentHeuristic, a class that chooses the best child - * of a node in an R tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_DESCENT_HEURISTIC_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_DESCENT_HEURISTIC_IMPL_HPP - -#include "r_plus_tree_descent_heuristic.hpp" -#include "../hrectbound.hpp" - -namespace mlpack { -namespace tree { - -template -size_t RPlusTreeDescentHeuristic::ChooseDescentNode(TreeType* node, - const size_t point) -{ - typedef typename TreeType::ElemType ElemType; - size_t bestIndex = 0; - bool success = true; - - // Try to find a node that contains the point. - for (bestIndex = 0; bestIndex < node->NumChildren(); bestIndex++) - { - if (node->Child(bestIndex).Bound().Contains( - node->Dataset().col(point))) - return bestIndex; - } - - // No one node contains the point. Try to enlarge a node in such a way, that - // the resulting node do not overlap other nodes. - for (bestIndex = 0; bestIndex < node->NumChildren(); bestIndex++) - { - bound::HRectBound bound = - node->Child(bestIndex).Bound(); - bound |= node->Dataset().col(point); - - success = true; - - for (size_t j = 0; j < node->NumChildren(); j++) - { - if (j == bestIndex) - continue; - success = false; - // Two nodes overlap if and only if there are no dimension in which - // they do not overlap each other. - for (size_t k = 0; k < node->Bound().Dim(); k++) - { - if (bound[k].Lo() >= node->Child(j).Bound()[k].Hi() || - node->Child(j).Bound()[k].Lo() >= bound[k].Hi()) - { - // We found the dimension in which these nodes do not overlap - // each other. - success = true; - break; - } - } - if (!success) // These two nodes overlap each other. - break; - } - if (success) // We found two nodes that do no overlap each other. - break; - } - - if (!success) // We could not find two nodes that do no overlap each other. - { - size_t depth = node->TreeDepth(); - - // Create a new node into which we will insert the point. - TreeType* tree = node; - while (depth > 1) - { - TreeType* child = new TreeType(tree); - - tree->children[tree->NumChildren()++] = child; - tree = child; - depth--; - } - return node->NumChildren() - 1; - } - - assert(bestIndex < node->NumChildren()); - - return bestIndex; -} - -template -size_t RPlusTreeDescentHeuristic::ChooseDescentNode( - const TreeType* /* node */, const TreeType* /*insertedNode */) -{ - // Should never be used. - assert(false); - - return 0; -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_DESCENT_HEURISTIC_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split.hpp deleted file mode 100644 index 0b0a5d84d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split.hpp +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @file r_plus_tree_split.hpp - * @author Mikhail Lozhnikov - * - * Definition of the RPlusTreeSplit class, a class that splits the nodes of an - * R+ (or R++) tree, starting at a leaf node and moving upwards if necessary. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_HPP - -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * The RPlusTreeSplit class performs the split process of a node on overflow. - * - * @tparam SplitPolicyType The class that helps to determine the subtree into - * which we should insert a child node. - * @tparam SweepType The class that finds the partition of a node along a given - * axis. The partition algorithm tries to find a partition along each axis, - * evaluates each partition and chooses the best one. - */ -template class SweepType> -class RPlusTreeSplit -{ - public: - typedef SplitPolicyType SplitPolicy; - /** - * Split a leaf node using the "default" algorithm. If necessary, this split - * will propagate upwards through the tree. - * @param node. The node that is being split. - * @param relevels Not used. - */ - template - static void SplitLeafNode(TreeType* tree, std::vector& relevels); - - /** - * Split a non-leaf node using the "default" algorithm. If this is a root - * node, the tree increases in depth. - * @param node. The node that is being split. - * @param relevels Not used. - */ - template - static bool SplitNonLeafNode(TreeType* tree, std::vector& relevels); - - private: - /** - * Split a leaf node along an axis. - * - * @param tree The node that is being split into two new nodes. - * @param treeOne The first subtree of two resulting subtrees. - * @param treeOne The second subtree of two resulting subtrees. - * @param cutAxis The axis along which the node is being split. - * @param cut The coordinate at which the node is being split. - */ - template - static void SplitLeafNodeAlongPartition( - TreeType* tree, - TreeType* treeOne, - TreeType* treeTwo, - const size_t cutAxis, - const typename TreeType::ElemType cut); - - /** - * Split a non-leaf node along an axis. This method propagates the split - * downward up to a leaf node if necessary. - * - * @param tree The node that is being split into two new nodes. - * @param treeOne The first subtree of two resulting subtrees. - * @param treeOne The second subtree of two resulting subtrees. - * @param cutAxis The axis along which the node is being split. - * @param cut The coordinate at which the node is being split. - */ - template - static void SplitNonLeafNodeAlongPartition( - TreeType* tree, - TreeType* treeOne, - TreeType* treeTwo, - const size_t cutAxis, - const typename TreeType::ElemType cut); - - /** - * This method is used to make sure that the tree has equivalent maximum depth - * in every branch. The method should be invoked if one of two resulting - * subtrees is empty after the split process - * (i.e. the subtree contains no children). - * The method convert the empty node into an empty subtree (increase the node - * in depth). - * - * @param tree One of two subtrees that is not empty. - * @param emptyTree The empty subtree. - */ - template - static void AddFakeNodes(const TreeType* tree, TreeType* emptyTree); - - /** - * Partition a node using SweepType. This method invokes - * SweepType::Sweep(Non)LeafNode() for each dimension and chooses the - * best one. The method returns false if the node needn't partitioning. - * Overwise, the method returns true. If the method failed in finding - * an acceptable partition, the minCutAxis will be equal to the number of - * dimensions. - * - * @param node The node that is being split. - * @param minCutAxis The axis along which the node will be split. - * @param minCut The coordinate at which the node will be split. - */ - template - static bool PartitionNode(const TreeType* node, - size_t& minCutAxis, - typename TreeType::ElemType& minCut); - - /** - * Insert a node into another node. - */ - template - static void InsertNodeIntoTree(TreeType* destTree, TreeType* srcNode); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation -#include "r_plus_tree_split_impl.hpp" - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split_impl.hpp deleted file mode 100644 index 0293f341e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split_impl.hpp +++ /dev/null @@ -1,380 +0,0 @@ -/** - * @file r_plus_tree_split_impl.hpp - * @author Mikhail Lozhnikov - * - * Implementation of class (RPlusTreeSplit) to split a RectangleTree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_IMPL_HPP - -#include "r_plus_tree_split.hpp" -#include "r_plus_plus_tree_auxiliary_information.hpp" -#include "r_plus_tree_split_policy.hpp" -#include "r_plus_plus_tree_split_policy.hpp" - -namespace mlpack { -namespace tree { - -template class SweepType> -template -void RPlusTreeSplit:: -SplitLeafNode(TreeType* tree, std::vector& relevels) -{ - typedef typename TreeType::ElemType ElemType; - - if (tree->Count() == 1) - { - // Check if an intermediate node was added during the insertion process. - // i.e. we couldn't enlarge a node of the R+ tree. So, one of intermediate - // nodes may be overflowed. - TreeType* node = tree->Parent(); - - while (node != NULL) - { - if (node->NumChildren() == node->MaxNumChildren() + 1) - { - // Split the overflowed node. - RPlusTreeSplit::SplitNonLeafNode(node, relevels); - return; - } - node = node->Parent(); - } - return; - } - else if (tree->Count() <= tree->MaxLeafSize()) - { - return; - } - - // If we are splitting the root node, we need will do things differently so - // that the constructor and other methods don't confuse the end user by giving - // an address of another node. - if (tree->Parent() == NULL) - { - // We actually want to copy this way. Pointers and everything. - TreeType* copy = new TreeType(*tree, false); - copy->Parent() = tree; - tree->Count() = 0; - tree->NullifyData(); - // Because this was a leaf node, numChildren must be 0. - tree->children[(tree->NumChildren())++] = copy; - assert(tree->NumChildren() == 1); - - RPlusTreeSplit::SplitLeafNode(copy, relevels); - return; - } - - size_t cutAxis = tree->Bound().Dim(); - ElemType cut = std::numeric_limits::lowest(); - - // Try to find a partiotion of the node. - if (!PartitionNode(tree, cutAxis, cut)) - return; - - // If we could not find a suitable partition. - if (cutAxis == tree->Bound().Dim()) - { - tree->MaxLeafSize()++; - tree->points.resize(tree->MaxLeafSize() + 1); - Log::Warn << "Could not find an acceptable partition." - "The size of the node will be increased."; - return; - } - - TreeType* treeOne = new TreeType(tree->Parent(), tree->MaxNumChildren()); - TreeType* treeTwo = new TreeType(tree->Parent(), tree->MaxNumChildren()); - treeOne->MinLeafSize() = 0; - treeOne->MinNumChildren() = 0; - treeTwo->MinLeafSize() = 0; - treeTwo->MinNumChildren() = 0; - - // Split the node into two new nodes. - SplitLeafNodeAlongPartition(tree, treeOne, treeTwo, cutAxis, cut); - - TreeType* parent = tree->Parent(); - size_t i = 0; - while (parent->children[i] != tree) - i++; - - assert(i < parent->NumChildren()); - - // Insert two new nodes to the tree. - parent->children[i] = treeOne; - parent->children[parent->NumChildren()++] = treeTwo; - - assert(parent->NumChildren() <= parent->MaxNumChildren() + 1); - - // Propagate the split upward if necessary. - if (parent->NumChildren() == parent->MaxNumChildren() + 1) - RPlusTreeSplit::SplitNonLeafNode(parent, relevels); - - tree->SoftDelete(); -} - -template class SweepType> -template -bool RPlusTreeSplit:: -SplitNonLeafNode(TreeType* tree, std::vector& relevels) -{ - typedef typename TreeType::ElemType ElemType; - // If we are splitting the root node, we need will do things differently so - // that the constructor and other methods don't confuse the end user by giving - // an address of another node. - if (tree->Parent() == NULL) - { - // We actually want to copy this way. Pointers and everything. - TreeType* copy = new TreeType(*tree, false); - - copy->Parent() = tree; - tree->NumChildren() = 0; - tree->NullifyData(); - tree->children[(tree->NumChildren())++] = copy; - - RPlusTreeSplit::SplitNonLeafNode(copy, relevels); - return true; - } - size_t cutAxis = tree->Bound().Dim(); - ElemType cut = std::numeric_limits::lowest(); - - // Try to find a partiotion of the node. - if ( !PartitionNode(tree, cutAxis, cut)) - return false; - - // If we could not find a suitable partition. - if (cutAxis == tree->Bound().Dim()) - { - tree->MaxNumChildren()++; - tree->children.resize(tree->MaxNumChildren() + 1); - Log::Warn << "Could not find an acceptable partition." - "The size of the node will be increased."; - return false; - } - - TreeType* treeOne = new TreeType(tree->Parent(), tree->MaxNumChildren()); - TreeType* treeTwo = new TreeType(tree->Parent(), tree->MaxNumChildren()); - treeOne->MinLeafSize() = 0; - treeOne->MinNumChildren() = 0; - treeTwo->MinLeafSize() = 0; - treeTwo->MinNumChildren() = 0; - - // Split the node into two new nodes. - SplitNonLeafNodeAlongPartition(tree, treeOne, treeTwo, cutAxis, cut); - - TreeType* parent = tree->Parent(); - size_t i = 0; - while (parent->children[i] != tree) - i++; - - assert(i < parent->NumChildren()); - - // Insert two new nodes to the tree. - parent->children[i] = treeOne; - parent->children[parent->NumChildren()++] = treeTwo; - - tree->SoftDelete(); - - assert(parent->NumChildren() <= parent->MaxNumChildren() + 1); - - // Propagate the split upward if necessary. - if (parent->NumChildren() == parent->MaxNumChildren() + 1) - RPlusTreeSplit::SplitNonLeafNode(parent, relevels); - - return false; -} - -template class SweepType> -template -void RPlusTreeSplit::SplitLeafNodeAlongPartition( - TreeType* tree, - TreeType* treeOne, - TreeType* treeTwo, - const size_t cutAxis, - const typename TreeType::ElemType cut) -{ - // Split the auxiliary information. - tree->AuxiliaryInfo().SplitAuxiliaryInfo(treeOne, treeTwo, cutAxis, cut); - - // Ensure that the capacity of the nodes is sufficient. - if (treeOne->MaxLeafSize() < tree->NumPoints()) - { - treeOne->MaxLeafSize() = tree->NumPoints(); - treeOne->points.resize(treeOne->MaxLeafSize() + 1); - } - - if (treeTwo->MaxLeafSize() < tree->NumPoints()) - { - treeTwo->MaxLeafSize() = tree->NumPoints(); - treeTwo->points.resize(treeTwo->MaxLeafSize() + 1); - } - - // Insert points into the corresponding subtree. - for (size_t i = 0; i < tree->NumPoints(); i++) - { - if (tree->Dataset().col(tree->Point(i))[cutAxis] <= cut) - { - treeOne->Point(treeOne->Count()++) = tree->Point(i); - treeOne->Bound() |= tree->Dataset().col(tree->Point(i)); - } - else - { - treeTwo->Point(treeTwo->Count()++) = tree->Point(i); - treeTwo->Bound() |= tree->Dataset().col(tree->Point(i)); - } - } - // Update the number of descandants. - treeOne->numDescendants = treeOne->Count(); - treeTwo->numDescendants = treeTwo->Count(); - - assert(treeOne->Count() <= treeOne->MaxLeafSize()); - assert(treeTwo->Count() <= treeTwo->MaxLeafSize()); - - assert(tree->Count() == treeOne->Count() + treeTwo->Count()); - assert(treeOne->Bound()[cutAxis].Hi() < treeTwo->Bound()[cutAxis].Lo()); -} - -template class SweepType> -template -void RPlusTreeSplit::SplitNonLeafNodeAlongPartition( - TreeType* tree, - TreeType* treeOne, - TreeType* treeTwo, - const size_t cutAxis, - const typename TreeType::ElemType cut) -{ - // Split the auxiliary information. - tree->AuxiliaryInfo().SplitAuxiliaryInfo(treeOne, treeTwo, cutAxis, cut); - - // Insert children into the corresponding subtree. - for (size_t i = 0; i < tree->NumChildren(); i++) - { - TreeType* child = tree->children[i]; - int policy = SplitPolicyType::GetSplitPolicy(*child, cutAxis, cut); - - if (policy == SplitPolicyType::AssignToFirstTree) - { - InsertNodeIntoTree(treeOne, child); - child->Parent() = treeOne; - } - else if (policy == SplitPolicyType::AssignToSecondTree) - { - InsertNodeIntoTree(treeTwo, child); - child->Parent() = treeTwo; - } - else - { - // The child should be split (i.e. the partition divides its bound). - TreeType* childOne = new TreeType(treeOne); - TreeType* childTwo = new TreeType(treeTwo); - treeOne->MinLeafSize() = 0; - treeOne->MinNumChildren() = 0; - treeTwo->MinLeafSize() = 0; - treeTwo->MinNumChildren() = 0; - - // Propagate the split downward. - if (child->IsLeaf()) - SplitLeafNodeAlongPartition(child, childOne, childTwo, cutAxis, cut); - else - SplitNonLeafNodeAlongPartition(child, childOne, childTwo, cutAxis, cut); - - InsertNodeIntoTree(treeOne, childOne); - InsertNodeIntoTree(treeTwo, childTwo); - - child->SoftDelete(); - } - } - - assert(treeOne->NumChildren() + treeTwo->NumChildren() != 0); - - // Add a fake subtree if one of the subtrees is empty. - if (treeOne->NumChildren() == 0) - AddFakeNodes(treeTwo, treeOne); - else if (treeTwo->NumChildren() == 0) - AddFakeNodes(treeOne, treeTwo); - - assert(treeOne->NumChildren() <= treeOne->MaxNumChildren()); - assert(treeTwo->NumChildren() <= treeTwo->MaxNumChildren()); -} - -template class SweepType> -template -void RPlusTreeSplit:: -AddFakeNodes(const TreeType* tree, TreeType* emptyTree) -{ - size_t numDescendantNodes = tree->TreeDepth() - 1; - - TreeType* node = emptyTree; - for (size_t i = 0; i < numDescendantNodes; i++) - { - TreeType* child = new TreeType(node); - node->children[node->NumChildren()++] = child; - - node = child; - } -} - -template class SweepType> -template -bool RPlusTreeSplit:: -PartitionNode(const TreeType* node, size_t& minCutAxis, - typename TreeType::ElemType& minCut) -{ - if ((node->NumChildren() <= node->MaxNumChildren() && !node->IsLeaf()) || - (node->Count() <= node->MaxLeafSize() && node->IsLeaf())) - return false; // No partition required. - - // Define the type of the sweep cost. - typedef typename - SweepType::template SweepCost::type - SweepCostType; - - SweepCostType minCost = std::numeric_limits::max(); - minCutAxis = node->Bound().Dim(); - - // Find the sweep with a minimal cost. - for (size_t k = 0; k < node->Bound().Dim(); k++) - { - typename TreeType::ElemType cut; - SweepCostType cost; - - if (node->IsLeaf()) - cost = SweepType::SweepLeafNode(k, node, cut); - else - cost = SweepType::SweepNonLeafNode(k, node, cut); - - if (cost < minCost) - { - minCost = cost; - minCutAxis = k; - minCut = cut; - } - } - - return true; -} - -template class SweepType> -template -void RPlusTreeSplit:: -InsertNodeIntoTree(TreeType* destTree, TreeType* srcNode) -{ - destTree->Bound() |= srcNode->Bound(); - destTree->numDescendants += srcNode->numDescendants; - destTree->children[destTree->NumChildren()++] = srcNode; -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split_policy.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split_policy.hpp deleted file mode 100644 index 3b22375b3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_plus_tree_split_policy.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file r_plus_tree_split_policy.hpp - * @author Mikhail Lozhnikov - * - * Definition and implementation of the RPlusTreeSplitPolicy class, a class that - * helps to determine the subtree into which we should insert an intermediate - * node. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_POLICY_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_POLICY_HPP - -namespace mlpack { -namespace tree { - -/** - * The RPlusPlusTreeSplitPolicy helps to determine the subtree into which - * we should insert a child of an intermediate node that is being split. - * This class is designed for the R+ tree. - */ -class RPlusTreeSplitPolicy -{ - public: - //! Indicate that the child should be split. - static const int SplitRequired = 0; - //! Indicate that the child should be inserted to the first subtree. - static const int AssignToFirstTree = 1; - //! Indicate that the child should be inserted to the second subtree. - static const int AssignToSecondTree = 2; - - /** - * This method returns SplitRequired if a child of an intermediate node should - * be split, AssignToFirstTree if the child should be inserted to the first - * subtree, AssignToSecondTree if the child should be inserted to the second - * subtree. The method makes desicion according to the minimum bounding - * rectangle of the child, the axis along which the intermediate node is being - * split and the coordinate at which the node is being split. - * - * @param child A child of the node that is being split. - * @param axis The axis along which the node is being split. - * @param cut The coordinate at which the node is being split. - */ - template - static int GetSplitPolicy(const TreeType& child, - const size_t axis, - const typename TreeType::ElemType cut) - { - if (child.Bound()[axis].Hi() <= cut) - return AssignToFirstTree; - else if (child.Bound()[axis].Lo() >= cut) - return AssignToSecondTree; - - return SplitRequired; - } - - /** - * Return the minimum bounding rectangle of the node. - * This method should always return the bound that is used for the - * decision-making in GetSplitPolicy(). - * - * @param node The node whose bound is requested. - */ - template - static const - bound::HRectBound& - Bound(const TreeType& node) - { - return node.Bound(); - } -}; - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_R_PLUS_TREE_SPLIT_POLICY_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_descent_heuristic.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_descent_heuristic.hpp deleted file mode 100644 index cfc8b059a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_descent_heuristic.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file r_star_tree_descent_heuristic.hpp - * @author Andrew Wells - * - * Definition of RStarTreeDescentHeuristic, a class that chooses the best child - * of a node in an R tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_STAR_TREE_DESCENT_HEURISTIC_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_STAR_TREE_DESCENT_HEURISTIC_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * When descending a RectangleTree to insert a point, we need to have a way to - * choose a child node when the point isn't enclosed by any of them. This - * heuristic is used to do so using the rules for the R* tree. - */ -class RStarTreeDescentHeuristic -{ - public: - /** - * Evaluate the node using a heuristic. The heuristic guarantees two things: - * - * 1. If point is contained in (or on) bound, the value returned is zero. - * 2. If the point is not contained in (or on) bound, the value returned is - * greater than zero. - * - * @param bound The bound used for the node that is being evaluated. - * @param point The index of the point that is being inserted. - */ - template - static size_t ChooseDescentNode(const TreeType* node, const size_t point); - - template - static size_t ChooseDescentNode(const TreeType* node, - const TreeType* insertedNode); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "r_star_tree_descent_heuristic_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_descent_heuristic_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_descent_heuristic_impl.hpp deleted file mode 100644 index 52bde9976..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_descent_heuristic_impl.hpp +++ /dev/null @@ -1,231 +0,0 @@ -/** - * @file r_star_tree_descent_heuristic_impl.hpp - * @author Andrew Wells - * - * Implementation of RStarTreeDescentHeuristic, a class that chooses the best child of a node in - * an R tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_STAR_TREE_DESCENT_HEURISTIC_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_STAR_TREE_DESCENT_HEURISTIC_IMPL_HPP - -#include "r_star_tree_descent_heuristic.hpp" - -namespace mlpack { -namespace tree { - -template -inline size_t RStarTreeDescentHeuristic::ChooseDescentNode( - const TreeType* node, - const size_t point) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - bool tiedOne = false; - std::vector originalScores(node->NumChildren()); - ElemType origMinScore = std::numeric_limits::max(); - - if (node->Child(0).IsLeaf()) - { - // If its children are leaf nodes, use minimum overlap to choose. - size_t bestIndex = 0; - - for (size_t i = 0; i < node->NumChildren(); i++) - { - ElemType sc = 0; - for (size_t j = 0; j < node->NumChildren(); j++) - { - if (j != i) - { - ElemType overlap = 1.0; - ElemType newOverlap = 1.0; - for (size_t k = 0; k < node->Bound().Dim(); k++) - { - ElemType newHigh = std::max(node->Dataset().col(point)[k], - node->Child(i).Bound()[k].Hi()); - ElemType newLow = std::min(node->Dataset().col(point)[k], - node->Child(i).Bound()[k].Lo()); - overlap *= node->Child(i).Bound()[k].Hi() < - node->Child(j).Bound()[k].Lo() || - node->Child(i).Bound()[k].Lo() > - node->Child(j).Bound()[k].Hi() ? 0 : - std::min(node->Child(i).Bound()[k].Hi(), - node->Child(j).Bound()[k].Hi()) - - std::max(node->Child(i).Bound()[k].Lo(), - node->Child(j).Bound()[k].Lo()); - - newOverlap *= newHigh < node->Child(j).Bound()[k].Lo() || - newLow > node->Child(j).Bound()[k].Hi() ? 0 : - std::min(newHigh, node->Child(j).Bound()[k].Hi()) - - std::max(newLow, node->Child(j).Bound()[k].Lo()); - } - sc += newOverlap - overlap; - } - } - - originalScores[i] = sc; - if (sc < origMinScore) - { - origMinScore = sc; - bestIndex = i; - } - else if (sc == origMinScore) - { - tiedOne = true; - } - } - - if (!tiedOne) - return bestIndex; - } - - // We do this if it is not on the second level or if there was a tie. - std::vector scores(node->NumChildren()); - if (tiedOne) - { - // If the first heuristic was tied, we need to eliminate garbage values. - for (size_t i = 0; i < scores.size(); i++) - scores[i] = std::numeric_limits::max(); - } - - std::vector vols(node->NumChildren()); - ElemType minScore = std::numeric_limits::max(); - size_t bestIndex = 0; - bool tied = false; - - for (size_t i = 0; i < node->NumChildren(); i++) - { - if (!tiedOne || originalScores[i] == origMinScore) - { - ElemType v1 = 1.0; - ElemType v2 = 1.0; - for (size_t j = 0; j < node->Bound().Dim(); j++) - { - v1 *= node->Child(i).Bound()[j].Width(); - v2 *= node->Child(i).Bound()[j].Contains( - node->Dataset().col(point)[j]) ? - node->Child(i).Bound()[j].Width() : - (node->Child(i).Bound()[j].Hi() < node->Dataset().col(point)[j] ? - (node->Dataset().col(point)[j] - node->Child(i).Bound()[j].Lo()) : - (node->Child(i).Bound()[j].Hi() - node->Dataset().col(point)[j])); - } - - assert(v2 - v1 >= 0); - vols[i] = v1; - scores[i] = v2 - v1; - - if (v2 - v1 < minScore) - { - minScore = v2 - v1; - bestIndex = i; - } - else if (v2 - v1 == minScore) - { - tied = true; - } - } - } - - if (tied) - { - // We break ties by choosing the smallest bound. - ElemType minVol = std::numeric_limits::max(); - bestIndex = 0; - for (size_t i = 0; i < scores.size(); i++) - { - if (scores[i] == minScore) - { - if (vols[i] < minVol) - { - minVol = vols[i]; - bestIndex = i; - } - } - } - } - - return bestIndex; -} - -/** - * We simplify this to the same code as is used in the regular R tree, since the - * inserted node should always be above the leaf level. If the tree is - * eventually changed to support rectangles, this could be changed to match the - * above code; however, the paper's explanation for their algorithm seems to - * indicate the above is more for points than for rectangles. - */ -template -inline size_t RStarTreeDescentHeuristic::ChooseDescentNode( - const TreeType* node, - const TreeType* insertedNode) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - std::vector scores(node->NumChildren()); - std::vector vols(node->NumChildren()); - ElemType minScore = std::numeric_limits::max(); - size_t bestIndex = 0; - bool tied = false; - - for (size_t i = 0; i < node->NumChildren(); i++) - { - ElemType v1 = 1.0; - ElemType v2 = 1.0; - for (size_t j = 0; j < node->Child(i).Bound().Dim(); j++) - { - v1 *= node->Child(i).Bound()[j].Width(); - v2 *= node->Child(i).Bound()[j].Contains(insertedNode->Bound()[j]) ? - node->Child(i).Bound()[j].Width() : - (insertedNode->Bound()[j].Contains(node->Child(i).Bound()[j]) ? - insertedNode->Bound()[j].Width() : - (insertedNode->Bound()[j].Lo() < node->Child(i).Bound()[j].Lo() ? - (node->Child(i).Bound()[j].Hi() - insertedNode->Bound()[j].Lo()) : - (insertedNode->Bound()[j].Hi() - node->Child(i).Bound()[j].Lo()))); - } - - assert(v2 - v1 >= 0); - vols[i] = v1; - scores[i] = v2 - v1; - - if (v2 - v1 < minScore) - { - minScore = v2 - v1; - bestIndex = i; - } - else if (v2 - v1 == minScore) - { - tied = true; - } - } - - if (tied) - { - // We break ties by choosing the smallest bound. - ElemType minVol = std::numeric_limits::max(); - bestIndex = 0; - for (size_t i = 0; i < scores.size(); i++) - { - if (scores[i] == minScore) - { - if (vols[i] < minVol) - { - minVol = vols[i]; - bestIndex = i; - } - } - } - } - - return bestIndex; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_split.hpp deleted file mode 100644 index 300d829ef..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_split.hpp +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @file r_tree_star_split.hpp - * @author Andrew Wells - * - * Definition of the RStarTreeSplit class, a class that splits the nodes of an R tree, starting - * at a leaf node and moving upwards if necessary. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_STAR_TREE_SPLIT_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_STAR_TREE_SPLIT_HPP - -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * A Rectangle Tree has new points inserted at the bottom. When these - * nodes overflow, we split them, moving up the tree and splitting nodes - * as necessary. - */ -class RStarTreeSplit -{ - public: - /** - * Split a leaf node using the algorithm described in "The R*-tree: An - * Efficient and Robust Access method for Points and Rectangles." If - * necessary, this split will propagate upwards through the tree. - */ - template - static void SplitLeafNode(TreeType *tree, std::vector& relevels); - - /** - * Split a non-leaf node using the "default" algorithm. If this is a root - * node, the tree increases in depth. - */ - template - static bool SplitNonLeafNode(TreeType *tree, std::vector& relevels); - - /** - * Reinsert any points into the tree, if needed. This returns the number of - * points reinserted. - */ - template - static size_t ReinsertPoints(TreeType* tree, std::vector& relevels); - - /** - * Given a node, return the best dimension and the best index to split on. - */ - template - static void PickLeafSplit( - TreeType* tree, - size_t& bestAxis, - size_t& bestIndex); - - private: - /** - * Insert a node into another node. - */ - template - static void InsertNodeIntoTree(TreeType* destTree, TreeType* srcNode); - - /** - * Comparator for sorting with std::pair. This comparator works a little bit - * faster then the default comparator. - */ - template - static bool PairComp(const std::pair& p1, - const std::pair& p2) - { - return p1.first < p2.first; - } -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation -#include "r_star_tree_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_split_impl.hpp deleted file mode 100644 index 6452cb92b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_star_tree_split_impl.hpp +++ /dev/null @@ -1,492 +0,0 @@ -/** - * @file r_star_tree_split_impl.hpp - * @author Andrew Wells - * - * Implementation of class (RStarTreeSplit) to split a RectangleTree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_STAR_TREE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_STAR_TREE_SPLIT_IMPL_HPP - -#include "r_star_tree_split.hpp" -#include "rectangle_tree.hpp" - -#include - -namespace mlpack { -namespace tree { - -/** - * Reinsert any points into the tree, if needed. This returns the number of - * points reinserted. - */ -template -size_t RStarTreeSplit::ReinsertPoints(TreeType* tree, - std::vector& relevels) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - // Check if we need to reinsert. - if (relevels[tree->TreeDepth() - 1]) - { - relevels[tree->TreeDepth() - 1] = false; - - // We sort the points by decreasing distance to the centroid of the bound. - // We then remove the first p entries and reinsert them at the root. - TreeType* root = tree; - while (root->Parent() != NULL) - root = root->Parent(); - size_t p = tree->MaxLeafSize() * 0.3; // The paper says this works the best. - if (p > 0) - { - // We'll only do reinsertions if p > 0. p is the number of points we will - // reinsert. If p == 0, then no reinsertion is necessary and we continue - // with the splitting procedure. - std::vector> sorted(tree->Count()); - arma::Col center; - tree->Bound().Center(center); - for (size_t i = 0; i < sorted.size(); i++) - { - sorted[i].first = tree->Metric().Evaluate(center, - tree->Dataset().col(tree->Point(i))); - sorted[i].second = tree->Point(i); - } - - std::sort(sorted.begin(), sorted.end(), PairComp); - - // Remove the points furthest from the center of the node. - for (size_t i = 0; i < p; i++) - root->DeletePoint(sorted[sorted.size() - 1 - i].second, relevels); - - // Now reinsert the points, but reverse the order---insert the closest to - // the center first. - for (size_t i = p; i > 0; --i) - root->InsertPoint(sorted[sorted.size() - i].second, relevels); - } - - return p; - } - - return 0; -} - -/** - * Given a node, return the best dimension and the best index to split on. - */ -template -void RStarTreeSplit::PickLeafSplit(TreeType* tree, - size_t& bestAxis, - size_t& bestIndex) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - typedef bound::HRectBound BoundType; - - bestAxis = 0; - bestIndex = 0; - ElemType bestScore = std::numeric_limits::max(); - - /** - * Check each dimension, to find which dimension is best to split on. - */ - for (size_t j = 0; j < tree->Bound().Dim(); j++) - { - ElemType axisScore = 0.0; - - // Sort in increasing values of the selected dimension j. - arma::Col dimValues(tree->Count()); - for (size_t i = 0; i < tree->Count(); ++i) - dimValues[i] = tree->Dataset().col(tree->Point(i))[j]; - arma::uvec sortedIndices = arma::sort_index(dimValues); - - // We'll store each of the three scores for each distribution. - const size_t numPossibleSplits = tree->MaxLeafSize() - - 2 * tree->MinLeafSize() + 2; - arma::Col areas(numPossibleSplits, arma::fill::zeros); - arma::Col margins(numPossibleSplits, arma::fill::zeros); - arma::Col overlaps(numPossibleSplits, arma::fill::zeros); - - for (size_t i = 0; i < numPossibleSplits; i++) - { - // The ith arrangement is obtained by placing the first - // tree->MinLeafSize() + i points in one rectangle and the rest in - // another. Then we calculate the three scores for that distribution. - size_t splitIndex = tree->MinLeafSize() + i; - - BoundType bound1(tree->Bound().Dim()); - BoundType bound2(tree->Bound().Dim()); - - for (size_t l = 0; l < splitIndex; l++) - bound1 |= tree->Dataset().col(tree->Point(sortedIndices[l])); - - for (size_t l = splitIndex; l < tree->Count(); l++) - bound2 |= tree->Dataset().col(tree->Point(sortedIndices[l])); - - areas[i] = bound1.Volume() + bound2.Volume(); - overlaps[i] = bound1.Overlap(bound2); - - for (size_t k = 0; k < bound1.Dim(); k++) - margins[i] += bound1[k].Width() + bound2[k].Width(); - - axisScore += margins[i]; - } - - // Is this dimension a new best score? We want the lowest possible score. - if (axisScore < bestScore) - { - bestScore = axisScore; - bestAxis = j; - size_t overlapIndex = 0; - size_t areaIndex = 0; - bool tiedOnOverlap = false; - - for (size_t i = 1; i < areas.n_elem; i++) - { - if (overlaps[i] < overlaps[overlapIndex]) - { - tiedOnOverlap = false; - overlapIndex = i; - areaIndex = i; - } - else if (overlaps[i] == overlaps[overlapIndex]) - { - tiedOnOverlap = true; - if (areas[i] < areas[areaIndex]) - areaIndex = i; - } - } - - // Select the best index for splitting. - bestIndex = (tiedOnOverlap ? areaIndex : overlapIndex); - } - } -} - -/** - * We call GetPointSeeds to get the two points which will be the initial points - * in the new nodes We then call AssignPointDestNode to assign the remaining - * points to the two new nodes. Finally, we delete the old node and insert the - * new nodes into the tree, spliting the parent if necessary. - */ -template -void RStarTreeSplit::SplitLeafNode(TreeType *tree, std::vector& relevels) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - // If there's no need to split, don't. - if (tree->Count() <= tree->MaxLeafSize()) - return; - - // If we haven't yet checked if we need to reinsert on this level, we try - // doing so now. - if (ReinsertPoints(tree, relevels) > 0) - return; - - // We don't need to reinsert. Instead, we need to split the node. - size_t bestAxis; - size_t bestIndex; - PickLeafSplit(tree, bestAxis, bestIndex); - - /** - * Now that we have found the best dimension to split on, re-sort in that - * dimension to prepare for reinsertion of points into the new nodes. - */ - std::vector> sorted(tree->Count()); - for (size_t i = 0; i < sorted.size(); i++) - { - sorted[i].first = tree->Dataset().col(tree->Point(i))[bestAxis]; - sorted[i].second = tree->Point(i); - } - - std::sort(sorted.begin(), sorted.end(), PairComp); - - /** - * If 'tree' is the root of the tree (i.e. if it has no parent), then we must - * create two new child nodes, distribute the points from the original node - * among them, and insert those. If 'tree' is not the root of the tree, then - * we may create only one new child node, redistribute the points from the - * original node between 'tree' and the new node, then insert those nodes into - * the parent. - * - * Here we simply set treeOne and treeTwo to the right values to avoid code - * duplication. - */ - TreeType* par = tree->Parent(); - TreeType* treeOne = (par) ? tree : new TreeType(tree); - TreeType* treeTwo = (par) ? new TreeType(par) : new TreeType(tree); - - // Now clean the node, and we will re-use this. - const size_t numPoints = tree->Count(); - - // Reset the original node's values, regardless of whether it will become - // the new parent or not. - tree->numChildren = 0; - tree->numDescendants = 0; - tree->count = 0; - tree->bound.Clear(); - - // Insert the points into the appropriate tree. - for (size_t i = 0; i < numPoints; i++) - { - if (i < bestIndex + tree->MinLeafSize()) - treeOne->InsertPoint(sorted[i].second); - else - treeTwo->InsertPoint(sorted[i].second); - } - - // Insert the new tree node(s). - if (par) - { - // Just insert the new node into the parent. - par->children[par->NumChildren()++] = treeTwo; - - // If we have overflowed the parent's children, then we need to split that - // node also. - if (par->NumChildren() == par->MaxNumChildren() + 1) - RStarTreeSplit::SplitNonLeafNode(par, relevels); - } - else - { - // Now insert the two nodes into 'tree', which is now a higher-level root - // node in the tree. - InsertNodeIntoTree(tree, treeOne); - InsertNodeIntoTree(tree, treeTwo); - } -} - -/** - * We call GetBoundSeeds to get the two new nodes that this one will be broken - * into. Then we call AssignNodeDestNode to move the children of this node into - * either of those two nodes. Finally, we delete the now unused information and - * recurse up the tree if necessary. We don't need to worry about the bounds - * higher up the tree because they were already updated if necessary. - */ -template -bool RStarTreeSplit::SplitNonLeafNode( - TreeType *tree, - std::vector& relevels) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - typedef bound::HRectBound BoundType; - - // Reinsertion isn't done for non-leaf nodes; the paper doesn't seem to make - // it clear how to reinsert an entire node without reinserting each of the - // points, so we will avoid that here. This is a possible area for - // improvement of this code. - - size_t bestAxis = 0; - size_t bestIndex = 0; - ElemType bestScore = std::numeric_limits::max(); - bool lowIsBetter = true; - - /** - * Check over each dimension to see which is best to use for splitting. - */ - for (size_t j = 0; j < tree->Bound().Dim(); j++) - { - ElemType axisLoScore = 0.0; - ElemType axisHiScore = 0.0; - - // We have to calculate values for both the lower and higher parts of the - // bound. - arma::Col loDimValues(tree->NumChildren()); - arma::Col hiDimValues(tree->NumChildren()); - for (size_t i = 0; i < tree->NumChildren(); i++) - { - loDimValues[i] = tree->Child(i).Bound()[j].Lo(); - hiDimValues[i] = tree->Child(i).Bound()[j].Hi(); - } - arma::uvec sortedLoDimIndices = arma::sort_index(loDimValues); - arma::uvec sortedHiDimIndices = arma::sort_index(hiDimValues); - - // We'll store each of the three scores for each distribution. Remember - // that these are the sums calculated over both the low and high bounds of - // each rectangle. - const size_t numPossibleSplits = tree->MaxNumChildren() - - 2 * tree->MinNumChildren() + 2; - arma::Col areas(2 * numPossibleSplits, arma::fill::zeros); - arma::Col margins(2 * numPossibleSplits, arma::fill::zeros); - arma::Col overlaps(2 * numPossibleSplits, arma::fill::zeros); - - for (size_t i = 0; i < numPossibleSplits; ++i) - { - // The ith arrangement is obtained by placing the first - // tree->MinNumChildren() + i points in one rectangle and the rest in - // another. Then we calculate the three scores for that distribution. - const size_t splitIndex = tree->MinNumChildren() + i; - - BoundType lb1(tree->Bound().Dim()); - BoundType lb2(tree->Bound().Dim()); - BoundType hb1(tree->Bound().Dim()); - BoundType hb2(tree->Bound().Dim()); - - for (size_t l = 0; l < splitIndex; ++l) - { - lb1 |= tree->Child(sortedLoDimIndices[l]).Bound(); - hb1 |= tree->Child(sortedHiDimIndices[l]).Bound(); - } - for (size_t l = splitIndex; l < tree->NumChildren(); ++l) - { - lb2 |= tree->Child(sortedLoDimIndices[l]).Bound(); - hb2 |= tree->Child(sortedHiDimIndices[l]).Bound(); - } - - // Calculate low bound distributions. - areas[2 * i] = lb1.Volume() + lb2.Volume(); - overlaps[2 * i] = lb1.Overlap(lb2); - - // Calculate high bound distributions. - areas[2 * i + 1] = hb1.Volume() + hb2.Volume(); - overlaps[2 * i + 1] = hb1.Overlap(hb2); - - // Now calculate margins for each. - for (size_t k = 0; k < lb1.Dim(); k++) - { - margins[2 * i] += lb1[k].Width() + lb2[k].Width(); - margins[2 * i + 1] += hb1[k].Width() + hb2[k].Width(); - } - - // The score we use is the sum of all scores. - axisLoScore += margins[2 * i]; - axisHiScore += margins[2 * i + 1]; - } - - // If this dimension's score (for lower or higher bound scores) is a new - // best, then extract the necessary split information. - if (std::min(axisLoScore, axisHiScore) < bestScore) - { - bestScore = std::min(axisLoScore, axisHiScore); - if (axisLoScore < axisHiScore) - lowIsBetter = true; - else - lowIsBetter = false; - - bestAxis = j; - - // This will get us either the lower or higher bound depending on which we - // want. Remember that we selected *either* the lower or higher bounds to - // split on, so we want to only check those. - const size_t indexOffset = lowIsBetter ? 0 : 1; - - size_t overlapIndex = indexOffset; - size_t areaIndex = indexOffset; - bool tiedOnOverlap = false; - - // Find the best possible split (and whether it is on the low values or - // high values of the bounds). - for (size_t i = 1; i < numPossibleSplits; i++) - { - // Check bounds. - if (overlaps[2 * i + indexOffset] < overlaps[overlapIndex]) - { - tiedOnOverlap = false; - areaIndex = 2 * i + indexOffset; - overlapIndex = 2 * i + indexOffset; - } - else if (overlaps[i] == overlaps[overlapIndex]) - { - tiedOnOverlap = true; - if (areas[2 * i + indexOffset] < areas[areaIndex]) - areaIndex = 2 * i + indexOffset; - } - } - - bestIndex = ((tiedOnOverlap ? areaIndex : overlapIndex) - indexOffset) / 2 - + tree->MinNumChildren(); - } - } - - // Get a list of the old children. - std::vector oldChildren(tree->NumChildren()); - for (size_t i = 0; i < oldChildren.size(); ++i) - oldChildren[i] = &tree->Child(i); - - /** - * If 'tree' is the root of the tree (i.e. if it has no parent), then we must - * create two new child nodes, distribute the children from the original node - * among them, and insert those. If 'tree' is not the root of the tree, then - * we may create only one new child node, redistribute the children from the - * original node between 'tree' and the new node, then insert those nodes into - * the parent. - * - * Here, we simply set treeOne and treeTwo to the right values to avoid code - * duplication. - */ - TreeType* par = tree->Parent(); - TreeType* treeOne = par ? tree : new TreeType(tree); - TreeType* treeTwo = par ? new TreeType(par) : new TreeType(tree); - - // Now clean the node. - tree->numChildren = 0; - tree->numDescendants = 0; - tree->count = 0; - tree->bound.Clear(); - - // Assemble vector of values. - arma::Col values(oldChildren.size()); - for (size_t i = 0; i < oldChildren.size(); ++i) - { - values[i] = (lowIsBetter ? oldChildren[i]->Bound()[bestAxis].Lo() - : oldChildren[i]->Bound()[bestAxis].Hi()); - } - arma::uvec indices = arma::sort_index(values); - - for (size_t i = 0; i < bestIndex; ++i) - InsertNodeIntoTree(treeOne, oldChildren[indices[i]]); - for (size_t i = bestIndex; i < oldChildren.size(); ++i) - InsertNodeIntoTree(treeTwo, oldChildren[indices[i]]); - - // Insert the new tree node(s). - if (par) - { - // Insert the new node into the parent. The number of descendants does not - // need to be updated. - par->children[par->NumChildren()++] = treeTwo; - } - else - { - // Insert both nodes into 'tree', which is now a higher-level root node. - InsertNodeIntoTree(tree, treeOne); - InsertNodeIntoTree(tree, treeTwo); - - // We have to update the children of treeOne so that they record the correct - // parent. - for (size_t i = 0; i < treeOne->NumChildren(); i++) - treeOne->children[i]->Parent() = treeOne; - } - - // Update the children of treeTwo to have the correct parent. - for (size_t i = 0; i < treeTwo->NumChildren(); i++) - treeTwo->children[i]->Parent() = treeTwo; - - // If we have overflowed hte parent's children, then we need to split that - // node also. - if (par && par->NumChildren() >= par->MaxNumChildren() + 1) - RStarTreeSplit::SplitNonLeafNode(par, relevels); - - return false; -} - -/** - * Insert a node into another node. Expanding the bounds and updating the - * numberOfChildren. - */ -template -void RStarTreeSplit::InsertNodeIntoTree(TreeType* destTree, TreeType* srcNode) -{ - destTree->Bound() |= srcNode->Bound(); - destTree->numDescendants += srcNode->numDescendants; - destTree->children[destTree->NumChildren()++] = srcNode; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic.hpp deleted file mode 100644 index e79a88504..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file r_tree_descent_heuristic.hpp - * @author Andrew Wells - * - * Definition of RTreeDescentHeuristic, a class that chooses the best child of a - * node in an R tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * When descending a RectangleTree to insert a point, we need to have a way to - * choose a child node when the point isn't enclosed by any of them. This - * heuristic is used to do so. - */ -class RTreeDescentHeuristic -{ - public: - /** - * Evaluate the node using a heuristic. The heuristic guarantees two things: - * - * 1. If point is contained in (or on) the bound, the value returned is zero. - * 2. If the point is not contained in (or on) the bound, the value returned - * is greater than zero. - * - * @param node The node that is being evaluated. - * @param point The index of the point that is being inserted. - */ - template - static size_t ChooseDescentNode(const TreeType* node, const size_t point); - - /** - * Evaluate the node using a heuristic. The heuristic guarantees two things: - * - * 1. If point is contained in (or on) the bound, the value returned is zero. - * 2. If the point is not contained in (or on) the bound, the value returned - * is greater than zero. - * - * @param node The node that is being evaluated. - * @param insertedNode The node that is being inserted. - */ - template - static size_t ChooseDescentNode(const TreeType* node, - const TreeType* insertedNode); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "r_tree_descent_heuristic_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic_impl.hpp deleted file mode 100644 index abb04566d..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic_impl.hpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @file r_tree_descent_heuristic_impl.hpp - * @author Andrew Wells - * - * Implementation of RTreeDescentHeuristic, a class that chooses the best child - * of a node in an R tree when inserting a new point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP - -#include "r_tree_descent_heuristic.hpp" - -namespace mlpack { -namespace tree { - -template -inline size_t RTreeDescentHeuristic::ChooseDescentNode(const TreeType* node, - const size_t point) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - ElemType minScore = std::numeric_limits::max(); - int bestIndex = 0; - ElemType bestVol = 0.0; - - for (size_t i = 0; i < node->NumChildren(); i++) - { - ElemType v1 = 1.0; - ElemType v2 = 1.0; - for (size_t j = 0; j < node->Child(i).Bound().Dim(); j++) - { - v1 *= node->Child(i).Bound()[j].Width(); - v2 *= node->Child(i).Bound()[j].Contains(node->Dataset().col(point)[j]) ? - node->Child(i).Bound()[j].Width() : - (node->Child(i).Bound()[j].Hi() < node->Dataset().col(point)[j] ? - (node->Dataset().col(point)[j] - node->Child(i).Bound()[j].Lo()) : - (node->Child(i).Bound()[j].Hi() - node->Dataset().col(point)[j])); - } - - assert(v2 - v1 >= 0); - - if ((v2 - v1) < minScore) - { - minScore = v2 - v1; - bestVol = v1; - bestIndex = i; - } - else if ((v2 - v1) == minScore && v1 < bestVol) - { - bestVol = v1; - bestIndex = i; - } - } - - return bestIndex; -} - -template -inline size_t RTreeDescentHeuristic::ChooseDescentNode( - const TreeType* node, - const TreeType* insertedNode) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - ElemType minScore = std::numeric_limits::max(); - int bestIndex = 0; - ElemType bestVol = 0.0; - - for (size_t i = 0; i < node->NumChildren(); i++) - { - ElemType v1 = 1.0; - ElemType v2 = 1.0; - for (size_t j = 0; j < node->Child(i).Bound().Dim(); j++) - { - v1 *= node->Child(i).Bound()[j].Width(); - v2 *= node->Child(i).Bound()[j].Contains(insertedNode->Bound()[j]) ? - node->Child(i).Bound()[j].Width() : - (insertedNode->Bound()[j].Contains(node->Child(i).Bound()[j]) ? - insertedNode->Bound()[j].Width() : - (insertedNode->Bound()[j].Lo() < node->Child(i).Bound()[j].Lo() - ? (node->Child(i).Bound()[j].Hi() - - insertedNode->Bound()[j].Lo()) : (insertedNode->Bound()[j].Hi() - - node->Child(i).Bound()[j].Lo()))); - } - - assert(v2 - v1 >= 0); - - if ((v2 - v1) < minScore) - { - minScore = v2 - v1; - bestVol = v1; - bestIndex = i; - } - else if ((v2 - v1) == minScore && v1 < bestVol) - { - bestVol = v1; - bestIndex = i; - } - } - - return bestIndex; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_split.hpp deleted file mode 100644 index b140454e5..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_split.hpp +++ /dev/null @@ -1,89 +0,0 @@ -/** - * @file r_tree_split.hpp - * @author Andrew Wells - * - * Definition of the RTreeSplit class, a class that splits the nodes of an R - * tree, starting at a leaf node and moving upwards if necessary. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_SPLIT_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_SPLIT_HPP - -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * A Rectangle Tree has new points inserted at the bottom. When these - * nodes overflow, we split them, moving up the tree and splitting nodes - * as necessary. - */ -class RTreeSplit -{ - public: - /** - * Split a leaf node using the "default" algorithm. If necessary, this split - * will propagate upwards through the tree. - */ - template - static void SplitLeafNode(TreeType *tree, std::vector& relevels); - - /** - * Split a non-leaf node using the "default" algorithm. If this is a root - * node, the tree increases in depth. - */ - template - static bool SplitNonLeafNode(TreeType *tree, std::vector& relevels); - - private: - /** - * Get the seeds for splitting a leaf node. - */ - template - static void GetPointSeeds(const TreeType *tree, int& i, int& j); - - /** - * Get the seeds for splitting a non-leaf node. - */ - template - static void GetBoundSeeds(const TreeType *tree, int& i, int& j); - - /** - * Assign points to the two new nodes. - */ - template - static void AssignPointDestNode(TreeType* oldTree, - TreeType* treeOne, - TreeType* treeTwo, - const int intI, - const int intJ); - - /** - * Assign nodes to the two new nodes. - */ - template - static void AssignNodeDestNode(TreeType* oldTree, - TreeType* treeOne, - TreeType* treeTwo, - const int intI, - const int intJ); - - /** - * Insert a node into another node. - */ - template - static void InsertNodeIntoTree(TreeType* destTree, TreeType* srcNode); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation -#include "r_tree_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_split_impl.hpp deleted file mode 100644 index 02b1427c8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/r_tree_split_impl.hpp +++ /dev/null @@ -1,538 +0,0 @@ -/** - * @file r_tree_split_impl.hpp - * @author Andrew Wells - * - * Implementation of class (RTreeSplit) to split a RectangleTree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_SPLIT_IMPL_HPP - -#include "r_tree_split.hpp" -#include "rectangle_tree.hpp" -#include - -namespace mlpack { -namespace tree { - -/** - * We call GetPointSeeds to get the two points which will be the initial points - * in the new nodes We then call AssignPointDestNode to assign the remaining - * points to the two new nodes. Finally, we delete the old node and insert the - * new nodes into the tree, spliting the parent if necessary. - */ -template -void RTreeSplit::SplitLeafNode(TreeType *tree, std::vector& relevels) -{ - if (tree->Count() <= tree->MaxLeafSize()) - return; - // If we are splitting the root node, we need will do things differently so - // that the constructor and other methods don't confuse the end user by giving - // an address of another node. - if (tree->Parent() == NULL) - { - // We actually want to copy this way. Pointers and everything. - TreeType* copy = new TreeType(*tree, false); - copy->Parent() = tree; - tree->Count() = 0; - tree->NullifyData(); - // Because this was a leaf node, numChildren must be 0. - tree->children[(tree->NumChildren())++] = copy; - RTreeSplit::SplitLeafNode(copy, relevels); - return; - } - - assert(tree->Parent()->NumChildren() <= tree->Parent()->MaxNumChildren()); - - // Use the quadratic split method from: Guttman "R-Trees: A Dynamic Index - // Structure for Spatial Searching" It is simplified since we don't handle - // rectangles, only points. We assume that the tree uses Euclidean Distance. - int i = 0; - int j = 0; - RTreeSplit::GetPointSeeds(tree, i, j); - - TreeType* treeOne = new TreeType(tree->Parent()); - TreeType* treeTwo = new TreeType(tree->Parent()); - - // This will assign the ith and jth point appropriately. - AssignPointDestNode(tree, treeOne, treeTwo, i, j); - - // Remove this node and insert treeOne and treeTwo. - TreeType* par = tree->Parent(); - size_t index = 0; - while (par->children[index] != tree) { ++index; } - - par->children[index] = treeOne; - par->children[par->NumChildren()++] = treeTwo; - - // We only add one at a time, so we should only need to test for equality - // just in case, we use an assert. - assert(par->NumChildren() <= par->MaxNumChildren() + 1); - if (par->NumChildren() == par->MaxNumChildren() + 1) - RTreeSplit::SplitNonLeafNode(par, relevels); - - assert(treeOne->Parent()->NumChildren() <= treeOne->MaxNumChildren()); - assert(treeOne->Parent()->NumChildren() >= treeOne->MinNumChildren()); - assert(treeTwo->Parent()->NumChildren() <= treeTwo->MaxNumChildren()); - assert(treeTwo->Parent()->NumChildren() >= treeTwo->MinNumChildren()); - - // We need to delete this carefully since references to points are used. - tree->SoftDelete(); -} - -/** - * We call GetBoundSeeds to get the two new nodes that this one will be broken - * into. Then we call AssignNodeDestNode to move the children of this node into - * either of those two nodes. Finally, we delete the now unused information and - * recurse up the tree if necessary. We don't need to worry about the bounds - * higher up the tree because they were already updated if necessary. - */ -template -bool RTreeSplit::SplitNonLeafNode(TreeType *tree, std::vector& relevels) -{ - // If we are splitting the root node, we need will do things differently so - // that the constructor and other methods don't confuse the end user by giving - // an address of another node. - if (tree->Parent() == NULL) - { - // We actually want to copy this way. Pointers and everything. - TreeType* copy = new TreeType(*tree, false); - copy->Parent() = tree; - tree->NumChildren() = 0; - tree->NullifyData(); - tree->children[(tree->NumChildren())++] = copy; - RTreeSplit::SplitNonLeafNode(copy, relevels); - return true; - } - - int i = 0; - int j = 0; - RTreeSplit::GetBoundSeeds(tree, i, j); - - assert(i != j); - - TreeType* treeOne = new TreeType(tree->Parent()); - TreeType* treeTwo = new TreeType(tree->Parent()); - - // This will assign the ith and jth rectangles appropriately. - AssignNodeDestNode(tree, treeOne, treeTwo, i, j); - - // Remove this node and insert treeOne and treeTwo. - TreeType* par = tree->Parent(); - size_t index = 0; - while (par->children[index] != tree) { ++index; } - - assert(index != par->NumChildren()); - par->children[index] = treeOne; - par->children[par->NumChildren()++] = treeTwo; - - for (size_t i = 0; i < par->NumChildren(); i++) - assert(par->children[i] != tree); - - // We only add one at a time, so should only need to test for equality just in - // case, we use an assert. - assert(par->NumChildren() <= par->MaxNumChildren() + 1); - - if (par->NumChildren() == par->MaxNumChildren() + 1) - RTreeSplit::SplitNonLeafNode(par, relevels); - - // We have to update the children of each of these new nodes so that they - // record the correct parent. - for (size_t i = 0; i < treeOne->NumChildren(); i++) - treeOne->children[i]->Parent() = treeOne; - - for (size_t i = 0; i < treeTwo->NumChildren(); i++) - treeTwo->children[i]->Parent() = treeTwo; - - assert(treeOne->NumChildren() <= treeOne->MaxNumChildren()); - assert(treeTwo->NumChildren() <= treeTwo->MaxNumChildren()); - assert(treeOne->Parent()->NumChildren() <= treeOne->MaxNumChildren()); - - // Because we now have pointers to the information stored under this tree, - // we need to delete this node carefully. - tree->SoftDelete(); // currently does nothing but leak memory. - - return false; -} - -/** - * Get the two points that will be used as seeds for the split of a leaf node. - * The indices of these points will be stored in iRet and jRet. - */ -template -void RTreeSplit::GetPointSeeds(const TreeType *tree, int& iRet, int& jRet) -{ - // Here we want to find the pair of points that it is worst to place in the - // same node. Because we are just using points, we will simply choose the two - // that would create the most voluminous hyperrectangle. - typename TreeType::ElemType worstPairScore = -1.0; - for (size_t i = 0; i < tree->Count(); i++) - { - for (size_t j = i + 1; j < tree->Count(); j++) - { - const typename TreeType::ElemType score = arma::prod(arma::abs( - tree->Dataset().col(tree->Point(i)) - - tree->Dataset().col(tree->Point(j)))); - - if (score > worstPairScore) - { - worstPairScore = score; - iRet = i; - jRet = j; - } - } - } -} - -/** - * Get the two bounds that will be used as seeds for the split of the node. The - * indices of the bounds will be stored in iRet and jRet. - */ -template -void RTreeSplit::GetBoundSeeds(const TreeType *tree, int& iRet, int& jRet) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - ElemType worstPairScore = -1.0; - for (size_t i = 0; i < tree->NumChildren(); i++) - { - for (size_t j = i + 1; j < tree->NumChildren(); j++) - { - ElemType score = 1.0; - for (size_t k = 0; k < tree->Bound().Dim(); k++) - { - const ElemType hiMax = std::max(tree->Child(i).Bound()[k].Hi(), - tree->Child(j).Bound()[k].Hi()); - const ElemType loMin = std::min(tree->Child(i).Bound()[k].Lo(), - tree->Child(j).Bound()[k].Lo()); - score *= (hiMax - loMin); - } - - if (score > worstPairScore) - { - worstPairScore = score; - iRet = i; - jRet = j; - } - } - } -} - -template -void RTreeSplit::AssignPointDestNode(TreeType* oldTree, - TreeType* treeOne, - TreeType* treeTwo, - const int intI, - const int intJ) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - size_t end = oldTree->Count(); - - assert(end > 1); // If this isn't true, the tree is really weird. - - // Restart the point counts since we are going to move them. - oldTree->Count() = 0; - treeOne->Count() = 0; - treeTwo->Count() = 0; - - treeOne->InsertPoint(oldTree->Point(intI)); - treeTwo->InsertPoint(oldTree->Point(intJ)); - - // If intJ is the last point in the tree, we need to switch the order so that - // we remove the correct points. - if (intI > intJ) - { - oldTree->Point(intI) = oldTree->Point(--end); // Decrement end. - oldTree->Point(intJ) = oldTree->Point(--end); // Decrement end. - } - else - { - oldTree->Point(intJ) = oldTree->Point(--end); // Decrement end. - oldTree->Point(intI) = oldTree->Point(--end); // Decrement end. - } - - size_t numAssignedOne = 1; - size_t numAssignedTwo = 1; - - // In each iteration, we go through all points and find the one that causes - // the least increase of volume when added to one of the rectangles. We then - // add it to that rectangle. We stop when we run out of points or when all of - // the remaining points need to be assigned to the same rectangle to satisfy - // the minimum fill requirement. - - // The below is safe because if end decreases and the right hand side of the - // second part of the conjunction changes on the same iteration, we added the - // point to the node with fewer points anyways. - while ((end > 0) && (end > oldTree->MinLeafSize() - - std::min(numAssignedOne, numAssignedTwo))) - { - int bestIndex = 0; - ElemType bestScore = std::numeric_limits::max(); - int bestRect = 1; - - // Calculate the increase in volume for assigning this point to each - // rectangle. - - // First, calculate the starting volume. - ElemType volOne = 1.0; - ElemType volTwo = 1.0; - for (size_t i = 0; i < oldTree->Bound().Dim(); i++) - { - volOne *= treeOne->Bound()[i].Width(); - volTwo *= treeTwo->Bound()[i].Width(); - } - - // Find the point that, when assigned to one of the two new rectangles, - // minimizes the increase in volume. - for (size_t index = 0; index < end; index++) - { - ElemType newVolOne = 1.0; - ElemType newVolTwo = 1.0; - for (size_t i = 0; i < oldTree->Bound().Dim(); i++) - { - ElemType c = oldTree->Dataset().col(oldTree->Point(index))[i]; - newVolOne *= treeOne->Bound()[i].Contains(c) ? - treeOne->Bound()[i].Width() : (c < treeOne->Bound()[i].Lo() ? - (treeOne->Bound()[i].Hi() - c) : (c - treeOne->Bound()[i].Lo())); - newVolTwo *= treeTwo->Bound()[i].Contains(c) ? - treeTwo->Bound()[i].Width() : (c < treeTwo->Bound()[i].Lo() ? - (treeTwo->Bound()[i].Hi() - c) : (c - treeTwo->Bound()[i].Lo())); - } - - // Choose the rectangle that requires the lesser increase in volume. - if ((newVolOne - volOne) < (newVolTwo - volTwo)) - { - if (newVolOne - volOne < bestScore) - { - bestScore = newVolOne - volOne; - bestIndex = index; - bestRect = 1; - } - } - else - { - if (newVolTwo - volTwo < bestScore) - { - bestScore = newVolTwo - volTwo; - bestIndex = index; - bestRect = 2; - } - } - } - - // Assign the point that causes the least increase in volume - // to the appropriate rectangle. - if (bestRect == 1) - { - treeOne->InsertPoint(oldTree->Point(bestIndex)); - numAssignedOne++; - } - else - { - treeTwo->InsertPoint(oldTree->Point(bestIndex)); - numAssignedTwo++; - } - - oldTree->Point(bestIndex) = oldTree->Point(--end); // Decrement end. - } - - // See if we need to satisfy the minimum fill. - if (end > 0) - { - if (numAssignedOne < numAssignedTwo) - { - for (size_t i = 0; i < end; i++) - treeOne->InsertPoint(oldTree->Point(i)); - } - else - { - for (size_t i = 0; i < end; i++) - treeTwo->InsertPoint(oldTree->Point(i)); - } - } -} - -template -void RTreeSplit::AssignNodeDestNode(TreeType* oldTree, - TreeType* treeOne, - TreeType* treeTwo, - const int intI, - const int intJ) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - size_t end = oldTree->NumChildren(); - assert(end > 1); // If this isn't true, the tree is really weird. - - assert(intI != intJ); - - for (size_t i = 0; i < oldTree->NumChildren(); i++) - for (size_t j = i + 1; j < oldTree->NumChildren(); j++) - assert(oldTree->children[i] != oldTree->children[j]); - - InsertNodeIntoTree(treeOne, oldTree->children[intI]); - InsertNodeIntoTree(treeTwo, oldTree->children[intJ]); - - // If intJ is the last node in the tree, we need to switch the order so that - // we remove the correct nodes. - if (intI > intJ) - { - oldTree->children[intI] = oldTree->children[--end]; - oldTree->children[intJ] = oldTree->children[--end]; - } - else - { - oldTree->children[intJ] = oldTree->children[--end]; - oldTree->children[intI] = oldTree->children[--end]; - } - - assert(treeOne->NumChildren() == 1); - assert(treeTwo->NumChildren() == 1); - - for (size_t i = 0; i < end; i++) - for (size_t j = i + 1; j < end; j++) - assert(oldTree->children[i] != oldTree->children[j]); - - for (size_t i = 0; i < end; i++) - assert(oldTree->children[i] != treeOne->children[0]); - - for (size_t i = 0; i < end; i++) - assert(oldTree->children[i] != treeTwo->children[0]); - - size_t numAssignTreeOne = 1; - size_t numAssignTreeTwo = 1; - - // In each iteration, we go through all of the nodes and find the one that - // causes the least increase of volume when added to one of the two new - // rectangles. We then add it to that rectangle. - while ((end > 0) && (end > oldTree->MinNumChildren() - - std::min(numAssignTreeOne, numAssignTreeTwo))) - { - int bestIndex = 0; - ElemType bestScore = std::numeric_limits::max(); - int bestRect = 0; - - // Calculate the increase in volume for assigning this node to each of the - // new rectangles. - ElemType volOne = 1.0; - ElemType volTwo = 1.0; - for (size_t i = 0; i < oldTree->Bound().Dim(); i++) - { - volOne *= treeOne->Bound()[i].Width(); - volTwo *= treeTwo->Bound()[i].Width(); - } - - for (size_t index = 0; index < end; index++) - { - ElemType newVolOne = 1.0; - ElemType newVolTwo = 1.0; - for (size_t i = 0; i < oldTree->Bound().Dim(); i++) - { - // For each of the new rectangles, find the width in this dimension if - // we add the rectangle at index to the new rectangle. - const math::RangeType& range = - oldTree->Child(index).Bound()[i]; - newVolOne *= treeOne->Bound()[i].Contains(range) ? - treeOne->Bound()[i].Width() : (range.Contains(treeOne->Bound()[i]) ? - range.Width() : (range.Lo() < treeOne->Bound()[i].Lo() ? - (treeOne->Bound()[i].Hi() - range.Lo()) : (range.Hi() - - treeOne->Bound()[i].Lo()))); - - newVolTwo *= treeTwo->Bound()[i].Contains(range) ? - treeTwo->Bound()[i].Width() : (range.Contains(treeTwo->Bound()[i]) ? - range.Width() : (range.Lo() < treeTwo->Bound()[i].Lo() ? - (treeTwo->Bound()[i].Hi() - range.Lo()) : (range.Hi() - - treeTwo->Bound()[i].Lo()))); - } - - // Choose the rectangle that requires the lesser increase in volume. - if ((newVolOne - volOne) < (newVolTwo - volTwo)) - { - if (newVolOne - volOne < bestScore) - { - bestScore = newVolOne - volOne; - bestIndex = index; - bestRect = 1; - } - } - else - { - if (newVolTwo - volTwo < bestScore) - { - bestScore = newVolTwo - volTwo; - bestIndex = index; - bestRect = 2; - } - } - } - - // Assign the rectangle that causes the least increase in volume - // to the appropriate rectangle. - if (bestRect == 1) - { - InsertNodeIntoTree(treeOne, oldTree->children[bestIndex]); - numAssignTreeOne++; - } - else - { - InsertNodeIntoTree(treeTwo, oldTree->children[bestIndex]); - numAssignTreeTwo++; - } - - oldTree->children[bestIndex] = oldTree->children[--end]; - } - - // See if we need to satisfy the minimum fill. - if (end > 0) - { - if (numAssignTreeOne < numAssignTreeTwo) - { - for (size_t i = 0; i < end; i++) - { - InsertNodeIntoTree(treeOne, oldTree->children[i]); - numAssignTreeOne++; - } - } - else - { - for (size_t i = 0; i < end; i++) - { - InsertNodeIntoTree(treeTwo, oldTree->children[i]); - numAssignTreeTwo++; - } - } - } - - for (size_t i = 0; i < treeOne->NumChildren(); i++) - for (size_t j = i + 1; j < treeOne->NumChildren(); j++) - assert(treeOne->children[i] != treeOne->children[j]); - - for (size_t i = 0; i < treeTwo->NumChildren(); i++) - for (size_t j = i + 1; j < treeTwo->NumChildren(); j++) - assert(treeTwo->children[i] != treeTwo->children[j]); -} - -/** - * Insert a node into another node. Expanding the bounds and updating the - * numberOfChildren. - */ -template -void RTreeSplit::InsertNodeIntoTree(TreeType* destTree, TreeType* srcNode) -{ - destTree->Bound() |= srcNode->Bound(); - destTree->numDescendants += srcNode->numDescendants; - destTree->children[destTree->NumChildren()++] = srcNode; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/rectangle_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/rectangle_tree.hpp deleted file mode 100644 index a3093df17..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/rectangle_tree.hpp +++ /dev/null @@ -1,618 +0,0 @@ -/** - * @file rectangle_tree.hpp - * @author Andrew Wells - * - * Definition of generalized rectangle type trees (r_tree, r_star_tree, x_tree, - * and hilbert_r_tree). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_RECTANGLE_TREE_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_RECTANGLE_TREE_HPP - -#include - -#include "../hrectbound.hpp" -#include "../statistic.hpp" -#include "r_tree_split.hpp" -#include "r_tree_descent_heuristic.hpp" -#include "no_auxiliary_information.hpp" - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * A rectangle type tree tree, such as an R-tree or X-tree. Once the - * bound and type of dataset is defined, the tree will construct itself. Call - * the constructor with the dataset to build the tree on, and the entire tree - * will be built. - * - * This tree does allow growth, so you can add and delete nodes from it. - * - * @tparam MetricType This *must* be EuclideanDistance, but the template - * parameter is required to satisfy the TreeType API. - * @tparam StatisticType Extra data contained in the node. See statistic.hpp - * for the necessary skeleton interface. - * @tparam MatType The dataset class. - * @tparam SplitType The type of split to use when inserting points. - * @tparam DescentType The heuristic to use when descending the tree to insert - * points. - * @tparam AuxiliaryInformationType An auxiliary information contained - * in the node. This information depends on the type of the RectangleTree. - */ - -template class AuxiliaryInformationType = - NoAuxiliaryInformation> -class RectangleTree -{ - // The metric *must* be the euclidean distance. - static_assert(boost::is_same::value, - "RectangleTree: MetricType must be metric::EuclideanDistance."); - - public: - //! So other classes can use TreeType::Mat. - typedef MatType Mat; - //! The element type held by the matrix type. - typedef typename MatType::elem_type ElemType; - //! The auxiliary information type held by the tree. - typedef AuxiliaryInformationType AuxiliaryInformation; - private: - //! The max number of child nodes a non-leaf node can have. - size_t maxNumChildren; - //! The minimum number of child nodes a non-leaf node can have. - size_t minNumChildren; - //! The number of child nodes actually in use (0 if this is a leaf node). - size_t numChildren; - //! The child nodes (Starting at 0 and ending at (numChildren-1) ). - std::vector children; - //! The parent node (NULL if this is the root of the tree). - RectangleTree* parent; - //! The index of the first point in the dataset contained in this node (and - //! its children). THIS IS ALWAYS 0 AT THE MOMENT. IT EXISTS MERELY IN CASE - //! I THINK OF A WAY TO CHANGE THAT. IN OTHER WORDS, IT WILL PROBABLY BE - //! REMOVED. - size_t begin; - //! The number of points in the dataset contained in this node (and its - //! children). - size_t count; - //! The number of descendants of this node. - size_t numDescendants; - //! The max leaf size. - size_t maxLeafSize; - //! The minimum leaf size. - size_t minLeafSize; - //! The bound object for this node. - bound::HRectBound bound; - //! Any extra data contained in the node. - StatisticType stat; - //! The distance from the centroid of this node to the centroid of the parent. - ElemType parentDistance; - //! The dataset. - const MatType* dataset; - //! Whether or not we are responsible for deleting the dataset. This is - //! probably not aligned well... - bool ownsDataset; - //! The mapping to the dataset - std::vector points; - //! A tree-specific information - AuxiliaryInformationType auxiliaryInfo; - - public: - //! A single traverser for rectangle type trees. See - //! single_tree_traverser.hpp for implementation. - template - class SingleTreeTraverser; - //! A dual tree traverser for rectangle type trees. - template - class DualTreeTraverser; - - /** - * Construct this as the root node of a rectangle type tree using the given - * dataset. This will modify the ordering of the points in the dataset! - * - * @param data Dataset from which to create the tree. This will be modified! - * @param maxLeafSize Maximum size of each leaf in the tree. - * @param minLeafSize Minimum size of each leaf in the tree. - * @param maxNumChildren The maximum number of child nodes a non-leaf node may - * have. - * @param minNumChildren The minimum number of child nodes a non-leaf node may - * have. - * @param firstDataIndex The index of the first data point. UNUSED UNLESS WE - * ADD SUPPORT FOR HAVING A "CENTERAL" DATA MATRIX. - */ - RectangleTree(const MatType& data, - const size_t maxLeafSize = 20, - const size_t minLeafSize = 8, - const size_t maxNumChildren = 5, - const size_t minNumChildren = 2, - const size_t firstDataIndex = 0); - - /** - * Construct this as the root node of a rectangle tree type using the given - * dataset, and taking ownership of the given dataset. - * - * @param data Dataset from which to create the tree. - * @param maxLeafSize Maximum size of each leaf in the tree. - * @param minLeafSize Minimum size of each leaf in the tree. - * @param maxNumChildren The maximum number of child nodes a non-leaf node may - * have. - * @param minNumChildren The minimum number of child nodes a non-leaf node may - * have. - * @param firstDataIndex The index of the first data point. UNUSED UNLESS WE - * ADD SUPPORT FOR HAVING A "CENTERAL" DATA MATRIX. - */ - RectangleTree(MatType&& data, - const size_t maxLeafSize = 20, - const size_t minLeafSize = 8, - const size_t maxNumChildren = 5, - const size_t minNumChildren = 2, - const size_t firstDataIndex = 0); - - /** - * Construct this as an empty node with the specified parent. Copying the - * parameters (maxLeafSize, minLeafSize, maxNumChildren, minNumChildren, - * firstDataIndex) from the parent. - * - * @param parentNode The parent of the node that is being constructed. - * @param numMaxChildren The max number of child nodes (used in x-trees). - */ - explicit RectangleTree(RectangleTree* parentNode, - const size_t numMaxChildren = 0); - - /** - * Create a rectangle tree by copying the other tree. Be careful! This can - * take a long time and use a lot of memory. - * - * @param other The tree to be copied. - * @param deepCopy If false, the children are not recursively copied. - */ - RectangleTree(const RectangleTree& other, - const bool deepCopy = true, - RectangleTree* newParent = NULL); - - /** - * Create a rectangle tree by moving the other tree. - * - * @param other The tree to be copied. - */ - RectangleTree(RectangleTree&& other); - - /** - * Construct the tree from a boost::serialization archive. - */ - template - RectangleTree( - Archive& ar, - const typename std::enable_if_t* = 0); - - /** - * Deletes this node, deallocating the memory for the children and calling - * their destructors in turn. This will invalidate any younters or references - * to any nodes which are children of this one. - */ - ~RectangleTree(); - - /** - * Delete this node of the tree, but leave the stuff contained in it intact. - * This is used when splitting a node, where the data in this tree is moved to - * two other trees. - */ - void SoftDelete(); - - /** - * Nullify the auxiliary information. Used for memory management. - * Be cafeful. - */ - void NullifyData(); - - /** - * Inserts a point into the tree. - * - * @param point The index of a point in the dataset. - */ - void InsertPoint(const size_t point); - - /** - * Inserts a point into the tree, tracking which levels have been inserted - * into. - * - * @param point The index of a point in the dataset. - * @param relevels The levels that have been reinserted to on this top level - * insertion. - */ - void InsertPoint(const size_t point, std::vector& relevels); - - /** - * Inserts a node into the tree, tracking which levels have been inserted - * into. The node will be inserted so that the tree remains valid. - * - * @param node The node to be inserted. - * @param level The depth that should match the node where this node is - * finally inserted. This should be the number returned by calling - * TreeDepth() from the node that originally contained "node". - * @param relevels The levels that have been reinserted to on this top level - * insertion. - */ - void InsertNode(RectangleTree* node, - const size_t level, - std::vector& relevels); - - /** - * Deletes a point from the treeand, updates the bounding rectangle. - * However, the point will be kept in the centeral dataset. (The - * user may remove it from there if he wants, but he must not change the - * indices of the other points.) Returns true if the point is successfully - * removed and false if it is not. (ie. the point is not in the tree) - */ - bool DeletePoint(const size_t point); - - /** - * Deletes a point from the tree, updates the bounding rectangle, - * tracking levels. However, the point will be kept in the centeral dataset. - * (The user may remove it from there if he wants, but he - * must not change the indices of the other points.) Returns true if the point - * is successfully removed and false if it is not. (ie. the point is not in - * the tree) - */ - bool DeletePoint(const size_t point, std::vector& relevels); - - /** - * Removes a node from the tree. You are responsible for deleting it if you - * wish to do so. - */ - bool RemoveNode(const RectangleTree* node, std::vector& relevels); - - /** - * Find a node in this tree by its begin and count (const). - * - * Every node is uniquely identified by these two numbers. - * This is useful for communicating position over the network, - * when pointers would be invalid. - * - * @param begin The begin() of the node to find. - * @param count The count() of the node to find. - * @return The found node, or NULL if not found. - */ - const RectangleTree* FindByBeginCount(size_t begin, size_t count) const; - - /** - * Find a node in this tree by its begin and count. - * - * Every node is uniquely identified by these two numbers. - * This is useful for communicating position over the network, - * when pointers would be invalid. - * - * @param begin The begin() of the node to find. - * @param count The count() of the node to find. - * @return The found node, or NULL if not found. - */ - RectangleTree* FindByBeginCount(size_t begin, size_t count); - - //! Return the bound object for this node. - const bound::HRectBound& Bound() const { return bound; } - //! Modify the bound object for this node. - bound::HRectBound& Bound() { return bound; } - - //! Return the statistic object for this node. - const StatisticType& Stat() const { return stat; } - //! Modify the statistic object for this node. - StatisticType& Stat() { return stat; } - - //! Return the auxiliary information object of this node. - const AuxiliaryInformationType &AuxiliaryInfo() const - { return auxiliaryInfo; } - //! Modify the split object of this node. - AuxiliaryInformationType& AuxiliaryInfo() - { return auxiliaryInfo; } - - //! Return whether or not this node is a leaf (true if it has no children). - bool IsLeaf() const; - - //! Return the maximum leaf size. - size_t MaxLeafSize() const { return maxLeafSize; } - //! Modify the maximum leaf size. - size_t& MaxLeafSize() { return maxLeafSize; } - - //! Return the minimum leaf size. - size_t MinLeafSize() const { return minLeafSize; } - //! Modify the minimum leaf size. - size_t& MinLeafSize() { return minLeafSize; } - - //! Return the maximum number of children (in a non-leaf node). - size_t MaxNumChildren() const { return maxNumChildren; } - //! Modify the maximum number of children (in a non-leaf node). - size_t& MaxNumChildren() { return maxNumChildren; } - - //! Return the minimum number of children (in a non-leaf node). - size_t MinNumChildren() const { return minNumChildren; } - //! Modify the minimum number of children (in a non-leaf node). - size_t& MinNumChildren() { return minNumChildren; } - - //! Gets the parent of this node. - RectangleTree* Parent() const { return parent; } - //! Modify the parent of this node. - RectangleTree*& Parent() { return parent; } - - //! Get the dataset which the tree is built on. - const MatType& Dataset() const { return *dataset; } - //! Modify the dataset which the tree is built on. Be careful! - MatType& Dataset() { return const_cast(*dataset); } - - //! Get the metric which the tree uses. - MetricType Metric() const { return MetricType(); } - - //! Get the centroid of the node and store it in the given vector. - void Center(arma::vec& center) { bound.Center(center); } - - //! Return the number of child nodes. (One level beneath this one only.) - size_t NumChildren() const { return numChildren; } - //! Modify the number of child nodes. Be careful. - size_t& NumChildren() { return numChildren; } - - /** - * Return the index of the nearest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ - template - size_t GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0); - - /** - * Return the index of the furthest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ - template - size_t GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0); - - /** - * Return the index of the nearest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ - size_t GetNearestChild(const RectangleTree& queryNode); - - /** - * Return the index of the furthest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ - size_t GetFurthestChild(const RectangleTree& queryNode); - - /** - * Return the furthest distance to a point held in this node. If this is not - * a leaf node, then the distance is 0 because the node holds no points. - */ - ElemType FurthestPointDistance() const; - - /** - * Return the furthest possible descendant distance. This returns the maximum - * distance from the centroid to the edge of the bound and not the empirical - * quantity which is the actual furthest descendant distance. So the actual - * furthest descendant distance may be less than what this method returns (but - * it will never be greater than this). - */ - ElemType FurthestDescendantDistance() const; - - //! Return the minimum distance from the center to any edge of the bound. - //! Currently, this returns 0, which doesn't break algorithms, but it isn't - //! necessarily correct, either. - ElemType MinimumBoundDistance() const { return bound.MinWidth() / 2.0; } - - //! Return the distance from the center of this node to the center of the - //! parent node. - ElemType ParentDistance() const { return parentDistance; } - //! Modify the distance from the center of this node to the center of the - //! parent node. - ElemType& ParentDistance() { return parentDistance; } - - /** - * Get the specified child. - * - * @param child Index of child to return. - */ - inline RectangleTree& Child(const size_t child) const - { - return *children[child]; - } - - /** - * Modify the specified child. - * - * @param child Index of child to return. - */ - inline RectangleTree& Child(const size_t child) - { - return *children[child]; - } - - //! Return the number of points in this node (returns 0 if this node is not a - //! leaf). - size_t NumPoints() const; - - /** - * Return the number of descendants of this node. For a non-leaf in a binary - * space tree, this is the number of points at the descendant leaves. For a - * leaf, this is the number of points in the leaf. - */ - size_t NumDescendants() const; - - /** - * Return the index (with reference to the dataset) of a particular descendant - * of this node. The index should be greater than zero but less than the - * number of descendants. - * - * @param index Index of the descendant. - */ - size_t Descendant(const size_t index) const; - - /** - * Return the index (with reference to the dataset) of a particular point in - * this node. This will happily return invalid indices if the given index is - * greater than the number of points in this node (obtained with NumPoints()) - * -- be careful. - * - * @param index Index of point for which a dataset index is wanted. - */ - size_t Point(const size_t index) const { return points[index]; } - - //! Modify the index of a particular point in this node. Be very careful when - //! you do this! You may make the tree invalid. - size_t& Point(const size_t index) { return points[index]; } - - //! Return the minimum distance to another node. - ElemType MinDistance(const RectangleTree& other) const - { - return bound.MinDistance(other.Bound()); - } - - //! Return the maximum distance to another node. - ElemType MaxDistance(const RectangleTree& other) const - { - return bound.MaxDistance(other.Bound()); - } - - //! Return the minimum and maximum distance to another node. - math::RangeType RangeDistance(const RectangleTree& other) const - { - return bound.RangeDistance(other.Bound()); - } - - //! Return the minimum distance to another point. - template - ElemType MinDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const - { - return bound.MinDistance(point); - } - - //! Return the maximum distance to another point. - template - ElemType MaxDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const - { - return bound.MaxDistance(point); - } - - //! Return the minimum and maximum distance to another point. - template - math::RangeType RangeDistance( - const VecType& point, - typename std::enable_if_t::value>* = 0) const - { - return bound.RangeDistance(point); - } - - /** - * Obtains the number of nodes in the tree, starting with this. - */ - size_t TreeSize() const; - - /** - * Obtains the number of levels below this node in the tree, starting with - * this. - */ - size_t TreeDepth() const; - - //! Return the index of the beginning point of this subset. - size_t Begin() const { return begin; } - //! Modify the index of the beginning point of this subset. - size_t& Begin() { return begin; } - - //! Return the number of points in this subset. - size_t Count() const { return count; } - //! Modify the number of points in this subset. - size_t& Count() { return count; } - - private: - /** - * Splits the current node, recursing up the tree. - * - * @param relevels Vector to track which levels have been inserted to. - */ - void SplitNode(std::vector& relevels); - - protected: - /** - * A default constructor. This is meant to only be used with - * boost::serialization, which is allowed with the friend declaration below. - * This does not return a valid tree! This method must be protected, so that - * the serialization shim can work with the default constructor. - */ - RectangleTree(); - - //! Friend access is given for the default constructor. - friend class boost::serialization::access; - - //! Give friend access for DescentType. - friend DescentType; - - //! Give friend access for SplitType. - friend SplitType; - - //! Give friend access for AuxiliaryInformationType. - friend AuxiliaryInformation; - - public: - /** - * Condense the bounding rectangles for this node based on the removal of the - * point specified by the arma::vec&. This recurses up the tree. If a node - * goes below the minimum fill, this function will fix the tree. - * - * @param point The arma::vec& of the point that was removed to require this - * condesation of the tree. - * @param usePoint True if we use the optimized version of the algorithm that - * is possible when we now what point was deleted. False otherwise (eg. - * if we deleted a node instead of a point). - */ - void CondenseTree(const arma::vec& point, - std::vector& relevels, - const bool usePoint); - - /** - * Shrink the bound object of this node for the removal of a point. - * - * @param point The arma::vec& of the point that was removed to require this - * shrinking. - * @return true if the bound needed to be changed, false if it did not. - */ - bool ShrinkBoundForPoint(const arma::vec& point); - - /** - * Shrink the bound object of this node for the removal of a child node. - * - * @param bound The HRectBound<>& of the bound that was removed to reqire this - * shrinking. - * @return true if the bound needed to be changed, false if it did not. - */ - bool ShrinkBoundForBound(const bound::HRectBound& changedBound); - - /** - * Make an exact copy of this node, pointers and everything. - */ - RectangleTree* ExactClone(); - - /** - * Serialize the tree. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "rectangle_tree_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/rectangle_tree_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/rectangle_tree_impl.hpp deleted file mode 100644 index 59a20e26f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/rectangle_tree_impl.hpp +++ /dev/null @@ -1,1309 +0,0 @@ -/** - * @file rectangle_tree_impl.hpp - * @author Andrew Wells - * - * Implementation of generalized rectangle tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_RECTANGLE_TREE_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_RECTANGLE_TREE_IMPL_HPP - -// In case it wasn't included already for some reason. -#include "rectangle_tree.hpp" - -#include -#include - -namespace mlpack { -namespace tree { - -template class AuxiliaryInformationType> -RectangleTree:: -RectangleTree(const MatType& data, - const size_t maxLeafSize, - const size_t minLeafSize, - const size_t maxNumChildren, - const size_t minNumChildren, - const size_t firstDataIndex) : - maxNumChildren(maxNumChildren), - minNumChildren(minNumChildren), - numChildren(0), - children(maxNumChildren + 1), // Add one to make splitting the node simpler. - parent(NULL), - begin(0), - count(0), - numDescendants(0), - maxLeafSize(maxLeafSize), - minLeafSize(minLeafSize), - bound(data.n_rows), - parentDistance(0), - dataset(new MatType(data)), - ownsDataset(true), - points(maxLeafSize + 1), // Add one to make splitting the node simpler. - auxiliaryInfo(this) -{ - stat = StatisticType(*this); - - // For now, just insert the points in order. - RectangleTree* root = this; - - for (size_t i = firstDataIndex; i < data.n_cols; i++) - root->InsertPoint(i); -} - -template class AuxiliaryInformationType> -RectangleTree:: -RectangleTree(MatType&& data, - const size_t maxLeafSize, - const size_t minLeafSize, - const size_t maxNumChildren, - const size_t minNumChildren, - const size_t firstDataIndex) : - maxNumChildren(maxNumChildren), - minNumChildren(minNumChildren), - numChildren(0), - children(maxNumChildren + 1), // Add one to make splitting the node simpler. - parent(NULL), - begin(0), - count(0), - numDescendants(0), - maxLeafSize(maxLeafSize), - minLeafSize(minLeafSize), - bound(data.n_rows), - parentDistance(0), - dataset(new MatType(std::move(data))), - ownsDataset(true), - points(maxLeafSize + 1), // Add one to make splitting the node simpler. - auxiliaryInfo(this) -{ - stat = StatisticType(*this); - - // For now, just insert the points in order. - RectangleTree* root = this; - - for (size_t i = firstDataIndex; i < dataset->n_cols; i++) - root->InsertPoint(i); -} - -template class AuxiliaryInformationType> -RectangleTree:: -RectangleTree( - RectangleTree* - parentNode, const size_t numMaxChildren) : - maxNumChildren(numMaxChildren > 0 ? numMaxChildren : - parentNode->MaxNumChildren()), - minNumChildren(parentNode->MinNumChildren()), - numChildren(0), - children(maxNumChildren + 1), - parent(parentNode), - begin(0), - count(0), - numDescendants(0), - maxLeafSize(parentNode->MaxLeafSize()), - minLeafSize(parentNode->MinLeafSize()), - bound(parentNode->Bound().Dim()), - parentDistance(0), - dataset(&parentNode->Dataset()), - ownsDataset(false), - points(maxLeafSize + 1), // Add one to make splitting the node simpler. - auxiliaryInfo(this) -{ - stat = StatisticType(*this); -} - -/** - * Create a rectangle tree by copying the other tree. Be careful! This can - * take a long time and use a lot of memory. - */ -template class AuxiliaryInformationType> -RectangleTree:: -RectangleTree( - const RectangleTree& other, - const bool deepCopy, - RectangleTree* newParent) : - maxNumChildren(other.MaxNumChildren()), - minNumChildren(other.MinNumChildren()), - numChildren(other.NumChildren()), - children(maxNumChildren + 1, NULL), - parent(deepCopy ? newParent : other.Parent()), - begin(other.Begin()), - count(other.Count()), - numDescendants(other.numDescendants), - maxLeafSize(other.MaxLeafSize()), - minLeafSize(other.MinLeafSize()), - bound(other.bound), - parentDistance(other.ParentDistance()), - dataset(deepCopy ? - (parent ? parent->dataset : new MatType(*other.dataset)) : - &other.Dataset()), - ownsDataset(deepCopy && (!parent)), - points(other.points), - auxiliaryInfo(other.auxiliaryInfo, this, deepCopy) -{ - if (deepCopy) - { - if (numChildren > 0) - { - for (size_t i = 0; i < numChildren; i++) - children[i] = new RectangleTree(other.Child(i), true, this); - } - } - else - children = other.children; -} - -template class AuxiliaryInformationType> -RectangleTree:: -RectangleTree(RectangleTree&& other) : - maxNumChildren(other.MaxNumChildren()), - minNumChildren(other.MinNumChildren()), - numChildren(other.NumChildren()), - children(std::move(other.children)), - parent(other.Parent()), - begin(other.Begin()), - count(other.Count()), - numDescendants(other.numDescendants), - maxLeafSize(other.MaxLeafSize()), - minLeafSize(other.MinLeafSize()), - bound(std::move(other.bound)), - parentDistance(other.ParentDistance()), - dataset(other.dataset), - ownsDataset(other.ownsDataset), - points(std::move(other.points)), - auxiliaryInfo(std::move(other.auxiliaryInfo)) -{ - if (parent) - { - size_t iChild = 0; - while (parent->children[iChild] != (&other)) - iChild++; - assert(iChild < numChildren); - parent->children[iChild] = this; - } - if (!IsLeaf()) - { - for (size_t i = 0; i < numChildren; i++) - children[i]->parent = this; - } - other.maxNumChildren = 0; - other.minNumChildren = 0; - other.numChildren = 0; - other.parent = NULL; - other.begin = 0; - other.count = 0; - other.numDescendants = 0; - other.maxLeafSize = 0; - other.minLeafSize = 0; - other.parentDistance = 0; - other.dataset = NULL; - other.ownsDataset = false; -} - -/** - * Construct the tree from a boost::serialization archive. - */ -template class AuxiliaryInformationType> -template -RectangleTree:: -RectangleTree( - Archive& ar, - const typename std::enable_if_t*) : - RectangleTree() // Use default constructor. -{ - // Now serialize. - ar >> BOOST_SERIALIZATION_NVP(*this); -} - -/** - * Deletes this node, deallocating the memory for the children and calling - * their destructors in turn. This will invalidate any pointers or references - * to any nodes which are children of this one. - */ -template class AuxiliaryInformationType> -RectangleTree:: -~RectangleTree() -{ - for (size_t i = 0; i < numChildren; i++) - delete children[i]; - - if (ownsDataset) - delete dataset; -} - -/** - * Deletes this node but leaves the children untouched. Needed for when we - * split nodes and remove nodes (inserting and deleting points). - */ -template class AuxiliaryInformationType> -void RectangleTree:: - SoftDelete() -{ - parent = NULL; - - for (size_t i = 0; i < children.size(); i++) - children[i] = NULL; - - numChildren = 0; - delete this; -} - -/** - * Nullify the auxiliary information. - */ -template class AuxiliaryInformationType> -void RectangleTree:: - NullifyData() -{ - auxiliaryInfo.NullifyData(); -} - -/** - * Recurse through the tree and insert the point at the leaf node chosen - * by the heuristic. - */ -template class AuxiliaryInformationType> -void RectangleTree:: - InsertPoint(const size_t point) -{ - // Expand the bound regardless of whether it is a leaf node. - bound |= dataset->col(point); - - numDescendants++; - - std::vector lvls(TreeDepth(), true); - - // If this is a leaf node, we stop here and add the point. - if (numChildren == 0) - { - if (!auxiliaryInfo.HandlePointInsertion(this, point)) - points[count++] = point; - - SplitNode(lvls); - return; - } - - // If it is not a leaf node, we use the DescentHeuristic to choose a child - // to which we recurse. - auxiliaryInfo.HandlePointInsertion(this, point); - const size_t descentNode = DescentType::ChooseDescentNode(this, point); - children[descentNode]->InsertPoint(point, lvls); -} - -/** - * Inserts a point into the tree, tracking which levels have been inserted into. - */ -template class AuxiliaryInformationType> -void RectangleTree:: - InsertPoint(const size_t point, std::vector& relevels) -{ - // Expand the bound regardless of whether it is a leaf node. - bound |= dataset->col(point); - - numDescendants++; - - // If this is a leaf node, we stop here and add the point. - if (numChildren == 0) - { - if (!auxiliaryInfo.HandlePointInsertion(this, point)) - points[count++] = point; - - SplitNode(relevels); - return; - } - - // If it is not a leaf node, we use the DescentHeuristic to choose a child - // to which we recurse. - auxiliaryInfo.HandlePointInsertion(this, point); - const size_t descentNode = DescentType::ChooseDescentNode(this, point); - children[descentNode]->InsertPoint(point, relevels); -} - -/** - * Inserts a node into the tree, tracking which levels have been inserted into. - * - * @param node The node to be inserted. - * @param level The level on which this node should be inserted. - * @param relevels The levels that have been reinserted to on this top level - * insertion. - */ -template class AuxiliaryInformationType> -void RectangleTree:: - InsertNode(RectangleTree* node, - const size_t level, - std::vector& relevels) -{ - // Expand the bound regardless of the level. - bound |= node->Bound(); - numDescendants += node->numDescendants; - if (level == TreeDepth()) - { - if (!auxiliaryInfo.HandleNodeInsertion(this, node, true)) - { - children[numChildren++] = node; - node->Parent() = this; - } - SplitNode(relevels); - } - else - { - auxiliaryInfo.HandleNodeInsertion(this, node, false); - const size_t descentNode = DescentType::ChooseDescentNode(this, node); - children[descentNode]->InsertNode(node, level, relevels); - } -} - -/** - * Recurse through the tree to remove the point. Once we find the point, we - * shrink the rectangles if necessary. - */ -template class AuxiliaryInformationType> -bool RectangleTree:: - DeletePoint(const size_t point) -{ - // It is possible that this will cause a reinsertion, so we need to handle the - // levels properly. - RectangleTree* root = this; - while (root->Parent() != NULL) - root = root->Parent(); - - std::vector lvls(root->TreeDepth(), true); - - if (numChildren == 0) - { - for (size_t i = 0; i < count; i++) - { - if (points[i] == point) - { - if (!auxiliaryInfo.HandlePointDeletion(this, i)) - points[i] = points[--count]; - - RectangleTree* tree = this; - while (tree != NULL) - { - tree->numDescendants--; - tree = tree->Parent(); - } - // This function wil ensure that minFill is satisfied. - CondenseTree(dataset->col(point), lvls, true); - return true; - } - } - } - - for (size_t i = 0; i < numChildren; i++) - if (children[i]->Bound().Contains(dataset->col(point))) - if (children[i]->DeletePoint(point, lvls)) - return true; - - return false; -} - -/** - * Recurse through the tree to remove the point. Once we find the point, we - * shrink the rectangles if necessary. - */ -template class AuxiliaryInformationType> -bool RectangleTree:: - DeletePoint(const size_t point, std::vector& relevels) -{ - if (numChildren == 0) - { - for (size_t i = 0; i < count; i++) - { - if (points[i] == point) - { - if (!auxiliaryInfo.HandlePointDeletion(this, i)) - points[i] = points[--count]; - - RectangleTree* tree = this; - while (tree != NULL) - { - tree->numDescendants--; - tree = tree->Parent(); - } - // This function will ensure that minFill is satisfied. - CondenseTree(dataset->col(point), relevels, true); - return true; - } - } - } - - for (size_t i = 0; i < numChildren; i++) - if (children[i]->Bound().Contains(dataset->col(point))) - if (children[i]->DeletePoint(point, relevels)) - return true; - - return false; -} - - -/** - * Recurse through the tree to remove the node. Once we find the node, we - * shrink the rectangles if necessary. - */ -template class AuxiliaryInformationType> -bool RectangleTree:: - RemoveNode(const RectangleTree* node, std::vector& relevels) -{ - for (size_t i = 0; i < numChildren; i++) - { - if (children[i] == node) - { - if (!auxiliaryInfo.HandleNodeRemoval(this, i)) - { - children[i] = children[--numChildren]; // Decrement numChildren. - } - RectangleTree* tree = this; - while (tree != NULL) - { - tree->numDescendants -= node->numDescendants; - tree = tree->Parent(); - } - CondenseTree(arma::vec(), relevels, false); - return true; - } - - bool contains = true; - for (size_t j = 0; j < node->Bound().Dim(); j++) - contains &= Child(i).Bound()[j].Contains(node->Bound()[j]); - - if (contains) - if (children[i]->RemoveNode(node, relevels)) - return true; - } - - return false; -} - -template class AuxiliaryInformationType> -size_t RectangleTree::TreeSize() const -{ - int n = 0; - for (int i = 0; i < numChildren; i++) - n += children[i]->TreeSize(); - - return n + 1; // Add one for this node. -} - -template class AuxiliaryInformationType> -size_t RectangleTree::TreeDepth() const -{ - int n = 1; - RectangleTree* currentNode = const_cast (this); - - while (!currentNode->IsLeaf()) - { - currentNode = currentNode->children[0]; - n++; - } - - return n; -} - -template class AuxiliaryInformationType> -inline bool RectangleTree::IsLeaf() const -{ - return (numChildren == 0); -} - -/** - * Return the index of the nearest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ -template class AuxiliaryInformationType> -template -size_t RectangleTree::GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>*) -{ - if (IsLeaf()) - return 0; - - ElemType bestDistance = std::numeric_limits::max(); - size_t bestIndex = 0; - for (size_t i = 0; i < NumChildren(); ++i) - { - ElemType distance = Child(i).MinDistance(point); - if (distance <= bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - return bestIndex; -} - -/** - * Return the index of the furthest child node to the given query point. If - * this is a leaf node, it will return NumChildren() (invalid index). - */ -template class AuxiliaryInformationType> -template -size_t RectangleTree::GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>*) -{ - if (IsLeaf()) - return 0; - - ElemType bestDistance = 0; - size_t bestIndex = 0; - for (size_t i = 0; i < NumChildren(); ++i) - { - ElemType distance = Child(i).MaxDistance(point); - if (distance >= bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - return bestIndex; -} - -/** - * Return the index of the nearest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ -template class AuxiliaryInformationType> -size_t RectangleTree::GetNearestChild(const RectangleTree& queryNode) -{ - if (IsLeaf()) - return 0; - - ElemType bestDistance = std::numeric_limits::max(); - size_t bestIndex = 0; - for (size_t i = 0; i < NumChildren(); ++i) - { - ElemType distance = Child(i).MinDistance(queryNode); - if (distance <= bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - return bestIndex; -} - -/** - * Return the index of the furthest child node to the given query node. If it - * can't decide, it will return NumChildren() (invalid index). - */ -template class AuxiliaryInformationType> -size_t RectangleTree::GetFurthestChild(const RectangleTree& queryNode) -{ - if (IsLeaf()) - return 0; - - ElemType bestDistance = 0; - size_t bestIndex = 0; - for (size_t i = 0; i < NumChildren(); ++i) - { - ElemType distance = Child(i).MaxDistance(queryNode); - if (distance >= bestDistance) - { - bestDistance = distance; - bestIndex = i; - } - } - return bestIndex; -} - -/** - * Return a bound on the furthest point in the node form the centroid. - * This returns 0 unless the node is a leaf. - */ -template class AuxiliaryInformationType> -inline -typename RectangleTree::ElemType -RectangleTree::FurthestPointDistance() const -{ - if (!IsLeaf()) - return 0.0; - - // Otherwise return the distance from the centroid to a corner of the bound. - return 0.5 * bound.Diameter(); -} - -/** - * Return the furthest possible descendant distance. This returns the maximum - * distance from the centroid to the edge of the bound and not the empirical - * quantity which is the actual furthest descendant distance. So the actual - * furthest descendant distance may be less than what this method returns (but - * it will never be greater than this). - */ -template class AuxiliaryInformationType> -inline -typename RectangleTree::ElemType -RectangleTree::FurthestDescendantDistance() const -{ - // Return the distance from the centroid to a corner of the bound. - return 0.5 * bound.Diameter(); -} - -/** - * Return the number of points contained in this node. Zero if it is a non-leaf - * node. - */ -template class AuxiliaryInformationType> -inline size_t RectangleTree::NumPoints() const -{ - if (numChildren != 0) // This is not a leaf node. - return 0; - - return count; -} - -/** - * Return the number of descendants under or in this node. - */ -template class AuxiliaryInformationType> -inline size_t RectangleTree::NumDescendants() const -{ - return numDescendants; -} - -/** - * Return the index of a particular descendant contained in this node. - */ -template class AuxiliaryInformationType> -inline size_t RectangleTree::Descendant(const size_t index) const -{ - // I think this may be inefficient... - if (numChildren == 0) - { - return (points[index]); - } - else - { - size_t n = 0; - for (size_t i = 0; i < numChildren; ++i) - { - const size_t nd = children[i]->NumDescendants(); - if (index - n < nd) - return children[i]->Descendant(index - n); - n += nd; - } - - // I don't think this is valid. - return children[numChildren - 1]->Descendant(index - n); - } -} - -/** - * Split the tree. This calls the SplitType code to split a node. This method - * should only be called on a leaf node. - */ -template class AuxiliaryInformationType> -void RectangleTree:: - SplitNode(std::vector& relevels) -{ - if (numChildren == 0) - { - // We let the SplitType check if the node if overflowed - // since an intermediate node of the R+ tree may be overflowed if the leaf - // node contains only one point. - - // The SplitType takes care of this and of moving up the tree if necessary. - SplitType::SplitLeafNode(this, relevels); - } - else - { - // Check to see if we are full. - if (numChildren <= maxNumChildren) - return; // We don't need to split. - - // If we are full, then we need to split (or at least try). The SplitType - // takes care of this and of moving up the tree if necessary. - SplitType::SplitNonLeafNode(this, relevels); - } -} - -//! Default constructor for boost::serialization. -template class AuxiliaryInformationType> -RectangleTree:: -RectangleTree() : - maxNumChildren(0), // Try to give sensible defaults, but it shouldn't matter - minNumChildren(0), // because this tree isn't valid anyway and is only used - numChildren(0), // by boost::serialization. - parent(NULL), - begin(0), - count(0), - numDescendants(0), - maxLeafSize(0), - minLeafSize(0), - parentDistance(0.0), - dataset(NULL), - ownsDataset(false) -{ - // Nothing to do. -} - -/** - * Condense the tree. This shrinks the bounds and moves up the tree if - * applicable. If a node goes below minimum fill, this code will deal with it. - */ -template class AuxiliaryInformationType> -void RectangleTree:: - CondenseTree(const arma::vec& point, - std::vector& relevels, - const bool usePoint) -{ - // First delete the node if we need to. There's no point in shrinking the - // bound first. - if (IsLeaf() && count < minLeafSize && parent != NULL) - { - // We can't delete the root node. - for (size_t i = 0; i < parent->NumChildren(); i++) - { - if (parent->children[i] == this) - { - // Decrement numChildren. - if (!auxiliaryInfo.HandleNodeRemoval(parent, i)) - { - parent->children[i] = parent->children[--parent->NumChildren()]; - } - - // We find the root and shrink bounds at the same time. - bool stillShrinking = true; - RectangleTree* root = parent; - while (root->Parent() != NULL) - { - if (stillShrinking) - stillShrinking = root->ShrinkBoundForBound(bound); - root = root->Parent(); - } - if (stillShrinking) - root->ShrinkBoundForBound(bound); - - root = parent; - while (root != NULL) - { - root->numDescendants -= numDescendants; - root = root->Parent(); - } - - stillShrinking = true; - root = parent; - while (root->Parent() != NULL) - { - if (stillShrinking) - stillShrinking = root->AuxiliaryInfo().UpdateAuxiliaryInfo(root); - root = root->Parent(); - } - if (stillShrinking) - root->AuxiliaryInfo().UpdateAuxiliaryInfo(root); - - // Reinsert the points at the root node. - for (size_t j = 0; j < count; j++) - root->InsertPoint(points[j], relevels); - - // This will check the minFill of the parent. - parent->CondenseTree(point, relevels, usePoint); - // Now it should be safe to delete this node. - SoftDelete(); - - return; - } - } - // Control should never reach here. - assert(false); - } - else if (!IsLeaf() && numChildren < minNumChildren) - { - if (parent != NULL) - { - // The normal case. We need to be careful with the root. - for (size_t j = 0; j < parent->NumChildren(); j++) - { - if (parent->children[j] == this) - { - // Decrement numChildren. - if (!auxiliaryInfo.HandleNodeRemoval(parent, j)) - { - parent->children[j] = parent->children[--parent->NumChildren()]; - } - size_t level = TreeDepth(); - - // We find the root and shrink bounds at the same time. - bool stillShrinking = true; - RectangleTree* root = parent; - while (root->Parent() != NULL) - { - if (stillShrinking) - stillShrinking = root->ShrinkBoundForBound(bound); - root = root->Parent(); - } - if (stillShrinking) - root->ShrinkBoundForBound(bound); - - root = parent; - while (root != NULL) - { - root->numDescendants -= numDescendants; - root = root->Parent(); - } - - stillShrinking = true; - root = parent; - while (root->Parent() != NULL) - { - if (stillShrinking) - stillShrinking = root->AuxiliaryInfo().UpdateAuxiliaryInfo(root); - root = root->Parent(); - } - if (stillShrinking) - root->AuxiliaryInfo().UpdateAuxiliaryInfo(root); - - // Reinsert the nodes at the root node. - for (size_t i = 0; i < numChildren; i++) - root->InsertNode(children[i], level, relevels); - - // This will check the minFill of the point. - parent->CondenseTree(point, relevels, usePoint); - // Now it should be safe to delete this node. - SoftDelete(); - - return; - } - } - } - else if (numChildren == 1) - { - // If there are multiple children, we can't do anything to the root. - RectangleTree* child = children[0]; - - // Required for the X tree. - if (child->NumChildren() > maxNumChildren) - { - maxNumChildren = child->MaxNumChildren(); - children.resize(maxNumChildren + 1); - } - - for (size_t i = 0; i < child->NumChildren(); i++) - { - children[i] = child->children[i]; - children[i]->Parent() = this; - child->children[i] = NULL; - } - - numChildren = child->NumChildren(); - child->NumChildren() = 0; - - for (size_t i = 0; i < child->Count(); i++) - { - // In case the tree has a height of two. - points[i] = child->Point(i); - } - - auxiliaryInfo = child->AuxiliaryInfo(); - - count = child->Count(); - child->Count() = 0; - - delete child; - return; - } - } - - // If we didn't delete it, shrink the bound if we need to. - if (usePoint && - (ShrinkBoundForPoint(point) || auxiliaryInfo.UpdateAuxiliaryInfo(this)) && - parent != NULL) - parent->CondenseTree(point, relevels, usePoint); - else if (!usePoint && - (ShrinkBoundForBound(bound) || - auxiliaryInfo.UpdateAuxiliaryInfo(this)) && - parent != NULL) - parent->CondenseTree(point, relevels, usePoint); -} - -/** - * Shrink the bound so it fits tightly after the removal of this point. - */ -template class AuxiliaryInformationType> -bool RectangleTree:: - ShrinkBoundForPoint(const arma::vec& point) -{ - bool shrunk = false; - if (IsLeaf()) - { - for (size_t i = 0; i < bound.Dim(); i++) - { - if (bound[i].Lo() == point[i]) - { - ElemType min = std::numeric_limits::max(); - for (size_t j = 0; j < count; j++) - { - if (dataset->col(points[j])[i] < min) - min = dataset->col(points[j])[i]; - } - - if (bound[i].Lo() < min) - { - shrunk = true; - bound[i].Lo() = min; - } - else if (min < bound[i].Lo()) - { - assert(false); // We have a problem. - } - } - else if (bound[i].Hi() == point[i]) - { - ElemType max = std::numeric_limits::lowest(); - for (size_t j = 0; j < count; j++) - { - if (dataset->col(points[j])[i] > max) - max = dataset->col(points[j])[i]; - } - - if (bound[i].Hi() > max) - { - shrunk = true; - bound[i].Hi() = max; - } - else if (max > bound[i].Hi()) - { - assert(false); // We have a problem. - } - } - } - } - else - { - for (size_t i = 0; i < bound.Dim(); i++) - { - if (bound[i].Lo() == point[i]) - { - ElemType min = std::numeric_limits::max(); - for (size_t j = 0; j < numChildren; j++) - { - if (children[j]->Bound()[i].Lo() < min) - min = children[j]->Bound()[i].Lo(); - } - - if (bound[i].Lo() < min) - { - shrunk = true; - bound[i].Lo() = min; - } - } - else if (bound[i].Hi() == point[i]) - { - ElemType max = std::numeric_limits::lowest(); - for (size_t j = 0; j < numChildren; j++) - { - if (children[j]->Bound()[i].Hi() > max) - max = children[j]->Bound()[i].Hi(); - } - - if (bound[i].Hi() > max) - { - shrunk = true; - bound[i].Hi() = max; - } - } - } - } - - return shrunk; -} - -/** - * Shrink the bound so it fits tightly after the removal of another bound. - */ -template class AuxiliaryInformationType> -bool RectangleTree:: - ShrinkBoundForBound(const bound::HRectBound& /* b */) -{ - // Using the sum is safe since none of the dimensions can increase. - ElemType sum = 0; - - // I think it may be faster to just recalculate the whole thing. - for (size_t i = 0; i < bound.Dim(); i++) - { - sum += bound[i].Width(); - bound[i].Lo() = std::numeric_limits::max(); - bound[i].Hi() = std::numeric_limits::lowest(); - } - - for (size_t i = 0; i < numChildren; i++) - { - bound |= children[i]->Bound(); - } - - ElemType sum2 = 0; - for (size_t i = 0; i < bound.Dim(); i++) - sum2 += bound[i].Width(); - - return sum != sum2; -} - -/** - * Serialize the tree. - */ -template class AuxiliaryInformationType> -template -void RectangleTree::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // Clean up memory, if necessary. - if (Archive::is_loading::value) - { - for (size_t i = 0; i < numChildren; i++) - delete children[i]; - children.clear(); - - if (ownsDataset && dataset) - delete dataset; - - parent = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(maxNumChildren); - ar & BOOST_SERIALIZATION_NVP(minNumChildren); - ar & BOOST_SERIALIZATION_NVP(numChildren); - if (Archive::is_loading::value) - children.resize(maxNumChildren + 1); - - ar & BOOST_SERIALIZATION_NVP(begin); - ar & BOOST_SERIALIZATION_NVP(count); - ar & BOOST_SERIALIZATION_NVP(numDescendants); - ar & BOOST_SERIALIZATION_NVP(maxLeafSize); - ar & BOOST_SERIALIZATION_NVP(minLeafSize); - ar & BOOST_SERIALIZATION_NVP(bound); - ar & BOOST_SERIALIZATION_NVP(stat); - ar & BOOST_SERIALIZATION_NVP(parentDistance); - ar & BOOST_SERIALIZATION_NVP(dataset); - ar & BOOST_SERIALIZATION_NVP(ownsDataset); - - ar & BOOST_SERIALIZATION_NVP(points); - ar & BOOST_SERIALIZATION_NVP(auxiliaryInfo); - - // Since we may or may not be holding children, we need to serialize _only_ - // numChildren children. - for (size_t i = 0; i < numChildren; ++i) - { - std::ostringstream oss; - oss << "children" << i; - ar & boost::serialization::make_nvp(oss.str().c_str(), children[i]); - - if (Archive::is_loading::value) - children[i]->parent = this; - } - for (size_t i = numChildren; i < maxNumChildren + 1; ++i) - { - children[i] = NULL; - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/single_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/single_tree_traverser.hpp deleted file mode 100644 index bd79017ec..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/single_tree_traverser.hpp +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file single_tree_traverser.hpp - * @author Andrew Wells - * - * A nested class of Rectangle Tree for traversing rectangle type trees - * with a given set of rules which indicate the branches to prune and the - * order in which to recurse. This is a depth-first traverser. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_SINGLE_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_SINGLE_TREE_TRAVERSER_HPP - -#include - -#include "rectangle_tree.hpp" - -namespace mlpack { -namespace tree { - -template class AuxiliaryInformationType> -template -class RectangleTree::SingleTreeTraverser -{ - public: - /** - * Instantiate the traverser with the given rule set. - */ - SingleTreeTraverser(RuleType& rule); - - /** - * Traverse the tree with the given point. - * - * @param queryIndex The index of the point in the query set which is being - * used as the query point. - * @param referenceNode The tree node to be traversed. - */ - void Traverse(const size_t queryIndex, const RectangleTree& referenceNode); - - //! Get the number of prunes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of prunes. - size_t& NumPrunes() { return numPrunes; } - - private: - // We use this class and this function to make the sorting and scoring easy - // and efficient: - struct NodeAndScore - { - RectangleTree* node; - double score; - }; - - static bool NodeComparator(const NodeAndScore& obj1, const NodeAndScore& obj2) - { - return obj1.score < obj2.score; - } - - //! Reference to the rules with which the tree will be traversed. - RuleType& rule; - - //! The number of nodes which have been prenud during traversal. - size_t numPrunes; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "single_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/single_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/single_tree_traverser_impl.hpp deleted file mode 100644 index 3b96faf00..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/single_tree_traverser_impl.hpp +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @file single_tree_traverser_impl.hpp - * @author Andrew Wells - * - * A class for traversing rectangle type trees with a given set of rules - * which indicate the branches to prune and the order in which to recurse. - * This is a depth-first traverser. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_SINGLE_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_SINGLE_TREE_TRAVERSER_IMPL_HPP - -#include "single_tree_traverser.hpp" - -#include -#include - -namespace mlpack { -namespace tree { - -template class AuxiliaryInformationType> -template -RectangleTree:: -SingleTreeTraverser::SingleTreeTraverser(RuleType& rule) : - rule(rule), - numPrunes(0) -{ /* Nothing to do */ } - -template class AuxiliaryInformationType> -template -void RectangleTree:: -SingleTreeTraverser::Traverse( - const size_t queryIndex, - const RectangleTree& referenceNode) -{ - // If we reach a leaf node, we need to run the base case. - if (referenceNode.IsLeaf()) - { - for (size_t i = 0; i < referenceNode.Count(); i++) - rule.BaseCase(queryIndex, referenceNode.Point(i)); - - return; - } - - // This is not a leaf node so we sort the children of this node by their - // scores. - std::vector nodesAndScores(referenceNode.NumChildren()); - for (size_t i = 0; i < referenceNode.NumChildren(); i++) - { - nodesAndScores[i].node = &(referenceNode.Child(i)); - nodesAndScores[i].score = rule.Score(queryIndex, *nodesAndScores[i].node); - } - - std::sort(nodesAndScores.begin(), nodesAndScores.end(), NodeComparator); - - // Now iterate through them starting with the best and stopping when we reach - // one that isn't good enough. - for (size_t i = 0; i < referenceNode.NumChildren(); i++) - { - if (rule.Rescore(queryIndex, *nodesAndScores[i].node, - nodesAndScores[i].score) != DBL_MAX) - { - Traverse(queryIndex, *nodesAndScores[i].node); - } - else - { - numPrunes += referenceNode.NumChildren() - i; - return; - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/traits.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/traits.hpp deleted file mode 100644 index c14d37bd3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/traits.hpp +++ /dev/null @@ -1,137 +0,0 @@ -/** - * @file traits.hpp - * @author Andrew Wells - * - * Specialization of the TreeTraits class for the RectangleTree type of tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_TRAITS_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_TRAITS_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * This is a specialization of the TreeType class to the RectangleTree tree - * type. It defines characteristics of the rectangle type trees, and is used to - * help write tree-independent (but still optimized) tree-based algorithms. See - * mlpack/core/tree/tree_traits.hpp for more information. - */ -template class AuxiliaryInformationType> -class TreeTraits> -{ - public: - /** - * An R-tree can have overlapping children. - */ - static const bool HasOverlappingChildren = true; - - /** - * An R-tree node doesn't share points with another node. - */ - static const bool HasDuplicatedPoints = false; - - /** - * There is no guarantee that the first point in a node is its centroid. - */ - static const bool FirstPointIsCentroid = false; - - /** - * Points are not contained at multiple levels of the R-tree. - */ - static const bool HasSelfChildren = false; - - /** - * Points are rearranged during building of the tree. - * THIS MAY NOT BE TRUE. IT'S HARD TO DYNAMICALLY INSERT POINTS - * AND REARRANGE THE MATRIX - */ - static const bool RearrangesDataset = false; - - /** - * This tree is not necessarily a binary tree. - */ - static const bool BinaryTree = false; - - /** - * Rectangle trees don't have duplicated points, so NumDescendants() - * represents the number of unique descendant points. - */ - static const bool UniqueNumDescendants = true; -}; - -/** - * Since the R+/R++ tree can not have overlapping children, we should define - * traits for the R+/R++ tree. - */ -template class SweepType, - typename DescentType, - template class AuxiliaryInformationType> -class TreeTraits, - DescentType, - AuxiliaryInformationType>> -{ - public: - /** - * The R+/R++ tree can't have overlapping children. - */ - static const bool HasOverlappingChildren = false; - - /** - * An R-tree node doesn't share points with another node. - */ - static const bool HasDuplicatedPoints = false; - - /** - * There is no guarantee that the first point in a node is its centroid. - */ - static const bool FirstPointIsCentroid = false; - - /** - * Points are not contained at multiple levels of the R-tree. - */ - static const bool HasSelfChildren = false; - - /** - * Points are rearranged during building of the tree. - * THIS MAY NOT BE TRUE. IT'S HARD TO DYNAMICALLY INSERT POINTS - * AND REARRANGE THE MATRIX - */ - static const bool RearrangesDataset = false; - - /** - * This tree is not necessarily a binary tree. - */ - static const bool BinaryTree = false; - - /** - * Rectangle trees don't have duplicated points, so NumDescendants() - * represents the number of unique descendant points. - */ - static const bool UniqueNumDescendants = true; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/typedef.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/typedef.hpp deleted file mode 100644 index c589732d7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/typedef.hpp +++ /dev/null @@ -1,201 +0,0 @@ -/** - * @file typedef.hpp - * @author Ryan Curtin - * - * Typedefs of RectangleTrees, for use by classes that require trees matching - * the TreeType API. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_TYPEDEF_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_TYPEDEF_HPP - -#include "rectangle_tree.hpp" - -namespace mlpack { -namespace tree { - -/** - * An implementation of the R tree that satisfies the TreeType policy API. - * - * This is the same R-tree structure as proposed by Guttman: - * - * @code - * @inproceedings{guttman1984r, - * title={R-trees: a dynamic index structure for spatial searching}, - * author={Guttman, A.}, - * booktitle={Proceedings of the 1984 ACM SIGMOD International Conference on - * Management of Data (SIGMOD '84)}, - * volume={14}, - * number={2}, - * year={1984}, - * publisher={ACM} - * } - * @endcode - * - * @see @ref trees, RStarTree - */ -template -using RTree = RectangleTree; - -/** - * The R*-tree, a more recent variant of the R tree. This template typedef - * satisfies the TreeType policy API. - * - * @code - * @inproceedings{beckmann1990r, - * title={The R*-tree: an efficient and robust access method for points and - * rectangles}, - * author={Beckmann, N. and Kriegel, H.-P. and Schneider, R. and Seeger, B.}, - * booktitle={Proceedings of the 1990 ACM SIGMOD International Conference on - * Management of Data (SIGMOD '90)}, - * volume={19}, - * number={2}, - * year={1990}, - * publisher={ACM} - * } - * @endcode - * - * @see @ref trees, RTree - */ -template -using RStarTree = RectangleTree; - -/** - * The X-tree, a variant of the R tree with supernodes. This template typedef - * satisfies the TreeType policy API. - * - * @code - * @inproceedings{berchtold1996r, - * title = {The X-Tree: An Index Structure for High--Dimensional Data}, - * author = {Berchtold, Stefan and Keim, Daniel A. and Kriegel, Hans-Peter}, - * booktitle = {Proc. 22th Int. Conf. on Very Large Databases (VLDB'96), Bombay, India}, - * editor = {Vijayaraman, T. and Buchmann, Alex and Mohan, C. and Sarda, N.}, - * pages = {28--39}, - * year = {1996}, - * publisher = {Morgan Kaufmann} - * } - * @endcode - * - * @see @ref trees, RTree, RStarTree - */ -template -using XTree = RectangleTree; - -/** - * The Hilbert R-tree, a variant of the R tree with an ordering along - * the Hilbert curve. This template typedef satisfies the TreeType policy API. - * - * @code - * @inproceedings{kamel1994r, - * author = {Kamel, Ibrahim and Faloutsos, Christos}, - * title = {Hilbert R-tree: An Improved R-tree Using Fractals}, - * booktitle = {Proceedings of the 20th International Conference on Very Large Data Bases}, - * series = {VLDB '94}, - * year = {1994}, - * isbn = {1-55860-153-8}, - * pages = {500--509}, - * numpages = {10}, - * url = {http://dl.acm.org/citation.cfm?id=645920.673001}, - * acmid = {673001}, - * publisher = {Morgan Kaufmann Publishers Inc.}, - * address = {San Francisco, CA, USA} - * } - * @endcode - * - * @see @ref trees, RTree, DiscreteHilbertRTree - */ -template -using DiscreteHilbertRTreeAuxiliaryInformation = - HilbertRTreeAuxiliaryInformation; - -template -using HilbertRTree = RectangleTree, - HilbertRTreeDescentHeuristic, - DiscreteHilbertRTreeAuxiliaryInformation>; - -/** - * The R+ tree, a variant of the R tree that avoids overlapping rectangles. - * The implementation is modified from the original paper implementation. - * This template typedef satisfies the TreeType policy API. - * - * @code - * @inproceedings{sellis1987r, - * author = {Sellis, Timos K. and Roussopoulos, Nick and Faloutsos, Christos}, - * title = {The R+-Tree: A Dynamic Index for Multi-Dimensional Objects}, - * booktitle = {Proceedings of the 13th International Conference on Very - * Large Data Bases}, - * series = {VLDB '87}, - * year = {1987}, - * isbn = {0-934613-46-X}, - * pages = {507--518}, - * numpages = {12}, - * publisher = {Morgan Kaufmann Publishers Inc.}, - * address = {San Francisco, CA, USA}, - * } - * @endcode - * - * @see @ref trees, RTree, RTree, RPlusTree - */ -template -using RPlusTree = RectangleTree, - RPlusTreeDescentHeuristic, - NoAuxiliaryInformation>; - -/** - * The R++ tree, a variant of the R+ tree with maximum buonding rectangles. - * This template typedef satisfies the TreeType policy API. - * - * @code - * @inproceedings{sumak2014r, - * author = {{\v{S}}um{\'a}k, Martin and Gursk{\'y}, Peter}, - * title = {R++-Tree: An Efficient Spatial Access Method for Highly Redundant - * Point Data}, - * booktitle = {New Trends in Databases and Information Systems: 17th East - * European Conference on Advances in Databases and Information Systems}, - * year = {2014}, - * isbn = {978-3-319-01863-8}, - * pages = {37--44}, - * publisher = {Springer International Publishing}, - * } - * @endcode - * - * @see @ref trees, RTree, RTree, RPlusTree, RPlusPlusTree - */ -template -using RPlusPlusTree = RectangleTree, - RPlusPlusTreeDescentHeuristic, - RPlusPlusTreeAuxiliaryInformation>; -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_auxiliary_information.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_auxiliary_information.hpp deleted file mode 100644 index 522341ca6..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_auxiliary_information.hpp +++ /dev/null @@ -1,237 +0,0 @@ -/** - * @file no_auxiliary_information.hpp - * @author Mikhail Lozhnikov - * - * Definition of the XTreeAuxiliaryInformation class, a class that provides - * some x-tree specific information about the nodes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_AUXILIARY_INFORMATION_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_AUXILIARY_INFORMATION_HPP - -namespace mlpack { -namespace tree { - -/** - * The XTreeAuxiliaryInformation class provides information specific to X trees - * for each node in a RectangleTree. - */ -template -class XTreeAuxiliaryInformation -{ - public: - //! Default constructor - XTreeAuxiliaryInformation() : - normalNodeMaxNumChildren(0), - splitHistory(0) - { }; - - /** - * Construct this with the specified node. - * - * @param node The node that stores this auxiliary information. - */ - XTreeAuxiliaryInformation(const TreeType* node) : - normalNodeMaxNumChildren(node->Parent() ? - node->Parent()->AuxiliaryInfo().NormalNodeMaxNumChildren() : - node->MaxNumChildren()), - splitHistory(node->Bound().Dim()) - { }; - - /** - * Create an auxiliary information object by copying from another object. - * - * @param other Another auxiliary information object from which the - * information will be copied. - * @param tree The node that holds the auxiliary information. - * @param deepCopy If false, the new object uses the same memory - * (not used here). - */ - XTreeAuxiliaryInformation(const XTreeAuxiliaryInformation& other, - TreeType* /* tree */ = NULL, - bool /* deepCopy */ = true) : - normalNodeMaxNumChildren(other.NormalNodeMaxNumChildren()), - splitHistory(other.SplitHistory()) - { }; - - /** - * Copy the auxiliary information object. - * - * @param other The node from which the information will be copied. - */ - XTreeAuxiliaryInformation& operator=(const XTreeAuxiliaryInformation& other) - { - normalNodeMaxNumChildren = other.NormalNodeMaxNumChildren(); - splitHistory = other.SplitHistory(); - - return *this; - } - - /** - * Create an auxiliary information object by moving from the other node. - * - * @param other The object from which the information will be moved. - */ - XTreeAuxiliaryInformation(XTreeAuxiliaryInformation&& other) : - normalNodeMaxNumChildren(other.NormalNodeMaxNumChildren()), - splitHistory(std::move(other.splitHistory)) - { - other.normalNodeMaxNumChildren = 0; - }; - - /** - * Some tree types require to save some properties at the insertion process. - * This method allows the auxiliary information the option of manipulating the - * tree in order to perform the insertion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node in which the point is being inserted. - * @param point The global number of the point being inserted. - */ - bool HandlePointInsertion(TreeType* /* node */, const size_t /* point */) - { - return false; - } - - /** - * Some tree types require to save some properties at the insertion process. - * This method allows the auxiliary information the option of manipulating the - * tree in order to perform the insertion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * - * @param node The node in which the nodeToInsert is being inserted. - * @param nodeToInsert The node being inserted. - * @param insertionLevel The level of the tree at which the nodeToInsert - * should be inserted. - */ - bool HandleNodeInsertion(TreeType* /* node */, - TreeType* /* nodeToInsert */, - bool /* insertionLevel */) - { - return false; - } - - /** - * Some tree types require to save some properties at the deletion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the deletion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * @param node The node from which the point is being deleted. - * @param localIndex The local index of the point being deleted. - */ - bool HandlePointDeletion(TreeType* , const size_t) - { - return false; - } - - /** - * Some tree types require to save some properties at the deletion process. - * This method allows the auxiliary information the option of manipulating - * the tree in order to perform the deletion process. If the auxiliary - * information does that, then the method should return true; if the method - * returns false the RectangleTree performs its default behavior. - * @param node The node from which the node is being deleted. - * @param nodeIndex The local index of the node being deleted. - */ - bool HandleNodeRemoval(TreeType* , const size_t) - { - return false; - } - - /** - * Some tree types require to propagate the information upward. - * This method should return false if this is not the case. If true is - * returned, the update will be propagated upward. - * @param node The node in which the auxiliary information being update. - */ - bool UpdateAuxiliaryInfo(TreeType* ) - { - return false; - } - - /** - * Nullify the auxiliary information in order to prevent an invalid free. - */ - void NullifyData() - { } - - /** - * The X tree requires that the tree records it's "split history". To make - * this easy, we use the following structure. - */ - typedef struct SplitHistoryStruct - { - int lastDimension; - std::vector history; - - SplitHistoryStruct(int dim) : lastDimension(0), history(dim) - { - for (int i = 0; i < dim; i++) - history[i] = false; - } - - SplitHistoryStruct(const SplitHistoryStruct& other) : - lastDimension(other.lastDimension), - history(other.history) - { } - - SplitHistoryStruct& operator=(const SplitHistoryStruct& other) - { - lastDimension = other.lastDimension; - history = other.history; - return *this; - } - - SplitHistoryStruct(SplitHistoryStruct&& other) : - lastDimension(other.lastDimension), - history(std::move(other.history)) - { - other.lastDimension = 0; - } - - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(lastDimension); - ar & BOOST_SERIALIZATION_NVP(history); - } - } SplitHistoryStruct; - - private: - //! The max number of child nodes a non-leaf normal node can have. - size_t normalNodeMaxNumChildren; - //! A struct to store the "split history" for X trees. - SplitHistoryStruct splitHistory; - - public: - //! Return the maximum number of a normal node's children. - size_t NormalNodeMaxNumChildren() const { return normalNodeMaxNumChildren; } - //! Modify the maximum number of a normal node's children. - size_t& NormalNodeMaxNumChildren() { return normalNodeMaxNumChildren; } - //! Return the split history of the node associated with this object. - const SplitHistoryStruct& SplitHistory() const { return splitHistory; } - //! Modify the split history of the node associated with this object. - SplitHistoryStruct& SplitHistory() { return splitHistory; } - - /** - * Serialize the information. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(normalNodeMaxNumChildren); - ar & BOOST_SERIALIZATION_NVP(splitHistory); - } -}; - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_AUXILIARY_INFORMATION_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_split.hpp deleted file mode 100644 index 5273a45a4..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_split.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file x_tre_split.hpp - * @author Andrew Wells - * - * Definition of the XTreeSplit class, a class that splits the nodes of an X - * tree, starting at a leaf node and moving upwards if necessary. - * - * This is known to have a bug: see #368. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP - -#include - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * The X-tree paper says that a maximum allowable overlap of 20% works well. - * - * This code should eventually be refactored so as to avoid polluting - * mlpack::tree with this random double. - */ -const double MAX_OVERLAP = 0.2; - -/** - * A Rectangle Tree has new points inserted at the bottom. When these - * nodes overflow, we split them, moving up the tree and splitting nodes - * as necessary. - */ -class XTreeSplit -{ - public: - /** - * Split a leaf node using the algorithm described in "The R*-tree: An - * Efficient and Robust Access method for Points and Rectangles." If - * necessary, this split will propagate upwards through the tree. - */ - template - static void SplitLeafNode(TreeType *tree, std::vector& relevels); - - /** - * Split a non-leaf node using the "default" algorithm. If this is a root - * node, the tree increases in depth. - */ - template - static bool SplitNonLeafNode(TreeType *tree, std::vector& relevels); - - private: - /** - * Insert a node into another node. - */ - template - static void InsertNodeIntoTree(TreeType* destTree, TreeType* srcNode); - - /** - * Comparator for sorting with std::pair. This comparator works a little bit - * faster then the default comparator. - */ - template - static bool PairComp(const std::pair& p1, - const std::pair& p2) - { - return p1.first < p2.first; - } -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation -#include "x_tree_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_split_impl.hpp deleted file mode 100644 index de27c3913..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/rectangle_tree/x_tree_split_impl.hpp +++ /dev/null @@ -1,723 +0,0 @@ -/** - * @file x_tree_split_impl.hpp - * @author Andrew Wells - * - * Implementation of class (XTreeSplit) to split a RectangleTree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_IMPL_HPP - -#include "x_tree_split.hpp" -#include "rectangle_tree.hpp" -#include - -namespace mlpack { -namespace tree { - -/** - * We call GetPointSeeds to get the two points which will be the initial points - * in the new nodes We then call AssignPointDestNode to assign the remaining - * points to the two new nodes. Finally, we delete the old node and insert the - * new nodes into the tree, spliting the parent if necessary. - */ -template -void XTreeSplit::SplitLeafNode(TreeType *tree, std::vector& relevels) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - - if (tree->Count() <= tree->MaxLeafSize()) - return; - - // If we haven't yet reinserted on this level, we try doing so now. - if (RStarTreeSplit::ReinsertPoints(tree, relevels) > 0) - return; - - // The procedure of splitting a leaf node is virtually identical to the R* - // tree procedure, so we can reuse code. - size_t bestAxis; - size_t bestIndex; - RStarTreeSplit::PickLeafSplit(tree, bestAxis, bestIndex); - - /** - * Now that we have found the best dimension to split on, re-sort in that - * dimension to prepare for reinsertion of points into the new nodes. - */ - std::vector> sorted(tree->Count()); - for (size_t i = 0; i < sorted.size(); i++) - { - sorted[i].first = tree->Dataset().col(tree->Point(i))[bestAxis]; - sorted[i].second = tree->Point(i); - } - - std::sort(sorted.begin(), sorted.end(), PairComp); - - /** - * If 'tree' is the root of the tree (i.e. if it has no parent), then we must - * create two new child nodes, distribute the points from the original node - * among them, and insert those. If 'tree' is not the root of the tree, then - * we may create only one new child node, redistribute the points from the - * original node between 'tree' and the new node, then insert those nodes into - * the parent. - * - * Here we simply set treeOne and treeTwo to the right values to avoid code - * duplication. - */ - TreeType* par = tree->Parent(); - TreeType* treeOne = (par) ? tree : new TreeType(tree); - TreeType* treeTwo = (par) ? new TreeType(par) : new TreeType(tree); - - // Now clean the node, and we will re-use this. - const size_t numPoints = tree->Count(); - - // Reset the original node's values, regardless of whether it will become - // the new parent or not. - tree->numChildren = 0; - tree->numDescendants = 0; - tree->count = 0; - tree->bound.Clear(); - - // Insert the points into the appropriate tree. - for (size_t i = 0; i < numPoints; i++) - { - if (i < bestIndex + tree->MinLeafSize()) - treeOne->InsertPoint(sorted[i].second); - else - treeTwo->InsertPoint(sorted[i].second); - } - - // Insert the new tree node(s). - if (par) - { - par->children[par->NumChildren()++] = treeTwo; - } - else - { - InsertNodeIntoTree(tree, treeOne); - InsertNodeIntoTree(tree, treeTwo); - } - - // We now update the split history of each new node. - treeOne->AuxiliaryInfo().SplitHistory().history[bestAxis] = true; - treeOne->AuxiliaryInfo().SplitHistory().lastDimension = bestAxis; - treeTwo->AuxiliaryInfo().SplitHistory().history[bestAxis] = true; - treeTwo->AuxiliaryInfo().SplitHistory().lastDimension = bestAxis; - - // If we overflowed the parent, split it. - if (par && par->NumChildren() == par->MaxNumChildren() + 1) - XTreeSplit::SplitNonLeafNode(par, relevels); -} - -/** - * We call GetBoundSeeds to get the two new nodes that this one will be broken - * into. Then we call AssignNodeDestNode to move the children of this node into - * either of those two nodes. Finally, we delete the now unused information and - * recurse up the tree if necessary. We don't need to worry about the bounds - * higher up the tree because they were already updated if necessary. - */ -template -bool XTreeSplit::SplitNonLeafNode(TreeType *tree, std::vector& relevels) -{ - // Convenience typedef. - typedef typename TreeType::ElemType ElemType; - typedef bound::HRectBound BoundType; - - // The X tree paper doesn't explain how to handle the split history when - // reinserting nodes and reinserting nodes seems to hurt the performance, so - // we don't do it. - - // We find the split axis that will be used if the topological split fails now - // to save CPU time. - - // Find the next split axis. - std::vector axes(tree->Bound().Dim(), true); - std::vector dimensionsLastUsed(tree->NumChildren()); - for (size_t i = 0; i < tree->NumChildren(); i++) - dimensionsLastUsed[i] = - tree->Child(i).AuxiliaryInfo().SplitHistory().lastDimension; - std::sort(dimensionsLastUsed.begin(), dimensionsLastUsed.end()); - - size_t lastDim = dimensionsLastUsed[dimensionsLastUsed.size() / 2]; - size_t minOverlapSplitDimension = tree->Bound().Dim(); - - // See if we can use a new dimension. - for (size_t i = lastDim + 1; i < axes.size(); i++) - { - for (size_t j = 0; j < tree->NumChildren(); j++) - axes[i] = axes[i] & - tree->Child(j).AuxiliaryInfo().SplitHistory().history[i]; - if (axes[i] == true) - { - minOverlapSplitDimension = i; - break; - } - } - - if (minOverlapSplitDimension == tree->Bound().Dim()) - { - for (size_t i = 0; i < lastDim + 1; i++) - { - axes[i] = true; - for (size_t j = 0; j < tree->NumChildren(); j++) - axes[i] = axes[i] & - tree->Child(j).AuxiliaryInfo().SplitHistory().history[i]; - if (axes[i] == true) - { - minOverlapSplitDimension = i; - break; - } - } - } - - bool minOverlapSplitUsesHi = false; - ElemType bestScoreMinOverlapSplit = std::numeric_limits::max(); - ElemType areaOfBestMinOverlapSplit = 0; - int bestIndexMinOverlapSplit = 0; - - int bestOverlapIndexOnBestAxis = 0; - int bestAreaIndexOnBestAxis = 0; - bool tiedOnOverlap = false; - bool lowIsBest = true; - int bestAxis = 0; - ElemType bestAxisScore = std::numeric_limits::max(); - ElemType overlapBestOverlapAxis = 0; - ElemType areaBestOverlapAxis = 0; - ElemType overlapBestAreaAxis = 0; - ElemType areaBestAreaAxis = 0; - - for (size_t j = 0; j < tree->Bound().Dim(); j++) - { - ElemType axisScore = 0.0; - - // We'll do Bound().Lo() now and use Bound().Hi() later. - std::vector> sorted(tree->NumChildren()); - for (size_t i = 0; i < sorted.size(); i++) - { - sorted[i].first = tree->Child(i).Bound()[j].Lo(); - sorted[i].second = &tree->Child(i); - } - - std::sort(sorted.begin(), sorted.end(), PairComp); - - // We'll store each of the three scores for each distribution. - std::vector areas(tree->MaxNumChildren() - - 2 * tree->MinNumChildren() + 2); - std::vector margins(tree->MaxNumChildren() - - 2 * tree->MinNumChildren() + 2); - std::vector overlapedAreas(tree->MaxNumChildren() - - 2 * tree->MinNumChildren() + 2); - for (size_t i = 0; i < areas.size(); i++) - { - areas[i] = 0.0; - margins[i] = 0.0; - overlapedAreas[i] = 0.0; - } - - for (size_t i = 0; i < areas.size(); i++) - { - // The ith arrangement is obtained by placing the first - // tree->MinNumChildren() + i points in one rectangle and the rest in - // another. Then we calculate the three scores for that distribution. - - size_t cutOff = tree->MinNumChildren() + i; - - BoundType bound1(tree->Bound().Dim()); - BoundType bound2(tree->Bound().Dim()); - - for (size_t l = 0; l < cutOff; l++) - bound1 |= sorted[l].second->Bound(); - - for (size_t l = cutOff; l < tree->NumChildren(); l++) - bound2 |= sorted[l].second->Bound(); - - ElemType area1 = bound1.Volume(); - ElemType area2 = bound2.Volume(); - ElemType oArea = bound1.Overlap(bound2); - - for (size_t k = 0; k < bound1.Dim(); k++) - margins[i] += bound1[k].Width() + bound2[k].Width(); - - areas[i] += area1 + area2; - overlapedAreas[i] += oArea; - axisScore += margins[i]; - } - - if (axisScore < bestAxisScore) - { - bestAxisScore = axisScore; - bestAxis = j; - bestOverlapIndexOnBestAxis = 0; - bestAreaIndexOnBestAxis = 0; - overlapBestOverlapAxis = overlapedAreas[bestOverlapIndexOnBestAxis]; - areaBestOverlapAxis = areas[bestAreaIndexOnBestAxis]; - for (size_t i = 1; i < areas.size(); i++) - { - if (overlapedAreas[i] < overlapedAreas[bestOverlapIndexOnBestAxis]) - { - tiedOnOverlap = false; - bestAreaIndexOnBestAxis = i; - bestOverlapIndexOnBestAxis = i; - overlapBestOverlapAxis = overlapedAreas[i]; - areaBestOverlapAxis = areas[i]; - } - else if (overlapedAreas[i] == - overlapedAreas[bestOverlapIndexOnBestAxis]) - { - tiedOnOverlap = true; - if (areas[i] < areas[bestAreaIndexOnBestAxis]) - { - bestAreaIndexOnBestAxis = i; - overlapBestAreaAxis = overlapedAreas[i]; - areaBestAreaAxis = areas[i]; - } - } - } - } - - // Track the minOverlapSplit data - if (minOverlapSplitDimension != tree->Bound().Dim() && - j == minOverlapSplitDimension) - { - for (size_t i = 0; i < overlapedAreas.size(); i++) - { - if (overlapedAreas[i] < bestScoreMinOverlapSplit) - { - bestScoreMinOverlapSplit = overlapedAreas[i]; - bestIndexMinOverlapSplit = i; - areaOfBestMinOverlapSplit = areas[i]; - } - } - } - } - - // Now we do the same thing using Bound().Hi() and choose the best of the two. - for (size_t j = 0; j < tree->Bound().Dim(); j++) - { - ElemType axisScore = 0.0; - - std::vector> sorted(tree->NumChildren()); - for (size_t i = 0; i < sorted.size(); i++) - { - sorted[i].first = tree->Child(i).Bound()[j].Hi(); - sorted[i].second = &tree->Child(i); - } - - std::sort(sorted.begin(), sorted.end(), PairComp); - - // We'll store each of the three scores for each distribution. - std::vector areas(tree->MaxNumChildren() - - 2 * tree->MinNumChildren() + 2); - std::vector margins(tree->MaxNumChildren() - - 2 * tree->MinNumChildren() + 2); - std::vector overlapedAreas(tree->MaxNumChildren() - - 2 * tree->MinNumChildren() + 2); - for (size_t i = 0; i < areas.size(); i++) - { - areas[i] = 0.0; - margins[i] = 0.0; - overlapedAreas[i] = 0.0; - } - - for (size_t i = 0; i < areas.size(); i++) - { - // The ith arrangement is obtained by placing the first - // tree->MinNumChildren() + i points in one rectangle and the rest in - // another. Then we calculate the three scores for that distribution. - - size_t cutOff = tree->MinNumChildren() + i; - - BoundType bound1(tree->Bound().Dim()); - BoundType bound2(tree->Bound().Dim()); - - for (size_t l = 0; l < cutOff; l++) - bound1 |= sorted[l].second->Bound(); - - for (size_t l = cutOff; l < tree->NumChildren(); l++) - bound2 |= sorted[l].second->Bound(); - - ElemType area1 = bound1.Volume(); - ElemType area2 = bound2.Volume(); - ElemType oArea = bound1.Overlap(bound2); - - for (size_t k = 0; k < bound1.Dim(); k++) - margins[i] += bound1[k].Width() + bound2[k].Width(); - - - areas[i] += area1 + area2; - overlapedAreas[i] += oArea; - axisScore += margins[i]; - } - - if (axisScore < bestAxisScore) - { - bestAxisScore = axisScore; - bestAxis = j; - lowIsBest = false; - bestOverlapIndexOnBestAxis = 0; - bestAreaIndexOnBestAxis = 0; - overlapBestOverlapAxis = overlapedAreas[bestOverlapIndexOnBestAxis]; - areaBestOverlapAxis = areas[bestAreaIndexOnBestAxis]; - for (size_t i = 1; i < areas.size(); i++) - { - if (overlapedAreas[i] < overlapedAreas[bestOverlapIndexOnBestAxis]) - { - tiedOnOverlap = false; - bestAreaIndexOnBestAxis = i; - bestOverlapIndexOnBestAxis = i; - overlapBestOverlapAxis = overlapedAreas[i]; - areaBestOverlapAxis = areas[i]; - } - else if (overlapedAreas[i] == - overlapedAreas[bestOverlapIndexOnBestAxis]) - { - tiedOnOverlap = true; - if (areas[i] < areas[bestAreaIndexOnBestAxis]) - { - bestAreaIndexOnBestAxis = i; - overlapBestAreaAxis = overlapedAreas[i]; - areaBestAreaAxis = areas[i]; - } - } - } - } - - // Track the minOverlapSplit data - if (minOverlapSplitDimension != tree->Bound().Dim() && - j == minOverlapSplitDimension) - { - for (size_t i = 0; i < overlapedAreas.size(); i++) - { - if (overlapedAreas[i] < bestScoreMinOverlapSplit) - { - minOverlapSplitUsesHi = true; - bestScoreMinOverlapSplit = overlapedAreas[i]; - bestIndexMinOverlapSplit = i; - areaOfBestMinOverlapSplit = areas[i]; - } - } - } - } - - std::vector> sorted(tree->NumChildren()); - if (lowIsBest) - { - for (size_t i = 0; i < sorted.size(); i++) - { - sorted[i].first = tree->Child(i).Bound()[bestAxis].Lo(); - sorted[i].second = &tree->Child(i); - } - } - else - { - for (size_t i = 0; i < sorted.size(); i++) - { - sorted[i].first = tree->Child(i).Bound()[bestAxis].Hi(); - sorted[i].second = &tree->Child(i); - } - } - - std::sort(sorted.begin(), sorted.end(), PairComp); - - if (tree->Parent() != NULL) - { - // Reuse tree as the new child. - TreeType* treeTwo = new TreeType(tree->Parent(), tree->MaxNumChildren()); - const size_t numChildren = tree->NumChildren(); - tree->numChildren = 0; - tree->count = 0; - - // Now as per the X-tree paper, we ensure that this split was good enough. - bool useMinOverlapSplit = false; - if (tiedOnOverlap) - { - if (overlapBestAreaAxis / areaBestAreaAxis < MAX_OVERLAP) - { - tree->numDescendants = 0; - tree->bound.Clear(); - for (size_t i = 0; i < numChildren; i++) - { - if (i < bestAreaIndexOnBestAxis + tree->MinNumChildren()) - InsertNodeIntoTree(tree, sorted[i].second); - else - InsertNodeIntoTree(treeTwo, sorted[i].second); - } - } - else - useMinOverlapSplit = true; - } - else - { - if (overlapBestOverlapAxis / areaBestOverlapAxis < MAX_OVERLAP) - { - tree->numDescendants = 0; - tree->bound.Clear(); - for (size_t i = 0; i < numChildren; i++) - { - if (i < bestOverlapIndexOnBestAxis + tree->MinNumChildren()) - InsertNodeIntoTree(tree, sorted[i].second); - else - InsertNodeIntoTree(treeTwo, sorted[i].second); - } - } - else - useMinOverlapSplit = true; - } - - // If the split was not good enough, then we try the minimal overlap split. - // If that fails, we create a "super node" (more accurately we resize this - // one to make it a super node). - if (useMinOverlapSplit) - { - // If there is a dimension that might work, try that. - if ((minOverlapSplitDimension != tree->Bound().Dim()) && - (bestScoreMinOverlapSplit / areaOfBestMinOverlapSplit < MAX_OVERLAP)) - { - std::vector> sorted2(numChildren); - if (minOverlapSplitUsesHi) - { - for (size_t i = 0; i < sorted2.size(); i++) - { - sorted2[i].first = sorted[i].second->Bound()[bestAxis].Hi(); - sorted2[i].second = sorted[i].second; - } - } - else - { - for (size_t i = 0; i < sorted2.size(); i++) - { - sorted2[i].first = sorted[i].second->Bound()[bestAxis].Lo(); - sorted2[i].second = sorted[i].second; - } - } - std::sort(sorted2.begin(), sorted2.end(), - PairComp); - - tree->numDescendants = 0; - tree->bound.Clear(); - for (size_t i = 0; i < numChildren; i++) - { - if (i < bestIndexMinOverlapSplit + tree->MinNumChildren()) - InsertNodeIntoTree(tree, sorted2[i].second); - else - InsertNodeIntoTree(treeTwo, sorted2[i].second); - } - } - else - { - // We don't create a supernode that would be the only child of the root. - // (Note that if you did try to do so you would need to update the - // parent field on each child of this new node as creating a supernode - // causes the function to return before that is done. - - // I thought commenting out the bellow would make the tree less - // efficient but would still work. It doesn't. I should look into that - // to see if there is another bug. - - if ((tree->Parent()->Parent() == NULL) && - (tree->Parent()->NumChildren() == 1)) - { - // We make the root a supernode instead. - tree->Parent()->MaxNumChildren() = tree->MaxNumChildren() + - tree->AuxiliaryInfo().NormalNodeMaxNumChildren(); - tree->Parent()->children.resize(tree->Parent()->MaxNumChildren() + 1); - tree->Parent()->NumChildren() = tree->NumChildren(); - for (size_t i = 0; i < numChildren; ++i) - { - tree->Parent()->children[i] = sorted[i].second; - tree->Parent()->children[i]->Parent() = tree->Parent(); - tree->children[i] = NULL; - } - - delete tree; - delete treeTwo; - - return false; - } - - // If we don't have to worry about the root, we just enlarge this node. - tree->MaxNumChildren() += - tree->AuxiliaryInfo().NormalNodeMaxNumChildren(); - tree->children.resize(tree->MaxNumChildren() + 1); - tree->numChildren = numChildren; - for (size_t i = 0; i < numChildren; i++) - tree->Child(i).Parent() = tree; - - delete treeTwo; - return false; - } - } - - // Update the split history of each child. - tree->AuxiliaryInfo().SplitHistory().history[bestAxis] = true; - tree->AuxiliaryInfo().SplitHistory().lastDimension = bestAxis; - treeTwo->AuxiliaryInfo().SplitHistory().history[bestAxis] = true; - treeTwo->AuxiliaryInfo().SplitHistory().lastDimension = bestAxis; - - // Remove this node and insert treeOne and treeTwo - TreeType* par = tree->Parent(); - par->children[par->NumChildren()++] = treeTwo; - - // We only add one at a time, so we should only need to test for equality - // just in case, we use an assert. - if (!(par->NumChildren() <= par->MaxNumChildren() + 1)) - Log::Debug << "error " << par->NumChildren() << ", " - << par->MaxNumChildren() + 1 << std::endl; - assert(par->NumChildren() <= par->MaxNumChildren() + 1); - - if (par->NumChildren() == par->MaxNumChildren() + 1) - XTreeSplit::SplitNonLeafNode(par, relevels); - - // We have to update the children of each of these new nodes so that they - // record the correct parent. - for (size_t i = 0; i < treeTwo->NumChildren(); i++) - treeTwo->Child(i).Parent() = treeTwo; - - assert(tree->Parent()->NumChildren() <= - tree->Parent()->MaxNumChildren()); - assert(tree->Parent()->NumChildren() >= - tree->Parent()->MinNumChildren()); - assert(treeTwo->Parent()->NumChildren() <= - treeTwo->Parent()->MaxNumChildren()); - assert(treeTwo->Parent()->NumChildren() >= - treeTwo->Parent()->MinNumChildren()); - - return false; - } - else - { - // We are the root of the tree, so we need to create two children to add. - TreeType* treeOne = new TreeType(tree, tree->MaxNumChildren()); - TreeType* treeTwo = new TreeType(tree, tree->MaxNumChildren()); - const size_t numChildren = tree->NumChildren(); - tree->numChildren = 0; - - // Now as per the X-tree paper, we ensure that this split was good enough. - bool useMinOverlapSplit = false; - if (tiedOnOverlap) - { - if (overlapBestAreaAxis/areaBestAreaAxis < MAX_OVERLAP) - { - for (size_t i = 0; i < numChildren; i++) - { - if (i < bestAreaIndexOnBestAxis + tree->MinNumChildren()) - InsertNodeIntoTree(treeOne, sorted[i].second); - else - InsertNodeIntoTree(treeTwo, sorted[i].second); - } - } - else - useMinOverlapSplit = true; - } - else - { - if (overlapBestOverlapAxis/areaBestOverlapAxis < MAX_OVERLAP) - { - for (size_t i = 0; i < numChildren; i++) - { - if (i < bestOverlapIndexOnBestAxis + tree->MinNumChildren()) - InsertNodeIntoTree(treeOne, sorted[i].second); - else - InsertNodeIntoTree(treeTwo, sorted[i].second); - } - } - else - useMinOverlapSplit = true; - } - - // If the split was not good enough, then we try the minimal overlap split. - // If that fails, we create a "super node" (more accurately we resize this - // one to make it a super node). - if (useMinOverlapSplit) - { - // If there is a dimension that might work, try that. - if ((minOverlapSplitDimension != tree->Bound().Dim()) && - (bestScoreMinOverlapSplit / areaOfBestMinOverlapSplit < MAX_OVERLAP)) - { - std::vector> sorted2(numChildren); - if (minOverlapSplitUsesHi) - { - for (size_t i = 0; i < sorted2.size(); i++) - { - sorted2[i].first = sorted[i].second->Bound()[bestAxis].Hi(); - sorted2[i].second = sorted[i].second; - } - } - else - { - for (size_t i = 0; i < sorted2.size(); i++) - { - sorted2[i].first = sorted[i].second->Bound()[bestAxis].Lo(); - sorted2[i].second = sorted[i].second; - } - } - std::sort(sorted2.begin(), sorted2.end(), - PairComp); - - for (size_t i = 0; i < numChildren; i++) - { - if (i < bestIndexMinOverlapSplit + tree->MinNumChildren()) - InsertNodeIntoTree(treeOne, sorted2[i].second); - else - InsertNodeIntoTree(treeTwo, sorted2[i].second); - } - } - else - { - // Make this node a supernode. - tree->MaxNumChildren() += - tree->AuxiliaryInfo().NormalNodeMaxNumChildren(); - tree->children.resize(tree->MaxNumChildren() + 1); - tree->numChildren = numChildren; - for (size_t i = 0; i < numChildren; i++) - tree->Child(i).Parent() = tree; - - delete treeOne; - delete treeTwo; - return false; - } - } - - // Update the split history of each child. - treeOne->AuxiliaryInfo().SplitHistory().history[bestAxis] = true; - treeOne->AuxiliaryInfo().SplitHistory().lastDimension = bestAxis; - treeTwo->AuxiliaryInfo().SplitHistory().history[bestAxis] = true; - treeTwo->AuxiliaryInfo().SplitHistory().lastDimension = bestAxis; - - // Remove this node and insert treeOne and treeTwo - tree->children[0] = treeOne; - tree->children[1] = treeTwo; - tree->numChildren = 2; - tree->numDescendants = treeOne->numDescendants + treeTwo->numDescendants; - - // We have to update the children of each of these new nodes so that they - // record the correct parent. - for (size_t i = 0; i < treeOne->NumChildren(); ++i) - treeOne->Child(i).Parent() = treeOne; - for (size_t i = 0; i < treeTwo->NumChildren(); i++) - treeTwo->Child(i).Parent() = treeTwo; - - return false; - } -} - -/** - * Insert a node into another node. Expanding the bounds and updating the - * numberOfChildren. - */ -template -void XTreeSplit::InsertNodeIntoTree(TreeType* destTree, TreeType* srcNode) -{ - destTree->Bound() |= srcNode->Bound(); - destTree->numDescendants += srcNode->numDescendants; - destTree->children[destTree->NumChildren()++] = srcNode; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/space_split/hyperplane.hpp b/src/sdk/mlpack/include/mlpack/core/tree/space_split/hyperplane.hpp deleted file mode 100644 index 92af587f3..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/space_split/hyperplane.hpp +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @file hyperplane.hpp - * @author Marcos Pividori - * - * Definition of Hyperplane and AxisOrthogonalHyperplane. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_HYPERPLANE_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_HYPERPLANE_HPP - -#include -#include "projection_vector.hpp" - -namespace mlpack { -namespace tree { - -/** - * HyperplaneBase defines a splitting hyperplane based on a projection vector - * and projection value. - * - * @tparam BoundT The bound type considered. - * @tparam ProjVectorT Type of projection vector (AxisParallelProjVector, - * ProjVector). - */ -template -class HyperplaneBase -{ - public: - //! Useful typedef for the bound type. - typedef BoundT BoundType; - //! Useful typedef for the projection vector type. - typedef ProjVectorT ProjVectorType; - - private: - //! Projection vector. - ProjVectorType projVect; - - //! Projection value that determines the decision boundary. - double splitVal; - - public: - /** - * Empty Constructor. By default will consider all points to the left. - */ - HyperplaneBase() : - splitVal(DBL_MAX) - {}; - - /** - * Create the hyperplane with the specified projection vector and split value. - * - * @param projVect Projection vector. - * @param splitVal Split value. - */ - HyperplaneBase(const ProjVectorType& projVect, double splitVal) : - projVect(projVect), - splitVal(splitVal) - {}; - - /** - * Project the given point on the projection vector and subtract the - * split value. - * - * @param point Point to be projected. - */ - template - double Project(const VecType& point, - typename std::enable_if_t::value>* = 0) const - { - if (splitVal == DBL_MAX) - return 0; - return projVect.Project(point) - splitVal; - }; - - /** - * Determine if the given point is to the left of the hyperplane, this means - * if the projection over the projection vector is negative or zero. - * - * @param point Point to be analyzed. - */ - template - bool Left(const VecType& point, - typename std::enable_if_t::value>* = 0) const - { - return Project(point) <= 0; - }; - - /** - * Determine if the given point is to the right of the hyperplane, this means - * if the projection over the projection vector is positive. - * - * @param point Point to be analyzed. - */ - template - bool Right(const VecType& point, - typename std::enable_if_t::value>* = 0) const - { - return Project(point) > 0; - }; - - /** - * Determine if the given bound is to the left of the hyperplane. - * - * @param point Bound to be analyzed. - */ - bool Left(const BoundType& bound) const - { - if (splitVal == DBL_MAX) - return true; - return projVect.Project(bound).Hi() <= splitVal; - }; - - /** - * Determine if the given bound is to the right of the hyperplane. - * - * @param point Bound to be analyzed. - */ - bool Right(const BoundType& bound) const - { - if (splitVal == DBL_MAX) - return false; - return projVect.Project(bound).Lo() > splitVal; - }; - - /** - * Serialization. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(projVect); - ar & BOOST_SERIALIZATION_NVP(splitVal); - }; -}; - -/** - * AxisOrthogonalHyperplane represents a hyperplane orthogonal to an axis. - */ -template -using AxisOrthogonalHyperplane = HyperplaneBase, - AxisParallelProjVector>; - -/** - * Hyperplane represents a general hyperplane (not necessarily axis-orthogonal). - */ -template -using Hyperplane = HyperplaneBase, ProjVector>; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/space_split/mean_space_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/space_split/mean_space_split.hpp deleted file mode 100644 index 622dae711..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/space_split/mean_space_split.hpp +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file mean_space_split.hpp - * @author Marcos Pividori - * - * Definition of MeanSpaceSplit, to create a splitting hyperplane considering - * the mean of the values in a certain projection. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_MEAN_SPACE_SPLIT_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_MEAN_SPACE_SPLIT_HPP - -#include -#include "hyperplane.hpp" - -namespace mlpack { -namespace tree { - -template -class MeanSpaceSplit -{ - public: - /** - * Create a splitting hyperplane considering the mean of the values in a - * certain projection. - * - * @param bound The bound used for this node. - * @param data The dataset used by the tree. - * @param points Vector of indexes of points to be considered. - * @param hyp Resulting splitting hyperplane. - * @return Flag to determine if split is possible. - */ - template - static bool SplitSpace( - const typename HyperplaneType::BoundType& bound, - const MatType& data, - const arma::Col& points, - HyperplaneType& hyp); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "mean_space_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/space_split/mean_space_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/space_split/mean_space_split_impl.hpp deleted file mode 100644 index 158ed5bb8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/space_split/mean_space_split_impl.hpp +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file mean_space_split_impl.hpp - * @author Marcos Pividori - * - * Implementation of MeanSpaceSplit, to create a splitting hyperplane - * considering the midpoint/mean of the values in a certain projection. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_MEAN_SPACE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_MEAN_SPACE_SPLIT_IMPL_HPP - -#include "mean_space_split.hpp" -#include "space_split.hpp" - -namespace mlpack { -namespace tree { - -template -template -bool MeanSpaceSplit::SplitSpace( - const typename HyperplaneType::BoundType& bound, - const MatType& data, - const arma::Col& points, - HyperplaneType& hyp) -{ - typename HyperplaneType::ProjVectorType projVector; - double midValue; - - if (!SpaceSplit::GetProjVector(bound, data, points, - projVector, midValue)) - return false; - - double splitVal = 0.0; - for (size_t i = 0; i < points.n_elem; i++) - splitVal += projVector.Project(data.col(points[i])); - splitVal /= points.n_elem; - - hyp = HyperplaneType(projVector, splitVal); - - return true; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/space_split/midpoint_space_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/space_split/midpoint_space_split.hpp deleted file mode 100644 index 58266bb50..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/space_split/midpoint_space_split.hpp +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file midpoing_space_split.hpp - * @author Marcos Pividori - * - * Definition of MidpointSpaceSplit, to create a splitting hyperplane - * considering the midpoint of the values in a certain projection. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_MIDPOINT_SPACE_SPLIT_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_MIDPOINT_SPACE_SPLIT_HPP - -#include -#include "hyperplane.hpp" - -namespace mlpack { -namespace tree { - -template -class MidpointSpaceSplit -{ - public: - /** - * Create a splitting hyperplane considering the midpoint of the values in a - * certain projection. - * - * @param bound The bound used for this node. - * @param data The dataset used by the tree. - * @param points Vector of indexes of points to be considered. - * @param hyp Resulting splitting hyperplane. - * @return Flag to determine if split is possible. - */ - template - static bool SplitSpace( - const typename HyperplaneType::BoundType& bound, - const MatType& data, - const arma::Col& points, - HyperplaneType& hyp); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "midpoint_space_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/space_split/midpoint_space_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/space_split/midpoint_space_split_impl.hpp deleted file mode 100644 index 80eca935a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/space_split/midpoint_space_split_impl.hpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @file midpoint_space_split_impl.hpp - * @author Marcos Pividori - * - * Implementation of MidpointSpaceSplit, to create a splitting hyperplane - * considering the midpoint of the values in a certain projection. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_MIDPOINT_SPACE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_MIDPOINT_SPACE_SPLIT_IMPL_HPP - -#include "midpoint_space_split.hpp" -#include "space_split.hpp" - -namespace mlpack { -namespace tree { - -template -template -bool MidpointSpaceSplit::SplitSpace( - const typename HyperplaneType::BoundType& bound, - const MatType& data, - const arma::Col& points, - HyperplaneType& hyp) -{ - typename HyperplaneType::ProjVectorType projVector; - double midValue; - - if (!SpaceSplit::GetProjVector(bound, data, points, - projVector, midValue)) - return false; - - hyp = HyperplaneType(projVector, midValue); - - return true; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/space_split/projection_vector.hpp b/src/sdk/mlpack/include/mlpack/core/tree/space_split/projection_vector.hpp deleted file mode 100644 index 63fd96925..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/space_split/projection_vector.hpp +++ /dev/null @@ -1,154 +0,0 @@ -/** - * @file projection_vector.hpp - * @author Marcos Pividori - * - * Definition of ProjVector and AxisParallelProjVector. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_PROJECTION_VECTOR_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_PROJECTION_VECTOR_HPP - -#include -#include "../bounds.hpp" -namespace mlpack { -namespace tree { - -/** - * AxisParallelProjVector defines an axis-parallel projection vector. - * We can efficiently project points, simply analyzing a specific dimension. - */ -class AxisParallelProjVector -{ - //! Dimension considered. - size_t dim; - - public: - /** - * Create the projection vector based on the specified dimension. - * - * @param dim Dimension to be considered. - */ - AxisParallelProjVector(size_t dim = 0) : - dim(dim) - {}; - - /** - * Project the given point on the projection vector. - * - * @param point Point to be projected. - */ - template - double Project(const VecType& point, - typename std::enable_if_t::value>* = 0) const - { - return point[dim]; - }; - - /** - * Project the given hrect bound on the projection vector. - * - * @param bound Bound to be projected. - * @return Range of projected values. - */ - template - math::RangeType Project( - const bound::HRectBound& bound) const - { - return bound[dim]; - }; - - /** - * Project the given ball bound on the projection vector. - * - * @param bound Bound to be projected. - * @return Range of projected values. - */ - template - math::RangeType Project( - const bound::BallBound& bound) const - { - return bound[dim]; - }; - - /** - * Serialization. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(dim); - }; -}; - -/** - * ProjVector defines a general projection vector (not necessarily - * axis-parallel). - */ -class ProjVector -{ - //! Projection vector. - arma::vec projVect; - - public: - /** - * Empty Constructor. - */ - ProjVector() : - projVect() - {}; - - /** - * Create the projection vector based on the specified vector. - * - * @param vect Vector to be considered. - */ - ProjVector(const arma::vec& vect) : - projVect(arma::normalise(vect)) - {}; - - /** - * Project the given point on the projection vector. - * - * @param point Point to be projected. - */ - template - double Project(const VecType& point, - typename std::enable_if_t::value>* = 0) const - { - return arma::dot(point, projVect); - }; - - /** - * Project the given ball bound on the projection vector. - * - * @param bound Bound to be projected. - * @return Range of projected values. - */ - template - math::RangeType Project( - const bound::BallBound& bound) const - { - typedef typename VecType::elem_type ElemType; - const double center = Project(bound.Center()); - const ElemType radius = bound.Radius(); - return math::RangeType(center - radius, center + radius); - }; - - /** - * Serialization. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(projVect); - }; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/space_split/space_split.hpp b/src/sdk/mlpack/include/mlpack/core/tree/space_split/space_split.hpp deleted file mode 100644 index 4982d67cb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/space_split/space_split.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file space_split.hpp - * @author Marcos Pividori - * - * Definition of SpaceSplit, implementing some methods to create a projection - * vector based on a given set of points. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_SPACE_SPLIT_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_SPACE_SPLIT_HPP - -#include -#include "hyperplane.hpp" - -namespace mlpack { -namespace tree { - -template -class SpaceSplit -{ - public: - /** - * Create a projection vector based on the given set of point. This special - * case will create an axis-parallel projection vector in the dimension that - * has the maximum width. - * - * @param bound The bound used for this node. - * @param data The dataset used by the tree. - * @param points Vector of indexes of points to be considered. - * @param projVector Resulting axis-parallel projection vector. - * @param midValue Mid value in the chosen projection. - * @return Flag to determine if it is possible. - */ - static bool GetProjVector( - const bound::HRectBound& bound, - const MatType& data, - const arma::Col& points, - AxisParallelProjVector& projVector, - double& midValue); - - /** - * Create a projection vector based on the given set of point. We efficiently - * estimate the farthest pair of points in the given set: p and q, and then - * consider the projection vector (q - p). - * - * @param bound The bound used for this node. - * @param data The dataset used by the tree. - * @param points Vector of indexes of points to be considered. - * @param projVector Resulting projection vector. - * @param midValue Mid value in the chosen projection. - * @return Flag to determine if it is possible. - */ - template - static bool GetProjVector( - const BoundType& bound, - const MatType& data, - const arma::Col& points, - ProjVector& projVector, - double& midValue); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "space_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/space_split/space_split_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/space_split/space_split_impl.hpp deleted file mode 100644 index 98f4ee0e4..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/space_split/space_split_impl.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @file space_split_impl.hpp - * @author Marcos Pividori - * - * Implementation of SpaceSplit, to create a projection vector based on a given - * set of points. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_SPACE_SPLIT_IMPL_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_SPACE_SPLIT_IMPL_HPP - -#include "space_split.hpp" - -namespace mlpack { -namespace tree { - -template -bool SpaceSplit::GetProjVector( - const bound::HRectBound& bound, - const MatType& data, - const arma::Col& /* points */, - AxisParallelProjVector& projVector, - double& midValue) -{ - // Get the dimension that has the maximum width. - size_t splitDim = data.n_rows; // Indicate invalid. - double maxWidth = -1; - - for (size_t d = 0; d < data.n_rows; d++) - { - const double width = bound[d].Width(); - - if (width > maxWidth) - { - maxWidth = width; - splitDim = d; - } - } - - if (maxWidth <= 0) // All these points are the same. - return false; - - projVector = AxisParallelProjVector(splitDim); - - midValue = bound[splitDim].Mid(); - - return true; -} - -template -template -bool SpaceSplit::GetProjVector( - const BoundType& /* bound */, - const MatType& data, - const arma::Col& points, - ProjVector& projVector, - double& midValue) -{ - MetricType metric; - - // Efficiently estimate the farthest pair of points in the given set. - size_t fst = points[rand() % points.n_elem]; - size_t snd = points[0]; - double max = metric.Evaluate(data.col(fst), data.col(snd)); - - for (size_t i = 1; i < points.n_elem; i++) - { - double dist = metric.Evaluate(data.col(fst), data.col(points[i])); - if (dist > max) - { - max = dist; - snd = points[i]; - } - } - - std::swap(fst, snd); - - for (size_t i = 0; i < points.n_elem; i++) - { - double dist = metric.Evaluate(data.col(fst), data.col(points[i])); - if (dist > max) - { - max = dist; - snd = points[i]; - } - } - - if (max == 0) // All these points are the same. - return false; - - // Calculate the normalized projection vector. - projVector = ProjVector(data.col(snd) - data.col(fst)); - - arma::vec midPoint = (data.col(snd) + data.col(fst)) / 2; - - midValue = projVector.Project(midPoint); - - return true; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree.hpp deleted file mode 100644 index 0f21a7064..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree.hpp +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @file spill_tree.hpp - * @author Marcos Pividori - * - * Include all the necessary files to use the SpillTree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_HPP - -#include -#include "bounds.hpp" -#include "spill_tree/is_spill_tree.hpp" -#include "spill_tree/spill_tree.hpp" -#include "spill_tree/spill_single_tree_traverser.hpp" -#include "spill_tree/spill_single_tree_traverser_impl.hpp" -#include "spill_tree/spill_dual_tree_traverser.hpp" -#include "spill_tree/spill_dual_tree_traverser_impl.hpp" -#include "spill_tree/traits.hpp" -#include "spill_tree/typedef.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/is_spill_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/is_spill_tree.hpp deleted file mode 100644 index 4548ffc6e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/is_spill_tree.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @file is_spill_tree.hpp - * - * Definition of IsSpillTree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_IS_SPILL_TREE_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_IS_SPILL_TREE_HPP - -#include "spill_tree.hpp" - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -// Useful struct when specific behaviour for SpillTrees is required. -template -struct IsSpillTree -{ - static const bool value = false; -}; - -// Specialization for SpillTree. -template - class HyperplaneType, - template - class SplitType> -struct IsSpillTree> -{ - static const bool value = true; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_dual_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_dual_tree_traverser.hpp deleted file mode 100644 index 210dea77a..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_dual_tree_traverser.hpp +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @file spill_dual_tree_traverser.hpp - * @author Ryan Curtin - * @author Marcos Pividori - * - * Defines the SpillDualTreeTraverser for the SpillTree tree type. This is a - * nested class of SpillTree which traverses two trees in a depth-first - * manner with a given set of rules which indicate the branches which can be - * pruned and the order in which to recurse. - * The Defeatist template parameter determines if the traversers must do - * defeatist search on overlapping nodes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_SPILL_DUAL_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_SPILL_DUAL_TREE_TRAVERSER_HPP - -#include - -#include "spill_tree.hpp" - -namespace mlpack { -namespace tree { - -template class HyperplaneType, - template - class SplitType> -template -class SpillTree:: - SpillDualTreeTraverser -{ - public: - /** - * Instantiate the dual-tree traverser with the given rule set. - */ - SpillDualTreeTraverser(RuleType& rule); - - /** - * Traverse the two trees. This does not reset the number of prunes. - * - * @param queryNode The query node to be traversed. - * @param referenceNode The reference node to be traversed. - * @param score The score of the current node combination. - */ - void Traverse(SpillTree& queryNode, - SpillTree& referenceNode); - - //! Get the number of prunes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of prunes. - size_t& NumPrunes() { return numPrunes; } - - //! Get the number of visited combinations. - size_t NumVisited() const { return numVisited; } - //! Modify the number of visited combinations. - size_t& NumVisited() { return numVisited; } - - //! Get the number of times a node combination was scored. - size_t NumScores() const { return numScores; } - //! Modify the number of times a node combination was scored. - size_t& NumScores() { return numScores; } - - //! Get the number of times a base case was calculated. - size_t NumBaseCases() const { return numBaseCases; } - //! Modify the number of times a base case was calculated. - size_t& NumBaseCases() { return numBaseCases; } - - private: - //! Reference to the rules with which the trees will be traversed. - RuleType& rule; - - //! The number of prunes. - size_t numPrunes; - - //! The number of node combinations that have been visited during traversal. - size_t numVisited; - - //! The number of times a node combination was scored. - size_t numScores; - - //! The number of times a base case was calculated. - size_t numBaseCases; - - //! Traversal information, held in the class so that it isn't continually - //! being reallocated. - typename RuleType::TraversalInfoType traversalInfo; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "spill_dual_tree_traverser_impl.hpp" - -#endif // MLPACK_CORE_TREE_SPILL_TREE_SPILL_DUAL_TREE_TRAVERSER_HPP - diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_dual_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_dual_tree_traverser_impl.hpp deleted file mode 100644 index 1db72f510..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_dual_tree_traverser_impl.hpp +++ /dev/null @@ -1,417 +0,0 @@ -/** - * @file spill_dual_tree_traverser_impl.hpp - * @author Ryan Curtin - * @author Marcos Pividori - * - * Implementation of the SpillDualTreeTraverser for SpillTree. This is a way - * to perform a dual-tree traversal of two trees. The trees must be the same - * type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_SPILL_DUAL_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_SPILL_DUAL_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "spill_dual_tree_traverser.hpp" - -namespace mlpack { -namespace tree { - -template class HyperplaneType, - template - class SplitType> -template -SpillTree:: -SpillDualTreeTraverser::SpillDualTreeTraverser( - RuleType& rule) : - rule(rule), - numPrunes(0), - numVisited(0), - numScores(0), - numBaseCases(0) -{ /* Nothing to do. */ } - -template class HyperplaneType, - template - class SplitType> -template -void SpillTree:: -SpillDualTreeTraverser::Traverse( - SpillTree& - queryNode, - SpillTree& - referenceNode) -{ - // Increment the visit counter. - ++numVisited; - - // Store the current traversal info. - traversalInfo = rule.TraversalInfo(); - - // If both are leaves, we must evaluate the base case. - if (queryNode.IsLeaf() && referenceNode.IsLeaf()) - { - // Loop through each of the points in each node. - const size_t queryEnd = queryNode.NumPoints(); - const size_t refEnd = referenceNode.NumPoints(); - for (size_t query = 0; query < queryEnd; ++query) - { - const size_t queryIndex = queryNode.Point(query); - // See if we need to investigate this point. Restore the traversal - // information first. - rule.TraversalInfo() = traversalInfo; - const double childScore = rule.Score(queryIndex, referenceNode); - - if (childScore == DBL_MAX) - continue; // We can't improve this particular point. - - for (size_t ref = 0; ref < refEnd; ++ref) - rule.BaseCase(queryIndex, referenceNode.Point(ref)); - - numBaseCases += refEnd; - } - } - else if (((!queryNode.IsLeaf()) && referenceNode.IsLeaf()) || - (queryNode.NumDescendants() > 3 * referenceNode.NumDescendants() && - !queryNode.IsLeaf() && !referenceNode.IsLeaf())) - { - // We have to recurse down the query node. In this case the recursion order - // does not matter. - const double leftScore = rule.Score(*queryNode.Left(), referenceNode); - ++numScores; - - if (leftScore != DBL_MAX) - Traverse(*queryNode.Left(), referenceNode); - else - ++numPrunes; - - // Before recursing, we have to set the traversal information correctly. - rule.TraversalInfo() = traversalInfo; - const double rightScore = rule.Score(*queryNode.Right(), referenceNode); - ++numScores; - - if (rightScore != DBL_MAX) - Traverse(*queryNode.Right(), referenceNode); - else - ++numPrunes; - } - else if (queryNode.IsLeaf() && (!referenceNode.IsLeaf())) - { - if (Defeatist && referenceNode.Overlap()) - { - // If referenceNode is a overlapping node let's do defeatist search. - size_t bestChild = rule.GetBestChild(queryNode, referenceNode); - if (bestChild < referenceNode.NumChildren()) - { - Traverse(queryNode, referenceNode.Child(bestChild)); - ++numPrunes; - } - else - { - // If we can't decide which child node to traverse, this means that - // queryNode is at both sides of the splitting hyperplane. So, as - // queryNode is a leafNode, all we can do is single tree search for each - // point in the query node. - const size_t queryEnd = queryNode.NumPoints(); - DefeatistSingleTreeTraverser st(rule); - // Loop through each of the points in query node. - for (size_t query = 0; query < queryEnd; ++query) - { - const size_t queryIndex = queryNode.Point(query); - // See if we need to investigate this point. - const double childScore = rule.Score(queryIndex, referenceNode); - - if (childScore == DBL_MAX) - continue; // We can't improve this particular point. - - st.Traverse(queryIndex, referenceNode); - } - } - } - else - { - // We have to recurse down the reference node. In this case the recursion - // order does matter. Before recursing, though, we have to set the - // traversal information correctly. - double leftScore = rule.Score(queryNode, *referenceNode.Left()); - typename RuleType::TraversalInfoType leftInfo = rule.TraversalInfo(); - rule.TraversalInfo() = traversalInfo; - double rightScore = rule.Score(queryNode, *referenceNode.Right()); - numScores += 2; - - if (leftScore < rightScore) - { - // Recurse to the left. Restore the left traversal info. Store the - // right traversal info. - traversalInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(queryNode, *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(queryNode, *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = traversalInfo; - Traverse(queryNode, *referenceNode.Right()); - } - else - ++numPrunes; - } - else if (rightScore < leftScore) - { - // Recurse to the right. - Traverse(queryNode, *referenceNode.Right()); - - // Is it still valid to recurse to the left? - leftScore = rule.Rescore(queryNode, *referenceNode.Left(), leftScore); - - if (leftScore != DBL_MAX) - { - // Restore the left traversal info. - rule.TraversalInfo() = leftInfo; - Traverse(queryNode, *referenceNode.Left()); - } - else - ++numPrunes; - } - else // leftScore is equal to rightScore. - { - if (leftScore == DBL_MAX) - { - numPrunes += 2; - } - else - { - // Choose the left first. Restore the left traversal info. Store the - // right traversal info. - traversalInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(queryNode, *referenceNode.Left()); - - rightScore = rule.Rescore(queryNode, *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = traversalInfo; - Traverse(queryNode, *referenceNode.Right()); - } - else - ++numPrunes; - } - } - } - } - else - { - if (Defeatist && referenceNode.Overlap()) - { - // If referenceNode is a overlapping node let's do defeatist search. - size_t bestChild = rule.GetBestChild(*queryNode.Left(), referenceNode); - if (bestChild < referenceNode.NumChildren()) - { - Traverse(*queryNode.Left(), referenceNode.Child(bestChild)); - ++numPrunes; - } - else - { - // If we can't decide which child node to traverse, this means that - // queryNode.Left() is at both sides of the splitting hyperplane. So, - // let's recurse down only the query node. - Traverse(*queryNode.Left(), referenceNode); - } - - bestChild = rule.GetBestChild(*queryNode.Right(), referenceNode); - if (bestChild < referenceNode.NumChildren()) - { - Traverse(*queryNode.Right(), referenceNode.Child(bestChild)); - ++numPrunes; - } - else - { - // If we can't decide which child node to traverse, this means that - // queryNode.Right() is at both sides of the splitting hyperplane. So, - // let's recurse down only the query node. - Traverse(*queryNode.Right(), referenceNode); - } - } - else - { - // We have to recurse down both query and reference nodes. Because the - // query descent order does not matter, we will go to the left query child - // first. Before recursing, we have to set the traversal information - // correctly. - double leftScore = rule.Score(*queryNode.Left(), *referenceNode.Left()); - typename RuleType::TraversalInfoType leftInfo = rule.TraversalInfo(); - rule.TraversalInfo() = traversalInfo; - double rightScore = rule.Score(*queryNode.Left(), *referenceNode.Right()); - typename RuleType::TraversalInfoType rightInfo; - numScores += 2; - - if (leftScore < rightScore) - { - // Recurse to the left. Restore the left traversal info. Store the - // right traversal info. - rightInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Left(), *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(*queryNode.Left(), *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = rightInfo; - Traverse(*queryNode.Left(), *referenceNode.Right()); - } - else - ++numPrunes; - } - else if (rightScore < leftScore) - { - // Recurse to the right. - Traverse(*queryNode.Left(), *referenceNode.Right()); - - // Is it still valid to recurse to the left? - leftScore = rule.Rescore(*queryNode.Left(), *referenceNode.Left(), - leftScore); - - if (leftScore != DBL_MAX) - { - // Restore the left traversal info. - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Left(), *referenceNode.Left()); - } - else - ++numPrunes; - } - else - { - if (leftScore == DBL_MAX) - { - numPrunes += 2; - } - else - { - // Choose the left first. Restore the left traversal info and store - // the right traversal info. - rightInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Left(), *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(*queryNode.Left(), *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal information. - rule.TraversalInfo() = rightInfo; - Traverse(*queryNode.Left(), *referenceNode.Right()); - } - else - ++numPrunes; - } - } - - // Restore the main traversal information. - rule.TraversalInfo() = traversalInfo; - - // Now recurse down the right query node. - leftScore = rule.Score(*queryNode.Right(), *referenceNode.Left()); - leftInfo = rule.TraversalInfo(); - rule.TraversalInfo() = traversalInfo; - rightScore = rule.Score(*queryNode.Right(), *referenceNode.Right()); - numScores += 2; - - if (leftScore < rightScore) - { - // Recurse to the left. Restore the left traversal info. Store the - // right traversal info. - rightInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Right(), *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(*queryNode.Right(), *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = rightInfo; - Traverse(*queryNode.Right(), *referenceNode.Right()); - } - else - ++numPrunes; - } - else if (rightScore < leftScore) - { - // Recurse to the right. - Traverse(*queryNode.Right(), *referenceNode.Right()); - - // Is it still valid to recurse to the left? - leftScore = rule.Rescore(*queryNode.Right(), *referenceNode.Left(), - leftScore); - - if (leftScore != DBL_MAX) - { - // Restore the left traversal info. - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Right(), *referenceNode.Left()); - } - else - ++numPrunes; - } - else - { - if (leftScore == DBL_MAX) - { - numPrunes += 2; - } - else - { - // Choose the left first. Restore the left traversal info. Store the - // right traversal info. - rightInfo = rule.TraversalInfo(); - rule.TraversalInfo() = leftInfo; - Traverse(*queryNode.Right(), *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(*queryNode.Right(), *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - { - // Restore the right traversal info. - rule.TraversalInfo() = rightInfo; - Traverse(*queryNode.Right(), *referenceNode.Right()); - } - else - ++numPrunes; - } - } - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_SPILL_TREE_SPILL_DUAL_TREE_TRAVERSER_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_single_tree_traverser.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_single_tree_traverser.hpp deleted file mode 100644 index 99794365e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_single_tree_traverser.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @file spill_single_tree_traverser.hpp - * @author Ryan Curtin - * @author Marcos Pividori - * - * A nested class of SpillTree which traverses the entire tree with a - * given set of rules which indicate the branches which can be pruned and the - * order in which to recurse. This traverser is a depth-first traverser. - * The Defeatist template parameter determines if the traversers must do - * defeatist search on overlapping nodes. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_SPILL_SINGLE_TREE_TRAVERSER_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_SPILL_SINGLE_TREE_TRAVERSER_HPP - -#include - -#include "spill_tree.hpp" - -namespace mlpack { -namespace tree { - -template class HyperplaneType, - template - class SplitType> -template -class SpillTree:: - SpillSingleTreeTraverser -{ - public: - /** - * Instantiate the single tree traverser with the given rule set. - */ - SpillSingleTreeTraverser(RuleType& rule); - - /** - * Traverse the tree with the given point. - * - * @param queryIndex The index of the point in the query set which is being - * used as the query point. - * @param referenceNode The tree node to be traversed. - */ - void Traverse(const size_t queryIndex, SpillTree& referenceNode); - - //! Get the number of prunes. - size_t NumPrunes() const { return numPrunes; } - //! Modify the number of prunes. - size_t& NumPrunes() { return numPrunes; } - - private: - //! Reference to the rules with which the tree will be traversed. - RuleType& rule; - - //! The number of nodes which have been pruned during traversal. - size_t numPrunes; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "spill_single_tree_traverser_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_single_tree_traverser_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_single_tree_traverser_impl.hpp deleted file mode 100644 index b8478bb40..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_single_tree_traverser_impl.hpp +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @file spill_single_tree_traverser_impl.hpp - * @author Ryan Curtin - * @author Marcos Pividori - * - * A nested class of SpillTree which traverses the entire tree with a - * given set of rules which indicate the branches which can be pruned and the - * order in which to recurse. This traverser is a depth-first traverser. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_SPILL_SINGLE_TREE_TRAVERSER_IMPL_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_SPILL_SINGLE_TREE_TRAVERSER_IMPL_HPP - -// In case it hasn't been included yet. -#include "spill_single_tree_traverser.hpp" - -namespace mlpack { -namespace tree { - -template class HyperplaneType, - template - class SplitType> -template -SpillTree:: -SpillSingleTreeTraverser::SpillSingleTreeTraverser( - RuleType& rule) : - rule(rule), - numPrunes(0) -{ /* Nothing to do. */ } - -template class HyperplaneType, - template - class SplitType> -template -void SpillTree:: -SpillSingleTreeTraverser::Traverse( - const size_t queryIndex, - SpillTree& - referenceNode) -{ - // If we are a leaf, run the base case as necessary. - if (referenceNode.IsLeaf()) - { - for (size_t i = 0; i < referenceNode.NumPoints(); ++i) - rule.BaseCase(queryIndex, referenceNode.Point(i)); - } - else - { - if (Defeatist && referenceNode.Overlap()) - { - // If referenceNode is a overlapping node we do defeatist search. - size_t bestChild = rule.GetBestChild(queryIndex, referenceNode); - Traverse(queryIndex, referenceNode.Child(bestChild)); - ++numPrunes; - } - else - { - // If either score is DBL_MAX, we do not recurse into that node. - double leftScore = rule.Score(queryIndex, *referenceNode.Left()); - double rightScore = rule.Score(queryIndex, *referenceNode.Right()); - - if (leftScore < rightScore) - { - // Recurse to the left. - Traverse(queryIndex, *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(queryIndex, *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - Traverse(queryIndex, *referenceNode.Right()); // Recurse to the right. - else - ++numPrunes; - } - else if (rightScore < leftScore) - { - // Recurse to the right. - Traverse(queryIndex, *referenceNode.Right()); - - // Is it still valid to recurse to the left? - leftScore = rule.Rescore(queryIndex, *referenceNode.Left(), leftScore); - - if (leftScore != DBL_MAX) - Traverse(queryIndex, *referenceNode.Left()); // Recurse to the left. - else - ++numPrunes; - } - else // leftScore is equal to rightScore. - { - if (leftScore == DBL_MAX) - { - numPrunes += 2; // Pruned both left and right. - } - else - { - // Choose the left first. - Traverse(queryIndex, *referenceNode.Left()); - - // Is it still valid to recurse to the right? - rightScore = rule.Rescore(queryIndex, *referenceNode.Right(), - rightScore); - - if (rightScore != DBL_MAX) - Traverse(queryIndex, *referenceNode.Right()); - else - ++numPrunes; - } - } - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_tree.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_tree.hpp deleted file mode 100644 index 9ff9e8d6b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_tree.hpp +++ /dev/null @@ -1,484 +0,0 @@ -/** - * @file spill_tree.hpp - * - * Definition of generalized hybrid spill tree (SpillTree). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_SPILL_TREE_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_SPILL_TREE_HPP - -#include -#include "../space_split/midpoint_space_split.hpp" -#include "../statistic.hpp" - -namespace mlpack { -namespace tree /** Trees and tree-building procedures. */ { - -/** - * A hybrid spill tree is a variant of binary space trees in which the children - * of a node can "spill over" each other, and contain shared datapoints. - * - * Two new separating planes lplane and rplane are defined, both of which are - * parallel to the original decision boundary and at a distance tau from it. - * The region between lplane and rplane is called "overlapping buffer". - * - * For each node, we first split the points considering the overlapping buffer. - * If either of its children contains more than rho fraction of the total points - * we undo the overlapping splitting. Instead a conventional partition is used. - * In this way, we can ensure that each split reduces the number of points of a - * node by at least a constant factor. - * - * This particular tree does not allow growth, so you cannot add or delete nodes - * from it. If you need to add or delete a node, the better procedure is to - * rebuild the tree entirely. - * - * Three runtime parameters are required in the constructor: - * - maxLeafSize: Max leaf size to be used. - * - tau: Overlapping size. - * - rho: Balance threshold. - * - * For more information on spill trees, see - * - * @code - * @inproceedings{ - * author = {Ting Liu, Andrew W. Moore, Alexander Gray and Ke Yang}, - * title = {An Investigation of Practical Approximate Nearest Neighbor - * Algorithms}, - * booktitle = {Advances in Neural Information Processing Systems 17}, - * year = {2005}, - * pages = {825--832} - * } - * @endcode - * - * @tparam MetricType The metric used for tree-building. - * @tparam StatisticType Extra data contained in the node. See statistic.hpp - * for the necessary skeleton interface. - * @tparam MatType The dataset class. - * @tparam HyperplaneType The splitting hyperplane class. - * @tparam SplitType The class that partitions the dataset/points at a - * particular node into two parts. Its definition decides the way this split - * is done. - */ -template - class HyperplaneType = AxisOrthogonalHyperplane, - template - class SplitType = MidpointSpaceSplit> -class SpillTree -{ - public: - //! So other classes can use TreeType::Mat. - typedef MatType Mat; - //! The type of element held in MatType. - typedef typename MatType::elem_type ElemType; - //! The bound type. - typedef typename HyperplaneType::BoundType BoundType; - - private: - //! The left child node. - SpillTree* left; - //! The right child node. - SpillTree* right; - //! The parent node (NULL if this is the root of the tree). - SpillTree* parent; - //! The number of points of the dataset contained in this node (and its - //! children). - size_t count; - //! The list of indexes of points contained in this node (non-null for - //! leaf nodes). - arma::Col* pointsIndex; - //! Flag to distinguish overlapping nodes from non-overlapping nodes. - bool overlappingNode; - //! Splitting hyperplane represented by this node. - HyperplaneType hyperplane; - //! The bound object for this node. - BoundType bound; - //! Any extra data contained in the node. - StatisticType stat; - //! The distance from the centroid of this node to the centroid of the parent. - ElemType parentDistance; - //! The worst possible distance to the furthest descendant, cached to speed - //! things up. - ElemType furthestDescendantDistance; - //! The minimum distance from the center to any edge of the bound. - ElemType minimumBoundDistance; - //! The dataset. If we are the root of the tree, we own the dataset and must - //! delete it. - const MatType* dataset; - //! If true, we own the dataset and need to destroy it in the destructor. - bool localDataset; - - //! A generic single-tree traverser for hybrid spill trees; see - //! spill_single_tree_traverser.hpp for implementation. The Defeatist - //! template parameter determines if the traverser must do defeatist search on - //! overlapping nodes. - template - class SpillSingleTreeTraverser; - - //! A generic dual-tree traverser for hybrid spill trees; see - //! spill_dual_tree_traverser.hpp for implementation. The Defeatist - //! template parameter determines if the traverser must do defeatist search on - //! overlapping nodes. - template - class SpillDualTreeTraverser; - - public: - //! A single-tree traverser for hybrid spill trees. - template - using SingleTreeTraverser = SpillSingleTreeTraverser; - - //! A defeatist single-tree traverser for hybrid spill trees. - template - using DefeatistSingleTreeTraverser = SpillSingleTreeTraverser; - - //! A dual-tree traverser for hybrid spill trees. - template - using DualTreeTraverser = SpillDualTreeTraverser; - - //! A defeatist dual-tree traverser for hybrid spill trees. - template - using DefeatistDualTreeTraverser = SpillDualTreeTraverser; - - /** - * Construct this as the root node of a hybrid spill tree using the given - * dataset. The dataset will not be modified during the building procedure - * (unlike BinarySpaceTree). - * - * @param data Dataset to create tree from. - * @param tau Overlapping size. - * @param maxLeafSize Size of each leaf in the tree. - * @param rho Balance threshold. - */ - SpillTree(const MatType& data, - const double tau = 0, - const size_t maxLeafSize = 20, - const double rho = 0.7); - - /** - * Construct this as the root node of a hybrid spill tree using the given - * dataset. This will take ownership of the data matrix; if you don't want - * this, consider using the constructor that takes a const reference to a - * dataset. - * - * @param data Dataset to create tree from. - * @param tau Overlapping size. - * @param maxLeafSize Size of each leaf in the tree. - * @param rho Balance threshold. - */ - SpillTree(MatType&& data, - const double tau = 0, - const size_t maxLeafSize = 20, - const double rho = 0.7); - - /** - * Construct this node as a child of the given parent, including the given - * list of points. This is used for recursive tree-building by the other - * constructors which don't specify point indices. - * - * @param parent Parent of this node. - * @param points Vector of indexes of points to be included in this node. - * @param tau Overlapping size. - * @param maxLeafSize Size of each leaf in the tree. - * @param rho Balance threshold. - */ - SpillTree(SpillTree* parent, - arma::Col& points, - const double tau = 0, - const size_t maxLeafSize = 20, - const double rho = 0.7); - - /** - * Create a hybrid spill tree by copying the other tree. Be careful! This - * can take a long time and use a lot of memory. - * - * @param other tree to be replicated. - */ - SpillTree(const SpillTree& other); - - /** - * Move constructor for a SpillTree; possess all the members of the given - * tree. - * - * @param other tree to be moved. - */ - SpillTree(SpillTree&& other); - - /** - * Initialize the tree from a boost::serialization archive. - * - * @param ar Archive to load tree from. Must be an iarchive, not an oarchive. - */ - template - SpillTree( - Archive& ar, - const typename std::enable_if_t* = 0); - - /** - * Deletes this node, deallocating the memory for the children and calling - * their destructors in turn. This will invalidate any pointers or references - * to any nodes which are children of this one. - */ - ~SpillTree(); - - //! Return the bound object for this node. - const BoundType& Bound() const { return bound; } - //! Return the bound object for this node. - BoundType& Bound() { return bound; } - - //! Return the statistic object for this node. - const StatisticType& Stat() const { return stat; } - //! Return the statistic object for this node. - StatisticType& Stat() { return stat; } - - //! Return whether or not this node is a leaf (true if it has no children). - bool IsLeaf() const; - - //! Gets the left child of this node. - SpillTree* Left() const { return left; } - //! Modify the left child of this node. - SpillTree*& Left() { return left; } - - //! Gets the right child of this node. - SpillTree* Right() const { return right; } - //! Modify the right child of this node. - SpillTree*& Right() { return right; } - - //! Gets the parent of this node. - SpillTree* Parent() const { return parent; } - //! Modify the parent of this node. - SpillTree*& Parent() { return parent; } - - //! Get the dataset which the tree is built on. - const MatType& Dataset() const { return *dataset; } - - //! Distinguish overlapping nodes from non-overlapping nodes. - bool Overlap() const { return overlappingNode; } - - //! Get the Hyperplane instance. - const HyperplaneType& Hyperplane() const { return hyperplane; } - - //! Get the metric that the tree uses. - MetricType Metric() const { return MetricType(); } - - //! Return the number of children in this node. - size_t NumChildren() const; - - /** - * Return the index of the nearest child node to the given query point (this - * is an efficient estimation based on the splitting hyperplane, the node - * returned is not necessarily the nearest). If this is a leaf node, it will - * return NumChildren() (invalid index). - */ - template - size_t GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0); - - /** - * Return the index of the furthest child node to the given query point (this - * is an efficient estimation based on the splitting hyperplane, the node - * returned is not necessarily the furthest). If this is a leaf node, it will - * return NumChildren() (invalid index). - */ - template - size_t GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>* = 0); - - /** - * Return the index of the nearest child node to the given query node (this - * is an efficient estimation based on the splitting hyperplane, the node - * returned is not necessarily the nearest). If it can't decide it will - * return NumChildren() (invalid index). - */ - size_t GetNearestChild(const SpillTree& queryNode); - - /** - * Return the index of the furthest child node to the given query node (this - * is an efficient estimation based on the splitting hyperplane, the node - * returned is not necessarily the furthest). If it can't decide it will - * return NumChildren() (invalid index). - */ - size_t GetFurthestChild(const SpillTree& queryNode); - - /** - * Return the furthest distance to a point held in this node. If this is not - * a leaf node, then the distance is 0 because the node holds no points. - */ - ElemType FurthestPointDistance() const; - - /** - * Return the furthest possible descendant distance. This returns the maximum - * distance from the centroid to the edge of the bound and not the empirical - * quantity which is the actual furthest descendant distance. So the actual - * furthest descendant distance may be less than what this method returns (but - * it will never be greater than this). - */ - ElemType FurthestDescendantDistance() const; - - //! Return the minimum distance from the center of the node to any bound edge. - ElemType MinimumBoundDistance() const; - - //! Return the distance from the center of this node to the center of the - //! parent node. - ElemType ParentDistance() const { return parentDistance; } - //! Modify the distance from the center of this node to the center of the - //! parent node. - ElemType& ParentDistance() { return parentDistance; } - - /** - * Return the specified child (0 will be left, 1 will be right). If the index - * is greater than 1, this will return the right child. - * - * @param child Index of child to return. - */ - SpillTree& Child(const size_t child) const; - - SpillTree*& ChildPtr(const size_t child) - { return (child == 0) ? left : right; } - - //! Return the number of points in this node (0 if not a leaf). - size_t NumPoints() const; - - /** - * Return the number of descendants of this node. For a non-leaf spill tree, - * this is the number of points at the descendant leaves. For a leaf, this is - * the number of points in the leaf. - */ - size_t NumDescendants() const; - - /** - * Return the index (with reference to the dataset) of a particular descendant - * of this node. The index should be greater than zero but less than the - * number of descendants. - * - * @param index Index of the descendant. - */ - size_t Descendant(const size_t index) const; - - /** - * Return the index (with reference to the dataset) of a particular point in - * this node. This will happily return invalid indices if the given index is - * greater than the number of points in this node (obtained with NumPoints()) - * -- be careful. - * - * @param index Index of point for which a dataset index is wanted. - */ - size_t Point(const size_t index) const; - - //! Return the minimum distance to another node. - ElemType MinDistance(const SpillTree& other) const - { - return bound.MinDistance(other.Bound()); - } - - //! Return the maximum distance to another node. - ElemType MaxDistance(const SpillTree& other) const - { - return bound.MaxDistance(other.Bound()); - } - - //! Return the minimum and maximum distance to another node. - math::RangeType RangeDistance(const SpillTree& other) const - { - return bound.RangeDistance(other.Bound()); - } - - //! Return the minimum distance to another point. - template - ElemType MinDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const - { - return bound.MinDistance(point); - } - - //! Return the maximum distance to another point. - template - ElemType MaxDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) - const - { - return bound.MaxDistance(point); - } - - //! Return the minimum and maximum distance to another point. - template - math::RangeType - RangeDistance(const VecType& point, - typename std::enable_if_t::value>* = 0) const - { - return bound.RangeDistance(point); - } - - //! Returns false: this tree type does not have self children. - static bool HasSelfChildren() { return false; } - - //! Store the center of the bounding region in the given vector. - void Center(arma::vec& center) { bound.Center(center); } - - private: - /** - * Splits the current node, assigning its left and right children recursively. - * - * @param points Vector of indexes of points to be included in this node. - * @param maxLeafSize Maximum number of points held in a leaf. - * @param tau Overlapping size. - * @param rho Balance threshold. - */ - void SplitNode(arma::Col& points, - const size_t maxLeafSize, - const double tau, - const double rho); - - /** - * Split the list of points. - * - * @param tau Overlapping size. - * @param rho Balance threshold. - * @param points Vector of indexes of points to be included. - * @param leftPoints Indexes of points to be included in left child. - * @param rightPoints Indexes of points to be included in right child. - * @return Flag to know if the overlapping buffer was included. - */ - bool SplitPoints(const double tau, - const double rho, - const arma::Col& points, - arma::Col& leftPoints, - arma::Col& rightPoints); - protected: - /** - * A default constructor. This is meant to only be used with - * boost::serialization, which is allowed with the friend declaration below. - * This does not return a valid tree! The method must be protected, so that - * the serialization shim can work with the default constructor. - */ - SpillTree(); - - //! Friend access is given for the default constructor. - friend class boost::serialization::access; - - public: - /** - * Serialize the tree. - */ - template - void serialize(Archive& ar, const unsigned int version); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "spill_tree_impl.hpp" - -// Include everything else, if necessary. -#include "../spill_tree.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_tree_impl.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_tree_impl.hpp deleted file mode 100644 index 624b3a84c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/spill_tree_impl.hpp +++ /dev/null @@ -1,809 +0,0 @@ -/** - * @file spill_tree_impl.hpp - * - * Implementation of generalized hybrid spill tree (SpillTree). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_SPILL_TREE_IMPL_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_SPILL_TREE_IMPL_HPP - -// In case it wasn't included already for some reason. -#include "spill_tree.hpp" - -#include - -namespace mlpack { -namespace tree { - -template class HyperplaneType, - template - class SplitType> -SpillTree:: -SpillTree( - const MatType& data, - const double tau, - const size_t maxLeafSize, - const double rho) : - left(NULL), - right(NULL), - parent(NULL), - count(0), - pointsIndex(NULL), - overlappingNode(false), - hyperplane(), - bound(data.n_rows), - parentDistance(0), // Parent distance for the root is 0: it has no parent. - dataset(&data), - localDataset(false) -{ - arma::Col points; - if (dataset->n_cols > 0) - // Fill points with all possible indexes: 0 .. (dataset->n_cols - 1). - points = arma::linspace>(0, dataset->n_cols - 1, - dataset->n_cols); - - // Do the actual splitting of this node. - SplitNode(points, maxLeafSize, tau, rho); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -template class HyperplaneType, - template - class SplitType> -SpillTree:: -SpillTree( - MatType&& data, - const double tau, - const size_t maxLeafSize, - const double rho) : - left(NULL), - right(NULL), - parent(NULL), - count(0), - pointsIndex(NULL), - overlappingNode(false), - hyperplane(), - bound(data.n_rows), - parentDistance(0), // Parent distance for the root is 0: it has no parent. - dataset(new MatType(std::move(data))), - localDataset(true) -{ - arma::Col points; - if (dataset->n_cols > 0) - // Fill points with all possible indexes: 0 .. (dataset->n_cols - 1). - points = arma::linspace>(0, dataset->n_cols - 1, - dataset->n_cols); - - // Do the actual splitting of this node. - SplitNode(points, maxLeafSize, tau, rho); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -template class HyperplaneType, - template - class SplitType> -SpillTree:: -SpillTree( - SpillTree* parent, - arma::Col& points, - const double tau, - const size_t maxLeafSize, - const double rho) : - left(NULL), - right(NULL), - parent(parent), - count(0), - pointsIndex(NULL), - overlappingNode(false), - hyperplane(), - bound(parent->Dataset().n_rows), - dataset(&parent->Dataset()), // Point to the parent's dataset. - localDataset(false) -{ - // Perform the actual splitting. - SplitNode(points, maxLeafSize, tau, rho); - - // Create the statistic depending on if we are a leaf or not. - stat = StatisticType(*this); -} - -/** - * Create a hybrid spill tree by copying the other tree. Be careful! This can - * take a long time and use a lot of memory. - */ -template class HyperplaneType, - template - class SplitType> -SpillTree:: -SpillTree(const SpillTree& other) : - left(NULL), - right(NULL), - parent(other.parent), - count(other.count), - pointsIndex(NULL), - overlappingNode(other.overlappingNode), - hyperplane(other.hyperplane), - bound(other.bound), - stat(other.stat), - parentDistance(other.parentDistance), - furthestDescendantDistance(other.furthestDescendantDistance), - // Copy matrix, but only if we are the root and the other tree has its own - // copy of the dataset. - dataset((other.parent == NULL && other.localDataset) ? - new MatType(*other.dataset) : other.dataset), - localDataset(other.parent == NULL && other.localDataset) -{ - // Create left and right children (if any). - if (other.Left()) - { - left = new SpillTree(*other.Left()); - left->Parent() = this; // Set parent to this, not other tree. - } - - if (other.Right()) - { - right = new SpillTree(*other.Right()); - right->Parent() = this; // Set parent to this, not other tree. - } - - // If vector of indexes, copy it. - if (other.pointsIndex) - pointsIndex = new arma::Col(*other.pointsIndex); - - // Propagate matrix, but only if we are the root. - if (parent == NULL && localDataset) - { - std::queue queue; - if (left) - queue.push(left); - if (right) - queue.push(right); - while (!queue.empty()) - { - SpillTree* node = queue.front(); - queue.pop(); - - node->dataset = dataset; - if (node->left) - queue.push(node->left); - if (node->right) - queue.push(node->right); - } - } -} - -/** - * Move constructor. - */ -template class HyperplaneType, - template - class SplitType> -SpillTree:: -SpillTree(SpillTree&& other) : - left(other.left), - right(other.right), - parent(other.parent), - count(other.count), - pointsIndex(other.pointsIndex), - overlappingNode(other.overlappingNode), - hyperplane(other.hyperplane), - bound(std::move(other.bound)), - stat(std::move(other.stat)), - parentDistance(other.parentDistance), - furthestDescendantDistance(other.furthestDescendantDistance), - minimumBoundDistance(other.minimumBoundDistance), - dataset(other.dataset), - localDataset(other.localDataset) -{ - // Now we are a clone of the other tree. But we must also clear the other - // tree's contents, so it doesn't delete anything when it is destructed. - other.left = NULL; - other.right = NULL; - other.count = 0; - other.pointsIndex = NULL; - other.parentDistance = 0.0; - other.furthestDescendantDistance = 0.0; - other.minimumBoundDistance = 0.0; - other.dataset = NULL; - other.localDataset = false; - - // Set new parent. - if (left) - left->parent = this; - if (right) - right->parent = this; -} - -/** - * Initialize the tree from an archive. - */ -template class HyperplaneType, - template - class SplitType> -template -SpillTree:: -SpillTree( - Archive& ar, - const typename std::enable_if_t*) : - SpillTree() // Create an empty SpillTree. -{ - // We've delegated to the constructor which gives us an empty tree, and now we - // can serialize from it. - ar >> BOOST_SERIALIZATION_NVP(*this); -} - -/** - * Deletes this node, deallocating the memory for the children and calling their - * destructors in turn. This will invalidate any pointers or references to any - * nodes which are children of this one. - */ -template class HyperplaneType, - template - class SplitType> -SpillTree:: - ~SpillTree() -{ - delete left; - delete right; - delete pointsIndex; - - // If we're the root and we own the dataset, delete it. - if (!parent && localDataset) - delete dataset; -} - -template class HyperplaneType, - template - class SplitType> -inline bool SpillTree::IsLeaf() const -{ - return !left; -} - -/** - * Returns the number of children in this node. - */ -template class HyperplaneType, - template - class SplitType> -inline size_t SpillTree::NumChildren() const -{ - if (left && right) - return 2; - if (left) - return 1; - - return 0; -} - -/** - * Return the index of the nearest child node to the given query point (this - * is an efficient estimation based on the splitting hyperplane, the node - * returned is not necessarily the nearest). If this is a leaf node, it will - * return NumChildren() (invalid index). - */ -template class HyperplaneType, - template - class SplitType> -template -size_t SpillTree::GetNearestChild( - const VecType& point, - typename std::enable_if_t::value>*) -{ - if (IsLeaf() || !left || !right) - return 0; - - if (hyperplane.Left(point)) - return 0; - return 1; -} - -/** - * Return the index of the furthest child node to the given query point (this - * is an efficient estimation based on the splitting hyperplane, the node - * returned is not necessarily the furthest). If this is a leaf node, it will - * return NumChildren() (invalid index). - */ -template class HyperplaneType, - template - class SplitType> -template -size_t SpillTree::GetFurthestChild( - const VecType& point, - typename std::enable_if_t::value>*) -{ - if (IsLeaf() || !left || !right) - return 0; - - if (hyperplane.Left(point)) - return 1; - return 0; -} - -/** - * Return the index of the nearest child node to the given query node (this - * is an efficient estimation based on the splitting hyperplane, the node - * returned is not necessarily the nearest). If it can't decide it will - * return NumChildren() (invalid index). - */ -template class HyperplaneType, - template - class SplitType> -size_t SpillTree::GetNearestChild(const SpillTree& queryNode) -{ - if (IsLeaf() || !left || !right) - return 0; - - if (hyperplane.Left(queryNode.Bound())) - return 0; - if (hyperplane.Right(queryNode.Bound())) - return 1; - // Can't decide. - return 2; -} - -/** - * Return the index of the furthest child node to the given query point (this - * is an efficient estimation based on the splitting hyperplane, the node - * returned is not necessarily the furthest). If this is a leaf node, it will - * return NumChildren() (invalid index). - */ -template class HyperplaneType, - template - class SplitType> -size_t SpillTree::GetFurthestChild(const SpillTree& queryNode) -{ - if (IsLeaf() || !left || !right) - return 0; - - if (hyperplane.Left(queryNode.Bound())) - return 1; - if (hyperplane.Right(queryNode.Bound())) - return 0; - // Can't decide. - return 2; -} - -/** - * Return a bound on the furthest point in the node from the center. This - * returns 0 unless the node is a leaf. - */ -template class HyperplaneType, - template - class SplitType> -inline typename SpillTree::ElemType -SpillTree:: - FurthestPointDistance() const -{ - if (!IsLeaf()) - return 0.0; - - // Otherwise return the distance from the center to a corner of the bound. - return 0.5 * bound.Diameter(); -} - -/** - * Return the furthest possible descendant distance. This returns the maximum - * distance from the center to the edge of the bound and not the empirical - * quantity which is the actual furthest descendant distance. So the actual - * furthest descendant distance may be less than what this method returns (but - * it will never be greater than this). - */ -template class HyperplaneType, - template - class SplitType> -inline typename SpillTree::ElemType -SpillTree:: - FurthestDescendantDistance() const -{ - return furthestDescendantDistance; -} - -//! Return the minimum distance from the center to any bound edge. -template class HyperplaneType, - template - class SplitType> -inline typename SpillTree::ElemType -SpillTree:: - MinimumBoundDistance() const -{ - return bound.MinWidth() / 2.0; -} - -/** - * Return the specified child. - */ -template class HyperplaneType, - template - class SplitType> -inline SpillTree& -SpillTree:: - Child(const size_t child) const -{ - if (child == 0) - return *left; - else - return *right; -} - -/** - * Return the number of points contained in this node. - */ -template class HyperplaneType, - template - class SplitType> -inline size_t SpillTree::NumPoints() const -{ - if (IsLeaf()) - return count; - return 0; -} - -/** - * Return the number of descendants contained in the node. - */ -template class HyperplaneType, - template - class SplitType> -inline size_t SpillTree::NumDescendants() const -{ - return count; -} - -/** - * Return the index of a particular descendant contained in this node. - */ -template class HyperplaneType, - template - class SplitType> -inline size_t SpillTree::Descendant(const size_t index) const -{ - if (IsLeaf()) - return (*pointsIndex)[index]; - size_t num = left->NumDescendants(); - if (index < num) - return left->Descendant(index); - if (right) - return right->Descendant(index - num); - // This should never happen. - return (size_t() - 1); -} - -/** - * Return the index of a particular point contained in this node. - */ -template class HyperplaneType, - template - class SplitType> -inline size_t SpillTree::Point(const size_t index) const -{ - if (IsLeaf()) - return (*pointsIndex)[index]; - // This should never happen. - return (size_t() - 1); -} - -template class HyperplaneType, - template - class SplitType> -void SpillTree:: - SplitNode(arma::Col& points, - const size_t maxLeafSize, - const double tau, - const double rho) -{ - // We need to expand the bounds of this node properly. - for (size_t i = 0; i < points.n_elem; i++) - bound |= dataset->col(points[i]); - - // Calculate the furthest descendant distance. - furthestDescendantDistance = 0.5 * bound.Diameter(); - - // Now, check if we need to split at all. - if (points.n_elem <= maxLeafSize) - { - pointsIndex = new arma::Col(); - pointsIndex->swap(points); - count = pointsIndex->n_elem; - return; // We can't split this. - } - - const bool split = SplitType::SplitSpace(bound, - *dataset, points, hyperplane); - // The node may not be always split. For instance, if all the points are the - // same, we can't split them. - if (!split) - { - pointsIndex = new arma::Col(); - pointsIndex->swap(points); - count = pointsIndex->n_elem; - return; // We can't split this. - } - - arma::Col leftPoints, rightPoints; - // Split the node. - overlappingNode = SplitPoints(tau, rho, points, leftPoints, rightPoints); - - // We don't need the information in points, so lets clean it. - arma::Col().swap(points); - - // Now we will recursively split the children by calling their constructors - // (which perform this splitting process). - left = new SpillTree(this, leftPoints, tau, maxLeafSize, rho); - right = new SpillTree(this, rightPoints, tau, maxLeafSize, rho); - - // Update count number, to represent the number of descendant points. - count = left->NumDescendants() + right->NumDescendants(); - - // Calculate parent distances for those two nodes. - arma::vec center, leftCenter, rightCenter; - Center(center); - left->Center(leftCenter); - right->Center(rightCenter); - - const ElemType leftParentDistance = MetricType::Evaluate(center, leftCenter); - const ElemType rightParentDistance = MetricType::Evaluate(center, - rightCenter); - - left->ParentDistance() = leftParentDistance; - right->ParentDistance() = rightParentDistance; -} - -template class HyperplaneType, - template - class SplitType> -bool SpillTree:: - SplitPoints(const double tau, - const double rho, - const arma::Col& points, - arma::Col& leftPoints, - arma::Col& rightPoints) -{ - arma::vec projections(points.n_elem); - size_t left = 0, right = 0, leftFrontier = 0, rightFrontier = 0; - - // Count the number of points to the left/right of the splitting hyperplane. - for (size_t i = 0; i < points.n_elem; i++) - { - // Store projection value for future use. - projections[i] = hyperplane.Project(dataset->col(points[i])); - if (projections[i] <= 0) - { - left++; - if (projections[i] > -tau) - leftFrontier++; - } - else - { - right++; - if (projections[i] < tau) - rightFrontier++; - } - } - - const double p1 = (double) (left + rightFrontier) / points.n_elem; - const double p2 = (double) (right + leftFrontier) / points.n_elem; - - if ((p1 <= rho || rightFrontier == 0) && - (p2 <= rho || leftFrontier == 0)) - { - // Perform the actual splitting considering the overlapping buffer. Points - // with projection value in the range (-tau, tau) are included in both, - // leftPoints and rightPoints. - leftPoints.resize(left + rightFrontier); - rightPoints.resize(right + leftFrontier); - for (size_t i = 0, rc = 0, lc = 0; i < points.n_elem; i++) - { - if (projections[i] < tau || projections[i] <= 0) - leftPoints[lc++] = points[i]; - if (projections[i] > -tau) - rightPoints[rc++] = points[i]; - } - // Return true, because it is a overlapping node. - return true; - } - - // Perform the actual splitting ignoring the overlapping buffer. Points - // with projection value less than or equal to zero are included in leftPoints - // and points with projection value greater than zero are included in - // rightPoints. - leftPoints.resize(left); - rightPoints.resize(right); - for (size_t i = 0, rc = 0, lc = 0; i < points.n_elem; i++) - { - if (projections[i] <= 0) - leftPoints[lc++] = points[i]; - else - rightPoints[rc++] = points[i]; - } - // Return false, because it isn't a overlapping node. - return false; -} - -// Default constructor (private), for boost::serialization. -template class HyperplaneType, - template - class SplitType> -SpillTree:: - SpillTree() : - left(NULL), - right(NULL), - parent(NULL), - count(0), - pointsIndex(NULL), - overlappingNode(false), - stat(*this), - parentDistance(0), - furthestDescendantDistance(0), - dataset(NULL), - localDataset(false) -{ - // Nothing to do. -} - -/** - * Serialize the tree. - */ -template class HyperplaneType, - template - class SplitType> -template -void SpillTree:: - serialize(Archive& ar, const unsigned int /* version */) -{ - // If we're loading, and we have children, they need to be deleted. - if (Archive::is_loading::value) - { - if (left) - delete left; - if (right) - delete right; - if (!parent && localDataset) - delete dataset; - - parent = NULL; - left = NULL; - right = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(count); - ar & BOOST_SERIALIZATION_NVP(pointsIndex); - ar & BOOST_SERIALIZATION_NVP(overlappingNode); - ar & BOOST_SERIALIZATION_NVP(hyperplane); - ar & BOOST_SERIALIZATION_NVP(bound); - ar & BOOST_SERIALIZATION_NVP(stat); - ar & BOOST_SERIALIZATION_NVP(parent); - ar & BOOST_SERIALIZATION_NVP(parentDistance); - ar & BOOST_SERIALIZATION_NVP(furthestDescendantDistance); - ar & BOOST_SERIALIZATION_NVP(dataset); - - if (Archive::is_loading::value) - localDataset = true; - - // Save children last; otherwise boost::serialization gets confused. - bool hasLeft = (left != NULL); - bool hasRight = (right != NULL); - - ar & BOOST_SERIALIZATION_NVP(hasLeft); - ar & BOOST_SERIALIZATION_NVP(hasRight); - - if (hasLeft) - ar & BOOST_SERIALIZATION_NVP(left); - if (hasRight) - ar & BOOST_SERIALIZATION_NVP(right); - - if (Archive::is_loading::value) - { - if (left) - { - left->parent = this; - left->localDataset = false; - } - if (right) - { - right->parent = this; - right->localDataset = false; - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/traits.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/traits.hpp deleted file mode 100644 index 5c3b1abda..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/traits.hpp +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file traits.hpp - * @author Ryan Curtin - * @author Marcos Pividori - * - * Specialization of the TreeTraits class for the SpillTree type of tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_TRAITS_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_TRAITS_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * This is a specialization of the TreeType class to the SpillTree tree type. - * It defines characteristics of the spill tree, and is used to help write - * tree-independent (but still optimized) tree-based algorithms. See - * mlpack/core/tree/tree_traits.hpp for more information. - */ -template class HyperplaneType, - template - class SplitType> -class TreeTraits> -{ - public: - /** - * Each spill tree node has two children which can share points. - * Therefore, children can be overlapping. - */ - static const bool HasOverlappingChildren = true; - - /** - * There is no guarantee that the first point in a node is its centroid. - */ - static const bool FirstPointIsCentroid = false; - - /** - * Points are not contained at multiple levels of the spill tree. - */ - static const bool HasSelfChildren = false; - - /** - * Points are not rearranged during building of the tree. - */ - static const bool RearrangesDataset = false; - - /** - * This is always a binary tree. - */ - static const bool BinaryTree = true; - - /** - * Spill trees have duplicated points, so NumDescendants() could count a given - * point twice. - */ - static const bool UniqueNumDescendants = false; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/typedef.hpp b/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/typedef.hpp deleted file mode 100644 index 1a8f01222..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/spill_tree/typedef.hpp +++ /dev/null @@ -1,124 +0,0 @@ -/** - * @file typedef.hpp - * @author Ryan Curtin - * @author Marcos Pividori - * - * Template typedefs for the SpillTree class that satisfy the requirements - * of the TreeType policy class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_SPILL_TREE_TYPEDEF_HPP -#define MLPACK_CORE_TREE_SPILL_TREE_TYPEDEF_HPP - -#include "../space_split/mean_space_split.hpp" -#include "../space_split/midpoint_space_split.hpp" - -namespace mlpack { -namespace tree { - -/** - * The hybrid spill tree. It is a variant of metric-trees in which the children - * of a node can "spill over" onto each other, and contain shared datapoints. - * - * When recursively splitting nodes, the SPTree class select the dimension with - * maximum width to split on, and picks the midpoint of the range in that - * dimension as the value on which to split nodes. - * - * In each case a "overlapping buffer" is defined, included points at a distance - * less than tau from the decision boundary defined by the midpoint. - * - * For each node, we first split the points considering the overlapping buffer. - * If either of its children contains more than rho fraction of the total points - * we undo the overlapping splitting. Instead a conventional partition is used. - * In this way, we can ensure that each split reduces the number of points of a - * node by at least a constant factor. - * - * For more information, see the following paper. - * - * @code - * @inproceedings{ - * author = {Ting Liu, Andrew W. Moore, Alexander Gray and Ke Yang}, - * title = {An Investigation of Practical Approximate Nearest Neighbor - * Algorithms}, - * booktitle = {Advances in Neural Information Processing Systems 17}, - * year = {2005}, - * pages = {825--832} - * } - * @endcode - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, SpillTree, MeanSPTree - */ -template -using SPTree = SpillTree; - -/** - * A mean-split hybrid spill tree. This is the same as the SPTree, but this - * particular implementation will use the mean of the data in the split - * dimension as the value on which to split, instead of the midpoint. - * This can sometimes give better performance, but it is not always clear which - * type of tree is best. - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, SpillTree, SPTree - */ -template -using MeanSPTree = SpillTree; - -/** - * A hybrid spill tree considering general splitting hyperplanes (not - * necessarily axis-orthogonal). This particular implementation will consider - * the midpoint of the projection of the data in the vector determined by the - * farthest pair of points. This can sometimes give better performance, but - * generally it doesn't because it takes O(d) to calculate the projection of the - * query point when deciding which node to traverse, while when using a - * axis-orthogonal hyperplane, as SPTree does, we can do it in O(1). - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, SpillTree, SPTree - */ -template -using NonOrtSPTree = SpillTree; - -/** - * A mean-split hybrid spill tree considering general splitting hyperplanes (not - * necessarily axis-orthogonal). This is the same as the NonOrtSPTree, but this - * particular implementation will use the mean of the data in the split - * projection as the value on which to split, instead of the midpoint. - * This can sometimes give better performance, but it is not always clear which - * type of tree is best. - * - * This template typedef satisfies the TreeType policy API. - * - * @see @ref trees, SpillTree, MeanSPTree, NonOrtSPTree - */ -template -using NonOrtMeanSPTree = SpillTree; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/statistic.hpp b/src/sdk/mlpack/include/mlpack/core/tree/statistic.hpp deleted file mode 100644 index 8c384e26b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/statistic.hpp +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @file statistic.hpp - * - * Definition of the policy type for the statistic class. - * - * You should define your own statistic that looks like EmptyStatistic. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_CORE_TREE_STATISTIC_HPP -#define MLPACK_CORE_TREE_STATISTIC_HPP - -namespace mlpack { -namespace tree { - -/** - * Empty statistic if you are not interested in storing statistics in your - * tree. Use this as a template for your own. - */ -class EmptyStatistic -{ - public: - EmptyStatistic() { } - ~EmptyStatistic() { } - - /** - * This constructor is called when a node is finished being created. The - * node is finished, and its children are finished, but it is not - * necessarily true that the statistics of other nodes are initialized yet. - * - * @param node Node which this corresponds to. - */ - template - EmptyStatistic(TreeType& /* node */) { } - - /** - * Serialize the statistic (there's nothing to be saved). - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */) - { } -}; - -} // namespace tree -} // namespace mlpack - -#endif // MLPACK_CORE_TREE_STATISTIC_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/tree/traversal_info.hpp b/src/sdk/mlpack/include/mlpack/core/tree/traversal_info.hpp deleted file mode 100644 index 1307f1a85..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/traversal_info.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file traversal_info.hpp - * @author Ryan Curtin - * - * This class will hold the traversal information for dual-tree traversals. A - * dual-tree traversal should be updating the members of this class before - * Score() is called. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_TRAVERSAL_INFO_HPP -#define MLPACK_CORE_TREE_TRAVERSAL_INFO_HPP - -namespace mlpack { -namespace tree { - -/** - * The TraversalInfo class holds traversal information which is used in - * dual-tree (and single-tree) traversals. A traversal should be updating the - * members of this class before Score() is called. This class should be held as - * a member of the RuleType class and the interface to it should be through a - * TraversalInfo() method. - * - * The information held by this class is the last node combination visited - * before the current node combination was recursed into, and the score - * resulting from when Score() was called on that combination. However, this - * information is identical for a query node and a reference node in a - * particular node combination, so traversals only need to update the - * TraversalInfo object in a query node (and the algorithms should only use the - * TraversalInfo object from a query node). - * - * In general, this auxiliary traversal information is used to try and make a - * prune without needing to call BaseCase() or calculate the distance between - * nodes. Using this information you can place bounds on the distance between - * the two nodes quickly. - * - * If the traversal is not updating the members of this class correctly, a - * likely result is a null pointer dereference. Dual-tree algorithms should - * assume that the members are set properly and should not need to check for - * null pointers. - * - * There is one exception, which is the root node combination; the score can be - * set to 0 and the query and reference nodes can just be set to the root nodes; - * no algorithm should be able to prune the root combination anyway. - */ -template -class TraversalInfo -{ - public: - /** - * Create the TraversalInfo object and initialize the pointers to NULL. - */ - TraversalInfo() : - lastQueryNode(NULL), - lastReferenceNode(NULL), - lastScore(0.0), - lastBaseCase(0.0) { /* Nothing to do. */ } - - //! Get the last query node. - TreeType* LastQueryNode() const { return lastQueryNode; } - //! Modify the last query node. - TreeType*& LastQueryNode() { return lastQueryNode; } - - //! Get the last reference node. - TreeType* LastReferenceNode() const { return lastReferenceNode; } - //! Modify the last reference node. - TreeType*& LastReferenceNode() { return lastReferenceNode; } - - //! Get the score associated with the last query and reference nodes. - double LastScore() const { return lastScore; } - //! Modify the score associated with the last query and reference nodes. - double& LastScore() { return lastScore; } - - //! Get the base case associated with the last node combination. - double LastBaseCase() const { return lastBaseCase; } - //! Modify the base case associated with the last node combination. - double& LastBaseCase() { return lastBaseCase; } - - private: - //! The last query node. - TreeType* lastQueryNode; - //! The last reference node. - TreeType* lastReferenceNode; - //! The last score. - double lastScore; - //! The last base case. - double lastBaseCase; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/tree/tree_traits.hpp b/src/sdk/mlpack/include/mlpack/core/tree/tree_traits.hpp deleted file mode 100644 index 7f1b79c4c..000000000 --- a/src/sdk/mlpack/include/mlpack/core/tree/tree_traits.hpp +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @file tree_traits.hpp - * @author Ryan Curtin - * - * This file implements the basic, unspecialized TreeTraits class, which - * provides information about tree types. If you create a tree class, you - * should specialize this class with the characteristics of your tree. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_TREE_TREE_TRAITS_HPP -#define MLPACK_CORE_TREE_TREE_TRAITS_HPP - -namespace mlpack { -namespace tree { - -/** - * The TreeTraits class provides compile-time information on the characteristics - * of a given tree type. These include traits such as whether or not a node - * knows the distance to its parent node, or whether or not the subspaces - * represented by children can overlap. - * - * These traits can be used for static compile-time optimization: - * - * @code - * // This if statement will be optimized out at compile time! - * if (TreeTraits::HasOverlappingChildren == false) - * { - * // Do a simpler computation because no children overlap. - * } - * else - * { - * // Do the full, complex calculation. - * } - * @endcode - * - * The traits can also be used in conjunction with SFINAE to write specialized - * versions of functions: - * - * @code - * template - * void Compute(TreeType& node, - * std::enable_if_t< - * TreeTraits::RearrangesDataset>*) - * { - * // Computation where special dataset-rearranging tree constructor is - * // called. - * } - * - * template - * void Compute(TreeType& node, - * std::enable_if_t< - * !TreeTraits::RearrangesDataset>*) - * { - * // Computation where normal tree constructor is called. - * } - * @endcode - * - * In those two examples, the std::enable_if_t<> class takes a boolean template - * parameter which allows that function to be called when the boolean is true. - * - * Each trait must be a static const value and not a function; only const values - * can be used as template parameters (or constexprs can be used too). By - * default (the unspecialized implementation of TreeTraits), each parameter is - * set to make as few assumptions about the tree as possible; so, even if - * TreeTraits is not specialized for a particular tree type, tree-based - * algorithms should still work. - * - * When you write your own tree, you must specialize the TreeTraits class to - * your tree type and set the corresponding values appropriately. See - * mlpack/core/tree/binary_space_tree/traits.hpp for an example. - */ -template -class TreeTraits -{ - public: - /** - * This is true if the subspaces represented by the children of a node can - * overlap. - */ - static const bool HasOverlappingChildren = true; - - /** - * This is true if a point can be included in more than one node. - */ - static const bool HasDuplicatedPoints = false; - - /** - * This is true if the first point of each node is the centroid of its bound. - */ - static const bool FirstPointIsCentroid = false; - - /** - * This is true if the points contained in the first child of a node - * (Child(0)) are also contained in that node. - */ - static const bool HasSelfChildren = false; - - /** - * This is true if the tree rearranges points in the dataset when it is built. - */ - static const bool RearrangesDataset = false; - - /** - * This is true if the tree always has only two children. - */ - static const bool BinaryTree = false; - - /** - * This is true if the NumDescendants() method doesn't include duplicated - * points. - */ - static const bool UniqueNumDescendants = true; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/arma_config.hpp b/src/sdk/mlpack/include/mlpack/core/util/arma_config.hpp deleted file mode 100644 index d15767e53..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/arma_config.hpp +++ /dev/null @@ -1,22 +0,0 @@ -/** - * @file arma_config.hpp - * - * This is an autogenerated file which contains the configuration of Armadillo - * at the time mlpack was built. If you modify anything in here by hand, your - * warranty is void, your house may catch fire, and we're not going to call the - * police when your program segfaults so hard that robbers come to your house - * and take everything you own. If you do decide, against better judgment, to - * modify anything at all in this file, and you are reporting a bug, be - * absolutely certain to mention that you've done something stupid in this file - * first. - * - * In short: don't touch this file. - */ -#ifndef MLPACK_CORE_UTIL_ARMA_CONFIG_HPP -#define MLPACK_CORE_UTIL_ARMA_CONFIG_HPP - -#define MLPACK_ARMA_NO64BIT_WORD - -#define MLPACK_ARMA_USE_OPENMP - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/arma_config_check.hpp b/src/sdk/mlpack/include/mlpack/core/util/arma_config_check.hpp deleted file mode 100644 index 545a9b74e..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/arma_config_check.hpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @file arma_config_check.hpp - * @author Ryan Curtin - * - * Using the contents of arma_config.hpp, try to catch the condition where the - * user has included mlpack with ARMA_64BIT_WORD enabled but mlpack was compiled - * without ARMA_64BIT_WORD enabled. This should help prevent a long, drawn-out - * debugging process where nobody can figure out why the stack is getting - * mangled. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_ARMA_CONFIG_CHECK_HPP -#define MLPACK_CORE_UTIL_ARMA_CONFIG_CHECK_HPP - -#include "arma_config.hpp" - -#ifdef ARMA_64BIT_WORD - #ifdef MLPACK_ARMA_NO_64BIT_WORD - #pragma message "mlpack was compiled without ARMA_64BIT_WORD, but you are \ -compiling with ARMA_64BIT_WORD. This will almost certainly cause irreparable \ -disaster. Either disable ARMA_64BIT_WORD in your application which is using \ -mlpack, or, recompile mlpack against a version of Armadillo which has \ -ARMA_64BIT_WORD enabled." - #endif -#else - #ifdef MLPACK_ARMA_64BIT_WORD - #pragma message "mlpack was compiled with ARMA_64BIT_WORD, but you are \ -compiling without ARMA_64BIT_WORD. This will almost certainly cause \ -irreparable disaster. Either enable ARMA_64BIT_WORD in your application which \ -is using mlpack, or, recompile mlpack against a version of Armadillo which has \ -ARMA_64BIT_WORD disabled." - #endif -#endif - -// Check if OpenMP was enabled when mlpack was built. This only matters for -// Armadillo 8.300.1 and newer. -#if (ARMA_VERSION_MAJOR > 8) || \ - ((ARMA_VERSION_MAJOR == 8) && (ARMA_VERSION_MINOR > 300)) || \ - ((ARMA_VERSION_MAJOR == 8) && (ARMA_VERSION_MINOR == 300) && \ - (ARMA_VERSION_PATCH >= 1)) - #ifdef ARMA_USE_OPENMP - #ifdef MLPACK_ARMA_DONT_USE_OPENMP - #pragma message "mlpack was compiled without OpenMP support, but you are \ -compiling with OpenMP support (either -fopenmp or another option). This will \ -almost certainly cause irreparable disaster. Either compile your application \ -*without* OpenMP support (i.e. remove -fopenmp or another flag), or, recompile \ -mlpack with OpenMP support." - #endif - #else - #ifdef MLPACK_ARMA_USE_OPENMP - #pragma message "mlpack was compiled with OpenMP support, but you are \ -compiling without OpenMP support. This will almost certainly cause \ -irreparable disaster. Either enable OpenMP support in your application (e.g., \ -add -fopenmp to your compiler command line), or, recompile mlpack *without* \ -OpenMP support." - #endif - #endif -#endif - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/arma_traits.hpp b/src/sdk/mlpack/include/mlpack/core/util/arma_traits.hpp deleted file mode 100644 index 45e5dac12..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/arma_traits.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file arma_traits.hpp - * @author Ryan Curtin - * - * Some traits used for template metaprogramming (SFINAE) with Armadillo types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_ARMA_TRAITS_HPP -#define MLPACK_CORE_UTIL_ARMA_TRAITS_HPP - -// Structs have public members by default (that's why they are chosen over -// classes). - -/** - * If value == true, then VecType is some sort of Armadillo vector or subview. - * You might use this struct like this: - * - * @code - * // Only accepts VecTypes that are actually Armadillo vector types. - * template - * void Function(const VecType& argumentA, - * typename std::enable_if_t::value>* = 0); - * @endcode - * - * The use of the enable_if_t object allows the compiler to instantiate - * Function() only if VecType is one of the Armadillo vector types. It has a - * default argument because it isn't meant to be used in either the function - * call or the function body. - */ -template -struct IsVector -{ - const static bool value = false; -}; - -// Commenting out the first template per case, because -// Visual Studio doesn't like this instantiaion pattern (error C2910). -// template<> -template -struct IsVector > -{ - const static bool value = true; -}; - -// template<> -template -struct IsVector > -{ - const static bool value = true; -}; - -// template<> -template -struct IsVector > -{ - const static bool value = true; -}; - -// template<> -template -struct IsVector > -{ - const static bool value = true; -}; - -// template<> -template -struct IsVector > -{ - const static bool value = true; -}; - -// template<> -template -struct IsVector > -{ - const static bool value = true; -}; - -// I'm not so sure about this one. An SpSubview object can be a row or column, -// but it can also be a matrix subview. - -// template<> -template -struct IsVector > -{ - const static bool value = true; -}; - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/backtrace.hpp b/src/sdk/mlpack/include/mlpack/core/util/backtrace.hpp deleted file mode 100644 index 934a4a1cb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/backtrace.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file backtrace.hpp - * @author Grzegorz Krajewski - * - * Definition of the Backtrace class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef __MLPACK_CORE_UTIL_BACKTRACE_HPP -#define __MLPACK_CORE_UTIL_BACKTRACE_HPP - -#include -#include - -namespace mlpack { - -/** - * Provides a backtrace. - * - * The Backtrace class retrieve addresses of each called function from the - * stack and decode file name, function & line number. Retrieved information - * can be printed in form: - * - * @code - * [b]: (count) /directory/to/file.cpp:function(args):line_number - * @endcode - * - * Backtrace is printed always when Log::Assert failed. - * An example is given below. - * - * @code - * if (!someImportantCondition()) - * { - * Log::Fatal << "someImportantCondition() is not satisfied! Terminating."; - * Log::Fatal << std::endl; - * } - * @endcode - * - * @note Log::Assert will not be shown when compiling in non-debug mode. - * - * @see PrefixedOutStream, Log - */ -class Backtrace -{ - public: - /** - * Constructor initialize fields and call GetAddress to retrieve addresses - * for each frame of backtrace. - * - * @param maxDepth Maximum depth of backtrace. Default 32 steps. - */ -#ifdef HAS_BFD_DL - Backtrace(int maxDepth = 32); -#else - Backtrace(); -#endif - //! Returns string of backtrace. - std::string ToString(); - - private: - /** - * Gets addresses of each called function from the stack. - * - * @param maxDepth Maximum depth of backtrace. Default 32 steps. - */ - static void GetAddress(int maxDepth); - - /** - * Decodes file name, function & line number. - * - * @param address Address of traced frame. - */ - static void DecodeAddress(long address); - - //! Demangles function name. - static void DemangleFunction(); - - //! Backtrace datastructure. - struct Frames - { - void *address; - const char* function; - const char* file; - unsigned line; - } static frame; - - //! A vector for all the backtrace information. - static std::vector stack; -}; - -}; // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/cli.hpp b/src/sdk/mlpack/include/mlpack/core/util/cli.hpp deleted file mode 100644 index adacfaeb8..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/cli.hpp +++ /dev/null @@ -1,331 +0,0 @@ -/** - * @file cli.hpp - * @author Matthew Amidon - * - * This file implements the CLI subsystem which is intended to replace FX. - * This can be used more or less regardless of context. In the future, - * it might be expanded to include file I/O. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_CLI_HPP -#define MLPACK_CORE_UTIL_CLI_HPP - -#include -#include -#include -#include - -#include - -#include - -#include "timers.hpp" -#include "program_doc.hpp" -#include "version.hpp" - -#include "param_data.hpp" - -namespace mlpack { -namespace util { - -// Externally defined in option.hpp, this class holds information about the -// program being run. -class ProgramDoc; - -} // namespace util - -/** - * @brief Parses the command line for parameters and holds user-specified - * parameters. - * - * The CLI class is a subsystem by which parameters for machine learning methods - * can be specified and accessed. In conjunction with the macros PARAM_DOUBLE, - * PARAM_INT, PARAM_STRING, PARAM_FLAG, and others, this class aims to make user - * configurability of mlpack methods very easy. There are only three methods in - * CLI that a user should need: CLI::ParseCommandLine(), CLI::GetParam(), and - * CLI::HasParam() (in addition to the PARAM_*() macros). - * - * @section addparam Adding parameters to a program - * - * @code - * $ ./executable --bar=5 - * @endcode - * - * @note The = is optional; a space can also be used. - * - * A parameter is specified by using one of the following macros (this is not a - * complete list; see core/io/cli.hpp): - * - * - PARAM_FLAG(ID, DESC, ALIAS) - * - PARAM_DOUBLE(ID, DESC, ALIAS, DEF) - * - PARAM_INT(ID, DESC, ALIAS, DEF) - * - PARAM_STRING(ID, DESC, ALIAS, DEF) - * - * @param ID Name of the parameter. - * @param DESC Short description of the parameter (one/two sentences). - * @param ALIAS An alias for the parameter. - * @param DEF Default value of the parameter. - * - * The flag (boolean) type automatically defaults to false; it is specified - * merely as a flag on the command line (no '=true' is required). - * - * Here is an example of a few parameters being defined; this is for the KNN - * executable (methods/neighbor_search/knn_main.cpp): - * - * @code - * PARAM_STRING_REQ("reference_file", "File containing the reference dataset.", - * "r"); - * PARAM_STRING_REQ("distances_file", "File to output distances into.", "d"); - * PARAM_STRING_REQ("neighbors_file", "File to output neighbors into.", "n"); - * PARAM_INT_REQ("k", "Number of furthest neighbors to find.", "k"); - * PARAM_STRING("query_file", "File containing query points (optional).", "q", - * ""); - * PARAM_INT("leaf_size", "Leaf size for tree building.", "l", 20); - * PARAM_FLAG("naive", "If true, O(n^2) naive mode is used for computation.", - * "N"); - * PARAM_FLAG("single_mode", "If true, single-tree search is used (as opposed " - * "to dual-tree search.", "s"); - * @endcode - * - * More documentation is available on the PARAM_*() macros in the documentation - * for core/io/cli.hpp. - * - * @section programinfo Documenting the program itself - * - * In addition to allowing documentation for each individual parameter and - * module, the PROGRAM_INFO() macro provides support for documenting the program - * itself. There should only be one instance of the PROGRAM_INFO() macro. - * Below is an example: - * - * @code - * PROGRAM_INFO("Maximum Variance Unfolding", "This program performs maximum " - * "variance unfolding on the given dataset, writing a lower-dimensional " - * "unfolded dataset to the given output file."); - * @endcode - * - * This description should be verbose, and explain to a non-expert user what the - * program does and how to use it. If relevant, paper citations should be - * included. - * - * @section parsecli Parsing the command line with CLI - * - * To have CLI parse the command line at the beginning of code execution, only a - * call to ParseCommandLine() is necessary: - * - * @code - * int main(int argc, char** argv) - * { - * CLI::ParseCommandLine(argc, argv); - * - * ... - * } - * @endcode - * - * CLI provides --help and --info options which give nicely formatted - * documentation of each option; the documentation is generated from the DESC - * arguments in the PARAM_*() macros. - * - * @section getparam Getting parameters with CLI - * - * When the parameters have been defined, the next important thing is how to - * access them. For this, the HasParam() and GetParam() methods are - * used. For instance, to see if the user passed the flag (boolean) "naive": - * - * @code - * if (CLI::HasParam("naive")) - * { - * Log::Info << "Naive has been passed!" << std::endl; - * } - * @endcode - * - * To get the value of a parameter, such as a string, use GetParam: - * - * @code - * const std::string filename = CLI::GetParam("filename"); - * @endcode - * - * @note - * Options should only be defined in files which define `main()` (that is, main - * executables). If options are defined elsewhere, they may be spuriously - * included into other executables and confuse users. Similarly, if your - * executable has options which you did not define, it is probably because the - * option is defined somewhere else and included in your executable. - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -class CLI -{ - public: - /** - * Adds a parameter to the hierarchy; use the PARAM_*() macros instead of this - * (i.e. PARAM_INT()). - * - * @param d Utility structure holding parameter data. - */ - static void Add(util::ParamData&& d); - - /** - * See if the specified flag was found while parsing. - * - * @param identifier The name of the parameter in question. - */ - static bool HasParam(const std::string& identifier); - - /** - * Get the value of type T found while parsing. You can set the value using - * this reference safely. - * - * @param identifier The name of the parameter in question. - */ - template - static T& GetParam(const std::string& identifier); - - /** - * Cast the given parameter of the given type to a short, printable - * std::string, for use in status messages. Ideally the message returned here - * should be only a handful of characters, and certainly no longer than one - * line. - * - * @param identifier The name of the parameter in question. - */ - template - static std::string GetPrintableParam(const std::string& identifier); - - /** - * Get the raw value of the parameter before any processing that GetParam() - * might normally do. So, e.g., for command-line programs, this does not - * perform any data loading or manipulation like GetParam() does. So if you - * want to access a matrix or model (or similar) parameter before it is - * loaded, this is the method to use. - * - * @param identifier The name of the parameter in question. - */ - template - static T& GetRawParam(const std::string& identifier); - - /** - * Retrieve the singleton. As an end user, if you are just using the CLI - * object, you should not need to use this function---the other static - * functions should be sufficient. - * - * In this case, the singleton is used to store data for the static methods, - * as there is no point in defining static methods only to have users call - * private instance methods. - * - * @return The singleton instance for use in the static methods. - */ - static CLI& GetSingleton(); - - /** - * Registers a ProgramDoc object, which contains documentation about the - * program. If this method has been called before (that is, if two - * ProgramDocs are instantiated in the program), a fatal error will occur. - * - * @param doc Pointer to the ProgramDoc object. - */ - static void RegisterProgramDoc(util::ProgramDoc* doc); - - //! Return a modifiable list of parameters that CLI knows about. - static std::map& Parameters(); - //! Return a modifiable list of aliases that CLI knows about. - static std::map& Aliases(); - - //! Get the program name as set by the PROGRAM_INFO() macro. - static std::string ProgramName(); - - /** - * Mark a particular parameter as passed. - * - * @param name Name of the parameter. - */ - static void SetPassed(const std::string& name); - - /** - * Take all parameters and function mappings and store them, under the given - * name. This can later be restored with RestoreSettings(). If settings have - * already been saved under the given name, they will be overwritten. This - * also clears the current parameters and function map. - * - * @param name Name of settings to save. - */ - static void StoreSettings(const std::string& name); - - /** - * Restore all of the parameters and function mappings of the given name, if - * they exist. A std::invalid_argument exception will be thrown if fatal is - * true and no settings with the given name have been stored (with - * StoreSettings()). - * - * @param name Name of settings to restore. - * @param fatal Whether to throw an exception on an unknown name. - */ - static void RestoreSettings(const std::string& name, const bool fatal = true); - - /** - * Clear all of the settings, removing all parameters and function mappings. - */ - static void ClearSettings(); - - private: - //! Convenience map from alias values to names. - std::map aliases; - //! Map of parameters. - std::map parameters; - - public: - //! Map for functions and types. - //! Use as functionMap["typename"]["functionName"]. - typedef std::map> FunctionMapType; - FunctionMapType functionMap; - - private: - //! Storage map for parameters. - std::map, - std::map, FunctionMapType>> storageMap; - - public: - //! True, if CLI was used to parse command line options. - bool didParse; - - //! Holds the name of the program for --version. This is the true program - //! name (argv[0]) not what is given in ProgramDoc. - std::string programName; - - //! Holds the timer objects. - Timers timer; - - //! So that Timer::Start() and Timer::Stop() can access the timer variable. - friend class Timer; - - //! Pointer to the ProgramDoc object. - util::ProgramDoc* doc; - - private: - /** - * Make the constructor private, to preclude unauthorized instances. - */ - CLI(); - - //! Private copy constructor; we don't want copies floating around. - CLI(const CLI& other); - //! Private copy operator; we don't want copies floating around. - CLI& operator=(const CLI& other); -}; - -} // namespace mlpack - -// Include the actual definitions of templated methods -#include "cli_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/cli_impl.hpp b/src/sdk/mlpack/include/mlpack/core/util/cli_impl.hpp deleted file mode 100644 index 9a82c36b7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/cli_impl.hpp +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @file cli_impl.hpp - * @author Matthew Amidon - * - * Implementation of templated functions of the CLI class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_CLI_IMPL_HPP -#define MLPACK_CORE_UTIL_CLI_IMPL_HPP - -// In case it has not already been included. -#include "cli.hpp" -#include "prefixedoutstream.hpp" - -#include -#include - -namespace mlpack { - -/** - * @brief Returns the value of the specified parameter. - * If the parameter is unspecified, an undefined but - * more or less valid value is returned. - * - * @tparam T The type of the parameter. - * @param identifier The full name of the parameter. - * - * @return The value of the parameter. Use CLI::CheckValue to determine if it's - * valid. - */ -template -T& CLI::GetParam(const std::string& identifier) -{ - // Only use the alias if the parameter does not exist as given. - std::string key = - (GetSingleton().parameters.count(identifier) == 0 && - identifier.length() == 1 && GetSingleton().aliases.count(identifier[0])) - ? GetSingleton().aliases[identifier[0]] : identifier; - - if (GetSingleton().parameters.count(key) == 0) - Log::Fatal << "Parameter --" << key << " does not exist in this program!" - << std::endl; - - util::ParamData& d = GetSingleton().parameters[key]; - - // Make sure the types are correct. - if (TYPENAME(T) != d.tname) - Log::Fatal << "Attempted to access parameter --" << key << " as type " - << TYPENAME(T) << ", but its true type is " << d.tname << "!" - << std::endl; - - // Do we have a special mapped function? - if (CLI::GetSingleton().functionMap[d.tname].count("GetParam") != 0) - { - T* output = NULL; - CLI::GetSingleton().functionMap[d.tname]["GetParam"](d, NULL, - (void*) &output); - return *output; - } - else - { - return *boost::any_cast(&d.value); - } -} - -/** - * Cast the given parameter of the given type to a short, printable std::string, - * for use in status messages. Ideally the message returned here should be only - * a handful of characters, and certainly no longer than one line. - * - * @param identifier The name of the parameter in question. - */ -template -std::string CLI::GetPrintableParam(const std::string& identifier) -{ - // Only use the alias if the parameter does not exist as given. - std::string key = ((GetSingleton().parameters.count(identifier) == 0) && - (identifier.length() == 1) && - (GetSingleton().aliases.count(identifier[0]) > 0)) ? - GetSingleton().aliases[identifier[0]] : identifier; - - if (GetSingleton().parameters.count(key) == 0) - Log::Fatal << "Parameter --" << key << " does not exist in this program!" - << std::endl; - - util::ParamData& d = GetSingleton().parameters[key]; - - // Make sure the types are correct. - if (TYPENAME(T) != d.tname) - Log::Fatal << "Attempted to access parameter --" << key << " as type " - << TYPENAME(T) << ", but its true type is " << d.tname << "!" - << std::endl; - - // Do we have a special mapped function? - if (CLI::GetSingleton().functionMap[d.tname].count("GetPrintableParam") != 0) - { - std::string output; - CLI::GetSingleton().functionMap[d.tname]["GetPrintableParam"](d, NULL, - (void*) &output); - return output; - } - else - { - std::ostringstream oss; - oss << "no GetPrintableParam function handler registered for type " - << d.cppType; - throw std::runtime_error(oss.str()); - } -} - -template -T& CLI::GetRawParam(const std::string& identifier) -{ - // Only use the alias if the parameter does not exist as given. - std::string key = - (GetSingleton().parameters.count(identifier) == 0 && - identifier.length() == 1 && GetSingleton().aliases.count(identifier[0])) - ? GetSingleton().aliases[identifier[0]] : identifier; - - if (GetSingleton().parameters.count(key) == 0) - Log::Fatal << "Parameter --" << key << " does not exist in this program!" - << std::endl; - - util::ParamData& d = GetSingleton().parameters[key]; - - // Make sure the types are correct. - if (TYPENAME(T) != d.tname) - Log::Fatal << "Attempted to access parameter --" << key << " as type " - << TYPENAME(T) << ", but its true type is " << d.tname << "!" - << std::endl; - - // Do we have a special mapped function? - if (CLI::GetSingleton().functionMap[d.tname].count("GetRawParam") != 0) - { - T* output = NULL; - CLI::GetSingleton().functionMap[d.tname]["GetRawParam"](d, NULL, - (void*) &output); - return *output; - } - else - { - // Use the regular GetParam(). - return GetParam(identifier); - } -} - -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/deprecated.hpp b/src/sdk/mlpack/include/mlpack/core/util/deprecated.hpp deleted file mode 100644 index b48ae507f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/deprecated.hpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @file deprecated.hpp - * @author Marcos Pividori. - * - * Definition of the mlpack_deprecated macro. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_DEPRECATED_HPP -#define MLPACK_CORE_UTIL_DEPRECATED_HPP - -#ifdef __GNUG__ -#define mlpack_deprecated __attribute__((deprecated)) -#elif defined(_MSC_VER) -#define mlpack_deprecated __declspec(deprecated) -#else -#pragma message("WARNING: You need to implement mlpack_deprecated for this " - "compiler") -#define mlpack_deprecated -#endif - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/gitversion.hpp b/src/sdk/mlpack/include/mlpack/core/util/gitversion.hpp deleted file mode 100644 index a638ff0f7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/gitversion.hpp +++ /dev/null @@ -1 +0,0 @@ -return "mlpack git-4bbf0c67e"; diff --git a/src/sdk/mlpack/include/mlpack/core/util/hyphenate_string.hpp b/src/sdk/mlpack/include/mlpack/core/util/hyphenate_string.hpp deleted file mode 100644 index 943f3ac6f..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/hyphenate_string.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @file hyphenate_string.hpp - * @author Ryan Curtin - * - * Hyphenate a string. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_HYPHENATE_STRING_HPP -#define MLPACK_CORE_UTIL_HYPHENATE_STRING_HPP - -namespace mlpack { -namespace util { - -/** - * Hyphenate a string or split it onto multiple 80-character lines, with some - * amount of padding on each line.  This is used for option output. - * - * @param str String to hyphenate (splits are on ' '). - * @param padding Amount of padding on the left for each new line. - */ -inline std::string HyphenateString(const std::string& str, int padding) -{ - size_t margin = 80 - padding; - if (str.length() < margin) - return str; - std::string out(""); - unsigned int pos = 0; - // First try to look as far as possible. - while (pos < str.length()) - { - size_t splitpos; - // Check that we don't have a newline first. - splitpos = str.find('\n', pos); - if (splitpos == std::string::npos || splitpos > (pos + margin)) - { - // We did not find a newline. - if (str.length() - pos < margin) - { - splitpos = str.length(); // The rest fits on one line. - } - else - { - splitpos = str.rfind(' ', margin + pos); // Find nearest space. - if (splitpos <= pos || splitpos == std::string::npos) // Not found. - splitpos = pos + margin; - } - } - out += str.substr(pos, (splitpos - pos)); - if (splitpos < str.length()) - { - out += '\n'; - out += std::string(padding, ' '); - } - - pos = splitpos; - if (str[pos] == ' ' || str[pos] == '\n') - pos++; - } - return out; -} - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/is_std_vector.hpp b/src/sdk/mlpack/include/mlpack/core/util/is_std_vector.hpp deleted file mode 100644 index 89f18c2da..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/is_std_vector.hpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @file is_std_vector.hpp - * @author Ryan Curtin - * - * Simple template metaprogramming struct to detect if a type is a - * std::vector. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_IS_STD_VECTOR_HPP -#define MLPACK_CORE_UTIL_IS_STD_VECTOR_HPP - -#include - -namespace mlpack { -namespace util { - -//! Metaprogramming structure for vector detection. -template -struct IsStdVector { const static bool value = false; }; - -//! Metaprogramming structure for vector detection. -template -struct IsStdVector> { const static bool value = true; }; - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/log.hpp b/src/sdk/mlpack/include/mlpack/core/util/log.hpp deleted file mode 100644 index 86e089696..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/log.hpp +++ /dev/null @@ -1,98 +0,0 @@ -/** - * @file log.hpp - * @author Matthew Amidon - * - * Definition of the Log class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_LOG_HPP -#define MLPACK_CORE_UTIL_LOG_HPP - -#include -#include - -#include "prefixedoutstream.hpp" -#include "nulloutstream.hpp" - -namespace mlpack { - -/** - * Provides a convenient way to give formatted output. - * - * The Log class has four members which can be used in the same way ostreams can - * be used: - * - * - Log::Debug - * - Log::Info - * - Log::Warn - * - Log::Fatal - * - * Each of these will prefix a tag to the output (for easy filtering), and the - * fatal output will terminate the program when a newline is encountered. An - * example is given below. - * - * @code - * Log::Info << "Checking a condition." << std::endl; - * if (!someCondition()) - * Log::Warn << "someCondition() is not satisfied!" << std::endl; - * Log::Info << "Checking an important condition." << std::endl; - * if (!someImportantCondition()) - * { - * Log::Fatal << "someImportantCondition() is not satisfied! Terminating."; - * Log::Fatal << std::endl; - * } - * @endcode - * - * Any messages sent to Log::Debug will not be shown when compiling in non-debug - * mode. Messages to Log::Info will only be shown when the --verbose flag is - * given to the program (or rather, the CLI class). - * - * @see PrefixedOutStream, NullOutStream, CLI - */ -class Log -{ - public: - /** - * Checks if the specified condition is true. - * If not, halts program execution and prints a custom error message. - * Does nothing in non-debug mode. - */ - static void Assert(bool condition, - const std::string& message = "Assert Failed."); - - /** - * MLPACK_EXPORT is required for global variables, so that they are properly - * exported by the Windows compiler. - */ - - // We only use PrefixedOutStream if the program is compiled with debug - // symbols. -#ifdef DEBUG - //! Prints debug output with the appropriate tag: [DEBUG]. - static MLPACK_EXPORT util::PrefixedOutStream Debug; -#else - //! Dumps debug output into the bit nether regions. - static MLPACK_EXPORT util::NullOutStream Debug; -#endif - - //! Prints informational messages if --verbose is specified, prefixed with - //! [INFO ]. - static MLPACK_EXPORT util::PrefixedOutStream Info; - - //! Prints warning messages prefixed with [WARN ]. - static MLPACK_EXPORT util::PrefixedOutStream Warn; - - //! Prints fatal messages prefixed with [FATAL], then terminates the program. - static MLPACK_EXPORT util::PrefixedOutStream Fatal; - - //! Reference to cout, if necessary. - static std::ostream& cout; -}; - -}; // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/mlpack_main.hpp b/src/sdk/mlpack/include/mlpack/core/util/mlpack_main.hpp deleted file mode 100644 index 4c915c0c0..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/mlpack_main.hpp +++ /dev/null @@ -1,160 +0,0 @@ -/** - * @param mlpack_cli_main.hpp - * @author Ryan Curtin - * - * This file, based on the value of the macro BINDING_TYPE, will define the - * macros necessary to compile an mlpack binding for the target language. - * - * This file should *only* be included by a program that is meant to be a - * command-line program or a binding to another language. This file also - * includes param_checks.hpp, which contains functions that are used to check - * parameter values at runtime. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_MLPACK_MAIN_HPP -#define MLPACK_CORE_UTIL_MLPACK_MAIN_HPP - -#define BINDING_TYPE_CLI 0 -#define BINDING_TYPE_TEST 1 -#define BINDING_TYPE_PYX 2 -#define BINDING_TYPE_UNKNOWN -1 - -#ifndef BINDING_TYPE -#define BINDING_TYPE BINDING_TYPE_UNKNOWN -#endif - -#if (BINDING_TYPE == BINDING_TYPE_CLI) // This is a command-line executable. - -#include -#include - -#define PRINT_PARAM_STRING mlpack::bindings::cli::ParamString -#define PRINT_PARAM_VALUE mlpack::bindings::cli::PrintValue -#define PRINT_CALL mlpack::bindings::cli::ProgramCall -#define PRINT_DATASET mlpack::bindings::cli::PrintDataset -#define PRINT_MODEL mlpack::bindings::cli::PrintModel -#define BINDING_IGNORE_CHECK mlpack::bindings::cli::IgnoreCheck - -namespace mlpack { -namespace util { - -template -using Option = mlpack::bindings::cli::CLIOption; - -} -} - -static const std::string testName = ""; -#include -#include -#include - -static void mlpackMain(); // This is typically defined after this include. - -int main(int argc, char** argv) -{ - // Parse the command-line options; put them into CLI. - mlpack::bindings::cli::ParseCommandLine(argc, argv); - // Enable timing. - mlpack::Timer::EnableTiming(); - - // A "total_time" timer is run by default for each mlpack program. - mlpack::Timer::Start("total_time"); - - mlpackMain(); - - // Print output options, print verbose information, save model parameters, - // clean up, and so forth. - mlpack::bindings::cli::EndProgram(); -} - -#elif(BINDING_TYPE == BINDING_TYPE_TEST) // This is a unit test. - -#include -#include -#include - -// These functions will do nothing. -#define PRINT_PARAM_STRING(A) std::string(" ") -#define PRINT_PARAM_VALUE(A, B) std::string(" ") -#define PRINT_DATASET(A) std::string(" ") -#define PRINT_MODEL(A) std::string(" ") -#define PRINT_CALL(...) std::string(" ") -#define BINDING_IGNORE_CHECK mlpack::bindings::tests::IgnoreCheck - -namespace mlpack { -namespace util { - -template -using Option = mlpack::bindings::tests::TestOption; - -} -} - -// testName symbol should be defined in each binding test file -#include - -#undef PROGRAM_INFO -#define PROGRAM_INFO(NAME, DESC) static mlpack::util::ProgramDoc \ - cli_programdoc_dummy_object = mlpack::util::ProgramDoc(NAME, \ - []() { return DESC; }); - -#elif(BINDING_TYPE == BINDING_TYPE_PYX) // This is a Python binding. - -#include -#include - -#define PRINT_PARAM_STRING mlpack::bindings::python::ParamString -#define PRINT_PARAM_VALUE mlpack::bindings::python::PrintValue -#define PRINT_DATASET mlpack::bindings::python::PrintDataset -#define PRINT_MODEL mlpack::bindings::python::PrintModel -#define PRINT_CALL mlpack::bindings::python::ProgramCall -#define BINDING_IGNORE_CHECK mlpack::bindings::python::IgnoreCheck - -namespace mlpack { -namespace util { - -template -using Option = mlpack::bindings::python::PyOption; - -} -} - -static const std::string testName = ""; -#include - -#undef PROGRAM_INFO -#define PROGRAM_INFO(NAME, DESC) static mlpack::util::ProgramDoc \ - cli_programdoc_dummy_object = mlpack::util::ProgramDoc(NAME, \ - []() { return DESC; }); \ - namespace mlpack { \ - namespace bindings { \ - namespace python { \ - std::string programName = NAME; \ - } \ - } \ - } - -PARAM_FLAG("verbose", "Display informational messages and the full list of " - "parameters and timers at the end of execution.", "v"); -PARAM_FLAG("copy_all_inputs", "If specified, all input parameters will be deep" - " copied before the method is run. This is useful for debugging problems " - "where the input parameters are being modified by the algorithm, but can " - "slow down the code.", ""); - -// Nothing else needs to be defined---the binding will use mlpackMain() as-is. - -#else - -#error "Unknown binding type! Be sure BINDING_TYPE is defined if you are " \ - "including ."; - -#endif - -#include "param_checks.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/nulloutstream.hpp b/src/sdk/mlpack/include/mlpack/core/util/nulloutstream.hpp deleted file mode 100644 index 2e2da94ff..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/nulloutstream.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file nulloutstream.hpp - * @author Ryan Curtin - * @author Matthew Amidon - * - * Definition of the NullOutStream class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_NULLOUTSTREAM_HPP -#define MLPACK_CORE_UTIL_NULLOUTSTREAM_HPP - -#include -#include -#include - -namespace mlpack { -namespace util { - -/** - * Used for Log::Debug when not compiled with debugging symbols. This class - * does nothing and should be optimized out entirely by the compiler. - */ -class NullOutStream -{ - public: - /** - * Does nothing. - */ - NullOutStream() { } - - /** - * Does nothing. - */ - NullOutStream(const NullOutStream& /* other */) { } - - //! Does nothing. - NullOutStream& operator<<(bool) { return *this; } - //! Does nothing. - NullOutStream& operator<<(short) { return *this; } - //! Does nothing. - NullOutStream& operator<<(unsigned short) { return *this; } - //! Does nothing. - NullOutStream& operator<<(int) { return *this; } - //! Does nothing. - NullOutStream& operator<<(unsigned int) { return *this; } - //! Does nothing. - NullOutStream& operator<<(long) { return *this; } - //! Does nothing. - NullOutStream& operator<<(unsigned long) { return *this; } - //! Does nothing. - NullOutStream& operator<<(float) { return *this; } - //! Does nothing. - NullOutStream& operator<<(double) { return *this; } - //! Does nothing. - NullOutStream& operator<<(long double) { return *this; } - //! Does nothing. - NullOutStream& operator<<(void*) { return *this; } - //! Does nothing. - NullOutStream& operator<<(const char*) { return *this; } - //! Does nothing. - NullOutStream& operator<<(std::string&) { return *this; } - //! Does nothing. - NullOutStream& operator<<(std::streambuf*) { return *this; } - //! Does nothing. - NullOutStream& operator<<(std::ostream& (*) (std::ostream&)) { return *this; } - //! Does nothing. - NullOutStream& operator<<(std::ios& (*) (std::ios&)) { return *this; } - //! Does nothing. - NullOutStream& operator<<(std::ios_base& (*) (std::ios_base&)) - { return *this; } - - //! Does nothing. - template - NullOutStream& operator<<(const T&) { return *this; } -}; - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/param.hpp b/src/sdk/mlpack/include/mlpack/core/util/param.hpp deleted file mode 100644 index b812887fb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/param.hpp +++ /dev/null @@ -1,1122 +0,0 @@ -/** - * @file param.hpp - * @author Matthew Amidon - * @author Ryan Curtin - * - * Definition of PARAM_*_IN() and PARAM_*_OUT() macros, as well as the - * PROGRAM_INFO() macro, which are used to define input and output parameters of - * command-line programs and bindings to other languages. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_PARAM_HPP -#define MLPACK_CORE_UTIL_PARAM_HPP - -// Required forward declarations. -namespace mlpack { -namespace data { - -class IncrementPolicy; - -template -class DatasetMapper; - -using DatasetInfo = DatasetMapper; - -} // namespace data -} // namespace mlpack - -/** - * Document an executable. Only one instance of this macro should be - * present in your program! Therefore, use it in the main.cpp - * (or corresponding executable) in your program. - * - * @see mlpack::CLI, PARAM_FLAG(), PARAM_INT_IN(), PARAM_DOUBLE_IN(), - * PARAM_STRING_IN(), PARAM_VECTOR_IN(), PARAM_INT_OUT(), PARAM_DOUBLE_OUT(), - * PARAM_VECTOR_OUT(), PARAM_INT_IN_REQ(), PARAM_DOUBLE_IN_REQ(), - * PARAM_STRING_IN_REQ(), PARAM_VECTOR_IN_REQ(), PARAM_INT_OUT_REQ(), - * PARAM_DOUBLE_OUT_REQ(), PARAM_VECTOR_OUT_REQ(), PARAM_STRING_OUT_REQ(). - * - * @param NAME Short string representing the name of the program. - * @param DESC Long string describing what the program does and possibly a - * simple usage example. Newlines should not be used here; this is taken - * care of by CLI (however, you can explicitly specify newlines to denote - * new paragraphs). - */ -#define PROGRAM_INFO(NAME, DESC) static mlpack::util::ProgramDoc \ - cli_programdoc_dummy_object = mlpack::util::ProgramDoc(NAME, \ - []() { return DESC; }) - -/** - * Define a flag parameter. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_FLAG(ID, DESC, ALIAS) \ - PARAM_IN(bool, ID, DESC, ALIAS, false, false); - -/** - * Define an integer input parameter. - * - * The parameter can then be specified on the command line with - * --ID=value. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * @param DEF Default value of the parameter. - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug -// Use a forward declaration of the class. - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_INT_IN(ID, DESC, ALIAS, DEF) \ - PARAM_IN(int, ID, DESC, ALIAS, DEF, false) - -/** - * Define an integer output parameter. This parameter will be printed on stdout - * at the end of the program; for instance, if the parameter name is "number" - * and the value is 5, the output on stdout would be of the following form: - * - * @code - * number: 5 - * @endcode - * - * If the parameter is not set by the end of the program, a fatal runtime error - * will be issued. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_INT_OUT(ID, DESC) \ - PARAM_OUT(int, ID, DESC, "", 0, false) - -/** - * Define a double input parameter. - * - * The parameter can then be specified on the command line with - * --ID=value. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * @param DEF Default value of the parameter. - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_DOUBLE_IN(ID, DESC, ALIAS, DEF) \ - PARAM_IN(double, ID, DESC, ALIAS, DEF, false) - -/** - * Define a double output parameter. This parameter will be printed on stdout - * at the end of the program; for instance, if the parameter name is "number" - * and the value is 5.012, the output on stdout would be of the following form: - * - * @code - * number: 5.012 - * @endcode - * - * If the parameter is not set by the end of the program, a fatal runtime error - * will be issued. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_DOUBLE_OUT(ID, DESC) \ - PARAM_OUT(double, ID, DESC, "", 0.0, false) - -/** - * Define a string input parameter. - * - * The parameter can then be specified on the command line with - * --ID=value. If ALIAS is equal to DEF_MOD (which is set using the - * PROGRAM_INFO() macro), the parameter can be specified with just --ID=value. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * @param DEF Default value of the parameter. - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_STRING_IN(ID, DESC, ALIAS, DEF) \ - PARAM_IN(std::string, ID, DESC, ALIAS, DEF, false) - -/** - * Define a string output parameter. - * - * The string will be printed to stdout at the end of the program. For - * instance, if there was a string output parameter called "something" with - * value "hello", at the end of the program the output would be of the following - * form: - * - * @code - * something: "hello" - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_STRING_OUT(ID, DESC, ALIAS) \ - PARAM_OUT(std::string, ID, DESC, ALIAS, "", false) - -/** - * Define a matrix input parameter. From the command line, the user can specify - * the file that holds the matrix, using the name of the matrix parameter with - * "_file" appended (and the same alias). So for instance, if the name of the - * matrix parameter was "mat", the user could specify that the "mat" matrix was - * held in matrix.csv by giving the parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_MATRIX_IN(ID, DESC, ALIAS) \ - PARAM_MATRIX(ID, DESC, ALIAS, false, true, true) - -/** - * Define a required matrix input parameter. From the command line, the user - * can specify the file that holds the matrix, using the name of the matrix - * parameter with "_file" appended (and the same alias). So for instance, if - * the name of the matrix parameter was "mat", the user could specify that the - * "mat" matrix was held in matrix.csv by giving the parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_MATRIX_IN_REQ(ID, DESC, ALIAS) \ - PARAM_MATRIX(ID, DESC, ALIAS, true, true, true) - -/** - * Define a matrix output parameter. When the program terminates, the matrix - * will be saved to whatever it was set to by CLI::GetParam(ID) - * during the program. From the command-line, the user may specify the file in - * which to save the output matrix using a string option that is the name of the - * matrix parameter with "_file" appended. So, for instance, if the name of the - * output matrix parameter was "mat", the user could speicfy that the "mat" - * matrix should be saved in matrix.csv by giving the parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * The output matrix will not be printed on stdout, like the other output option - * types. - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_MATRIX_OUT(ID, DESC, ALIAS) \ - PARAM_MATRIX(ID, DESC, ALIAS, false, true, false) - -/** - * Define a transposed matrix input parameter. This is useful when data is - * desired in row-major form instead of the usual column-major form. From the - * command line, the user can specify the file that holds the matrix, using the - * name of the matrix parameter with "_file" appended (and the same alias). So - * for instance, if the name of the matrix parameter was "mat", the user could - * specify that the "mat" matrix was held in matrix.csv by giving the parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_TMATRIX_IN(ID, DESC, ALIAS) \ - PARAM_MATRIX(ID, DESC, ALIAS, false, false, true) - -/** - * Define a required transposed matrix input parameter. This is useful when - * data is desired in row-major form instead of the usual column-major form. - * From the command line, the user can specify the file that holds the matrix, - * using the name of the matrix parameter with "_file" appended (and the same - * alias). So for instance, if the name of the matrix parameter was "mat", the - * user could specify that the "mat" matrix was held in matrix.csv by giving the - * parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_TMATRIX_IN_REQ(ID, DESC, ALIAS) \ - PARAM_MATRIX(ID, DESC, ALIAS, true, false, true) - -/** - * Define a transposed matrix output parameter. This is useful when data is - * stored in a row-major form instead of the usual column-major form. When the - * program terminates, the matrix will be saved to whatever it was set to by - * CLI::GetParam(ID) during the program. From the command-line, the - * user may specify the file in which to save the output matrix using a string - * option that is the name of the matrix parameter with "_file" appended. So, - * for instance, if the name of the output matrix parameter was "mat", the user - * could speicfy that the "mat" matrix should be saved in matrix.csv by giving - * the parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * The output matrix will not be printed on stdout, like the other output option - * types. - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_TMATRIX_OUT(ID, DESC, ALIAS) \ - PARAM_MATRIX(ID, DESC, ALIAS, false, false, false) - -/** - * Define an unsigned matrix input parameter (arma::Mat). From the - * command line, the user can specify the file that holds the matrix, using the - * name of the matrix parameter with "_file" appended (and the same alias). So - * for instance, if the name of the matrix parameter was "mat", the user could - * specify that the "mat" matrix was held in matrix.csv by giving the parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_UMATRIX_IN(ID, DESC, ALIAS) \ - PARAM_UMATRIX(ID, DESC, ALIAS, false, true, true) - -/** - * Define a required unsigned matrix input parameter (arma::Mat). From - * the command line, the user can specify the file that holds the matrix, using - * the name of the matrix parameter with "_file" appended (and the same alias). - * So for instance, if the name of the matrix parameter was "mat", the user - * could specify that the "mat" matrix was held in matrix.csv by giving the - * parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_UMATRIX_IN_REQ(ID, DESC, ALIAS) \ - PARAM_UMATRIX(ID, DESC, ALIAS, true, true, true) - -/** - * Define an unsigned matrix output parameter (arma::Mat). When the - * program terminates, the matrix will be saved to whatever it was set to by - * CLI::GetParam>(ID) during the program. From the - * command-line, the user may specify the file in which to save the output - * matrix using a string option that is the name of the matrix parameter with - * "_file" appended. So, for instance, if the name of the output matrix - * parameter was "mat", the user could speicfy that the "mat" matrix should be - * saved in matrix.csv by giving the parameter - * - * @code - * --mat_file matrix.csv - * @endcode - * - * The output matrix will not be printed on stdout, like the other output option - * types. - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_UMATRIX_OUT(ID, DESC, ALIAS) \ - PARAM_UMATRIX(ID, DESC, ALIAS, false, true, false) - - -/** - * Define a vector input parameter (type arma::vec). From the command line, the - * user can specify the file that holds the vector, using the name of the vector - * parameter with "_file" appended (and the same alias). So for instance, if - * the name of the vector parameter was "vec", the user could specify that the - * "vec" vector was held in vec.csv by giving the parameter: - * - * @code - * --vec_file vector.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_COL_IN(ID, DESC, ALIAS) \ - PARAM_COL(ID, DESC, ALIAS, false, true, true) - -/** - * Define a row vector input parameter (type arma::rowvec). From the command - * line, the user can specify the file that holds the vector, using the name of - * the vector parameter with "_file" appended (and the same alias). So for - * instance, if the name of the vector parameter was "vec", the user could - * specify that the "vec" vector was held in vec.csv by giving the parameter: - * - * @code - * --vec_file vector.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_ROW_IN(ID, DESC, ALIAS) \ - PARAM_ROW(ID, DESC, ALIAS, false, true, true) - -/** - * Define an unsigned vector input parameter (type arma::Col). From the - * command line, the user can specify the file that holds the vector, using the - * name of the vector parameter with "_file" appended (and the same alias). So - * for instance, if the name of the vector parameter was "vec", the user could - * specify that the "vec" vector was held in vec.csv by giving the parameter: - * - * @code - * --vec_file vector.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_UCOL_IN(ID, DESC, ALIAS) \ - PARAM_UCOL(ID, DESC, ALIAS, false, true, true) - -/** - * Define an unsigned row vector input parameter (type arma::Row). From - * the command line, the user can specify the file that holds the vector, using - * the name of the vector parameter with "_file" appended (and the same alias). - * So for instance, if the name of the vector parameter was "vec", the user - * could specify that the "vec" vector was held in vec.csv by giving the - * parameter: - * - * @code - * --vec_file vector.csv - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_UROW_IN(ID, DESC, ALIAS) \ - PARAM_UROW(ID, DESC, ALIAS, false, true, true) - -/** - * Define a vector output parameter (type arma::vec). When the program - * terminates, the vector will be saved to whatever it was set to during the - * program. From the command-line, the user may specify the file in which to - * save the output vector using a string option that is the name of the matrix - * parameter with "_file" appended. So, for instance, if the name of the output - * vector parameter was "vec", the user could specify that the "vec" vector - * should be saved in vector.csv by giving the parameter: - * - * @code - * --vec_file vector.csv - * @endcode - * - * The output vector will not be printed on stdout, like the other output option - * types. - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_COL_OUT(ID, DESC, ALIAS) \ - PARAM_COL(ID, DESC, ALIAS, false, true, false) - -/** - * Define a row vector output parameter (type arma::rowvec). When the program - * terminates, the vector will be saved to whatever it was set to during the - * program. From the command-line, the user may specify the file in which to - * save the output vector using a string option that is the name of the matrix - * parameter with "_file" appended. So, for instance, if the name of the output - * vector parameter was "vec", the user could specify that the "vec" vector - * should be saved in vector.csv by giving the parameter: - * - * @code - * --vec_file vector.csv - * @endcode - * - * The output vector will not be printed on stdout, like the other output option - * types. - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_ROW_OUT(ID, DESC, ALIAS) \ - PARAM_ROW(ID, DESC, ALIAS, false, true, false) - -/** - * Define an unsigned vector output parameter (type arma::Col). When - * the program terminates, the vector will be saved to whatever it was set to - * during the program. From the command-line, the user may specify the file in - * which to save the output vector using a string option that is the name of the - * matrix parameter with "_file" appended. So, for instance, if the name of the - * output vector parameter was "vec", the user could specify that the "vec" - * vector should be saved in vector.csv by giving the parameter: - * - * @code - * --vec_file vector.csv - * @endcode - * - * The output vector will not be printed on stdout, like the other output option - * types. - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_UCOL_OUT(ID, DESC, ALIAS) \ - PARAM_UCOL(ID, DESC, ALIAS, false, true, false) - -/** - * Define an unsigned row vector output parameter (type arma::Row). - * When the program terminates, the vector will be saved to whatever it was set - * to during the program. From the command-line, the user may specify the file - * in which to save the output vector using a string option that is the name of - * the matrix parameter with "_file" appended. So, for instance, if the name of - * the output vector parameter was "vec", the user could specify that the "vec" - * vector should be saved in vector.csv by giving the parameter: - * - * @code - * --vec_file vector.csv - * @endcode - * - * The output vector will not be printed on stdout, like the other output option - * types. - * - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_UROW_OUT(ID, DESC, ALIAS) \ - PARAM_UROW(ID, DESC, ALIAS, false, true, false) - -/** - * Define a std::vector input parameter. - * - * The parameter can then be specified on the command line with - * --ID=value1,value2,value3. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * @param DEF Default value of the parameter. - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_VECTOR_IN(T, ID, DESC, ALIAS) \ - PARAM_IN(std::vector, ID, DESC, ALIAS, std::vector(), false) - -/** - * Define a vector output parameter. This vector will be printed on stdout at - * the end of the program; for instance, if the parameter name is "vector" and - * the vector holds the array { 1, 2, 3, 4 }, the output on stdout would be of - * the following form: - * - * @code - * vector: 1, 2, 3, 4 - * @endcode - * - * If the parameter is not set by the end of the program, a fatal runtime error - * will be issued. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_VECTOR_OUT(T, ID, DESC, ALIAS) \ - PARAM_OUT(std::vector, ID, DESC, ALIAS, std::vector(), false) - -/** - * Define an input DatasetInfo/matrix parameter. From the command line, the - * user can specify the file that holds the matrix, using the name of the matrix - * parameter with "_file" appended (and the same alias). So for instance, if - * the name of the matrix parameter was "matrix", the user could specify that - * the "matrix" matrix was held in file.csv by giving the parameter - * - * @code - * --matrix_file file.csv - * @endcode - * - * Then the DatasetInfo and matrix type could be accessed with - * - * @code - * DatasetInfo d = std::move( - * CLI::GetParam>("matrix").get<0>()); - * arma::mat m = std::move( - * CLI::GetParam>("matrix").get<1>()); - * @endcode - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS One-character string representing the alias of the parameter. - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define TUPLE_TYPE std::tuple -#define PARAM_MATRIX_AND_INFO_IN(ID, DESC, ALIAS) \ - PARAM_IN(TUPLE_TYPE, ID, DESC, ALIAS, TUPLE_TYPE(), false) - -/** - * Define an input model. From the command line, the user can specify the file - * that holds the model, using the name of the model parameter with "_file" - * appended (and the same alias). So for instance, if the name of the model - * parameter was "model", the user could specify that the "model" model was held - * in model.bin by giving the parameter - * - * @code - * --model_file model.bin - * @endcode - * - * Note that the first parameter of this model is the type (the class name) of - * the model to be loaded. This model type must have a Serialize() function; a - * compilation error (a very long and complex one) will result if the model type - * does not have the following function: - * - * @code - * template - * void Serialize(Archive& ar, const unsigned int version); - * @endcode - * - * This is the boost::serialization serialize() function, just with a capital s - * for Serialize() (see src/mlpack/core/data/serialization_shim.hpp). - * - * @param TYPE Type of the model to be loaded. - * @param ID Name of the parameter. - * @param DESC Description of the parameter. - * @param ALIAS An alias for the parameter (one letter). - */ -#define PARAM_MODEL_IN(TYPE, ID, DESC, ALIAS) \ - PARAM_MODEL(TYPE, ID, DESC, ALIAS, false, true) - -/** - * Define a required input model. From the command line, the user can specify - * the file that holds the model, using the name of the model parameter with - * "_file" appended (and the same alias). So for instance, if the name of the - * model parameter was "model", the user could specify that the "model" model - * was held in model.bin by giving the parameter - * - * @code - * --model_file model.bin - * @endcode - * - * Note that the first parameter of this model is the type (the class name) of - * the model to be loaded. This model type must have a Serialize() function; a - * compilation error (a very long and complex one) will result if the model type - * does not have the following function: - * - * @code - * template - * void Serialize(Archive& ar, const unsigned int version); - * @endcode - * - * This is the boost::serialization serialize() function, just with a capital s - * for Serialize() (see src/mlpack/core/data/serialization_shim.hpp). - * - * @param TYPE Type of the model to be loaded. - * @param ID Name of the parameter. - * @param DESC Description of the parameter. - * @param ALIAS An alias for the parameter (one letter). - */ -#define PARAM_MODEL_IN_REQ(TYPE, ID, DESC, ALIAS) \ - PARAM_MODEL(TYPE, ID, DESC, ALIAS, true, true) - -/** - * Define an output model. From the command line, the user can specify the file - * that should hold the model, using the name of the model parameter with - * "_file" appended (and the same alias). So for instance, if the user desires - * to save the model to model.bin and the parameter name is "model", they could - * specify - * - * @code - * --model_file model.bin - * @endcode - * - * The model will be saved at the termination of the program. If you use a - * parameter of this type, you must call CLI::Destroy() at the end of your - * program. - * - * @param TYPE Type of the model to be saved. - * @param ID Name of the parameter. - * @param DESC Description of the parameter. - * @param ALIAS An alias for the parameter (one letter). - */ -#define PARAM_MODEL_OUT(TYPE, ID, DESC, ALIAS) \ - PARAM_MODEL(TYPE, ID, DESC, ALIAS, false, false) - -/** - * Define a required integer input parameter. - * - * The parameter must then be specified on the command line with --ID=value. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_INT_IN_REQ(ID, DESC, ALIAS) \ - PARAM_IN(int, ID, DESC, ALIAS, 0, true) - -/** - * Define a required double parameter. - * - * The parameter must then be specified on the command line with --ID=value. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_DOUBLE_IN_REQ(ID, DESC, ALIAS) \ - PARAM_IN(double, ID, DESC, ALIAS, 0.0, true) - -/** - * Define a required string parameter. - * - * The parameter must then be specified on the command line with --ID=value. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_STRING_IN_REQ(ID, DESC, ALIAS) \ - PARAM_IN(std::string, ID, DESC, ALIAS, "", true) - -/** - * Define a required vector parameter. - * - * The parameter must then be specified on the command line with - * --ID=value1,value2,value3. - * - * @param ID Name of the parameter. - * @param DESC Quick description of the parameter (1-2 sentences). - * @param ALIAS An alias for the parameter (one letter). - * - * @see mlpack::CLI, PROGRAM_INFO() - * - * @bug - * The __COUNTER__ variable is used in most cases to guarantee a unique global - * identifier for options declared using the PARAM_*() macros. However, not all - * compilers have this support--most notably, gcc < 4.3. In that case, the - * __LINE__ macro is used as an attempt to get a unique global identifier, but - * collisions are still possible, and they produce bizarre error messages. See - * https://github.com/mlpack/mlpack/issues/100 for more information. - */ -#define PARAM_VECTOR_IN_REQ(T, ID, DESC, ALIAS) \ - PARAM_IN(std::vector, ID, DESC, ALIAS, std::vector(), true); - -/** - * @cond - * Don't document internal macros. - */ - -// These are ugly, but necessary utility functions we must use to generate a -// unique identifier inside of the PARAM() module. -#define JOIN(x, y) JOIN_AGAIN(x, y) -#define JOIN_AGAIN(x, y) x ## y - -/** @endcond */ - -/** - * Define an input parameter. Don't use this function; use the other ones above - * that call it. Note that we are using the __LINE__ macro for naming these - * actual parameters when __COUNTER__ does not exist, which is a bit of an ugly - * hack... but this is the preprocessor, after all. We don't have much choice - * other than ugliness. - * - * @param T Type of the parameter. - * @param ID Name of the parameter. - * @param DESC Description of the parameter (1-2 sentences). - * @param ALIAS Alias for this parameter (one letter). - * @param DEF Default value of the parameter. - * @param REQ Whether or not parameter is required (boolean value). - */ -#ifdef __COUNTER__ - #define PARAM_IN(T, ID, DESC, ALIAS, DEF, REQ) \ - static mlpack::util::Option \ - JOIN(cli_option_dummy_object_in_, __COUNTER__) \ - (DEF, ID, DESC, ALIAS, #T, REQ, true, false, testName); - - #define PARAM_OUT(T, ID, DESC, ALIAS, DEF, REQ) \ - static mlpack::util::Option \ - JOIN(cli_option_dummy_object_out_, __COUNTER__) \ - (DEF, ID, DESC, ALIAS, #T, REQ, false, false, testName); - - #define PARAM_MATRIX(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option \ - JOIN(cli_option_dummy_matrix_, __COUNTER__) \ - (arma::mat(), ID, DESC, ALIAS, "arma::mat", \ - REQ, IN, !TRANS, testName); - - #define PARAM_UMATRIX(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option> \ - JOIN(cli_option_dummy_umatrix_, __COUNTER__) \ - (arma::Mat(), ID, DESC, ALIAS, "arma::Mat", \ - REQ, IN, !TRANS, testName); - - #define PARAM_COL(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option \ - JOIN(cli_option_dummy_col_, __COUNTER__) \ - (arma::vec(), ID, DESC, ALIAS, "arma::vec", \ - REQ, IN, !TRANS, testName); - - #define PARAM_UCOL(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option> \ - JOIN(cli_option_dummy_ucol_, __COUNTER__) \ - (arma::Col(), ID, DESC, ALIAS, "arma::Col", \ - REQ, IN, !TRANS, testName); - - #define PARAM_ROW(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option \ - JOIN(cli_option_dummy_row_, __COUNTER__) \ - (arma::rowvec(), ID, DESC, ALIAS, "arma::rowvec", \ - REQ, IN, !TRANS, testName); - - #define PARAM_UROW(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option> \ - JOIN(cli_option_dummy_urow_, __COUNTER__) \ - (arma::Row(), ID, DESC, ALIAS, "arma::Row", \ - REQ, IN, !TRANS, testName); - - // There are no uses of required models, so that is not an option to this - // macro (it would be easy to add). - #define PARAM_MODEL(TYPE, ID, DESC, ALIAS, REQ, IN) \ - static mlpack::util::Option \ - JOIN(cli_option_dummy_model_, __COUNTER__) \ - (nullptr, ID, DESC, ALIAS, #TYPE, REQ, IN, false, testName); -#else - // We have to do some really bizarre stuff since __COUNTER__ isn't defined. I - // don't think we can absolutely guarantee success, but it should be "good - // enough". We use the __LINE__ macro and the type of the parameter to try - // and get a good guess at something unique. - #define PARAM_IN(T, ID, DESC, ALIAS, DEF, REQ) \ - static mlpack::util::Option \ - JOIN(JOIN(cli_option_dummy_object_in_, __LINE__), opt) \ - (DEF, ID, DESC, ALIAS, #T, REQ, true, false, testName); - - #define PARAM_OUT(T, ID, DESC, ALIAS, DEF, REQ) \ - static mlpack::util::Option \ - JOIN(JOIN(cli_option_dummy_object_out_, __LINE__), opt) \ - (DEF, ID, DESC, ALIAS, #T, REQ, false, false, testName); - - #define PARAM_MATRIX(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option \ - JOIN(JOIN(cli_option_dummy_object_matrix_, __LINE__), opt) \ - (arma::mat(), ID, DESC, ALIAS, "arma::mat", REQ, IN, !TRANS, \ - testName); - - #define PARAM_UMATRIX(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option> \ - JOIN(JOIN(cli_option_dummy_object_umatrix_, __LINE__), opt) \ - (arma::Mat(), ID, DESC, ALIAS, "arma::Mat", REQ, IN, \ - !TRANS, testName); - - #define PARAM_COL(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option \ - JOIN(cli_option_dummy_object_col_, __LINE__) \ - (arma::vec(), ID, DESC, ALIAS, "arma::vec", REQ, IN, !TRANS, \ - testName); - - #define PARAM_UCOL(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option> \ - JOIN(cli_option_dummy_object_ucol_, __LINE__) \ - (arma::Col(), ID, DESC, ALIAS, "arma::Col", REQ, IN, \ - !TRANS, testName); - - #define PARAM_ROW(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option \ - JOIN(cli_option_dummy_object_row_, __LINE__) \ - (arma::rowvec(), ID, DESC, ALIAS, "arma::rowvec", REQ, IN, !TRANS, \ - testName); - - #define PARAM_UROW(ID, DESC, ALIAS, REQ, TRANS, IN) \ - static mlpack::util::Option> \ - JOIN(cli_option_dummy_object_urow_, __LINE__) \ - (arma::Row(), ID, DESC, ALIAS, "arma::Row", REQ, IN, \ - !TRANS, testName); - - #define PARAM_MODEL(TYPE, ID, DESC, ALIAS, REQ, IN) \ - static mlpack::util::Option \ - JOIN(JOIN(cli_option_dummy_object_model_, __LINE__), opt) \ - (nullptr, ID, DESC, ALIAS, #TYPE, REQ, IN, false, \ - testName); -#endif - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/param_checks.hpp b/src/sdk/mlpack/include/mlpack/core/util/param_checks.hpp deleted file mode 100644 index 665157992..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/param_checks.hpp +++ /dev/null @@ -1,212 +0,0 @@ -/** - * @file param_checks.hpp - * @author Ryan Curtin - * - * A set of utility functions to check parameter values for mlpack programs. - * These are meant to be used as the first part of an mlpackMain() function, to - * validate parameters. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_PARAM_CHECKS_HPP -#define MLPACK_CORE_UTIL_PARAM_CHECKS_HPP - -#include - -namespace mlpack { -namespace util { - -/** - * Require that only one of the given parameters in the constraints set was - * passed to the CLI object; otherwise, issue a warning or fatal error, - * optionally with the given custom error message. - * - * This uses the correct binding type name for each parameter (i.e. - * '--parameter' for CLI bindings, 'parameter' for Python bindings). - * - * If you use a custom error message, be aware that the given output will be - * similar to, for example: - * - * @code - * Must specify one of '--reference_file (-r)' or '--input_model_file (-m)'; - * ! - * @endcode - * - * so when you write your custom error message, be sure that the sentence makes - * sense. The custom error message should not have a capitalized first - * character and no ending punctuation (a '!' will be added by this function). - * - * @param constraints Set of parameters from which only one should be passed. - * @param fatal If true, output goes to Log::Fatal instead of Log::Warn and an - * exception is thrown. - * @param customErrorMessage Error message to append. - */ -void RequireOnlyOnePassed( - const std::vector& constraints, - const bool fatal = true, - const std::string& customErrorMessage = ""); - -/** - * Require that at least one of the given parameters in the constraints set was - * passed to the CLI object; otherwise, issue a warning or fatal error, - * optionally with the given custom error message. - * - * This uses the correct binding type name for each parameter (i.e. - * '--parameter' for CLI bindings, 'parameter' for Python bindings). - * - * This can be used with a set of only one constraint and the output is still - * sensible. - * - * If you use a custom error message, be aware that the given output will be - * similar to, for example: - * - * @code - * Should pass one of '--codes_file (-c)', '--dictionary_file (-d)', or - * '--output_model_file (-M)'; ! - * @endcode - * - * so when you write your custom error message, be sure that the sentence makes - * sense. The custom error message should not have a capitalized first - * character and no ending punctuation (a '!' will be added by this function). - * - * @param constraints Set of parameters from which only one should be passed. - * @param fatal If true, output goes to Log::Fatal instead of Log::Warn and an - * exception is thrown. - * @param customErrorMessage Error message to append. - */ -void RequireAtLeastOnePassed( - const std::vector& constraints, - const bool fatal = true, - const std::string& customErrorMessage = ""); - -/** - * Require that either none or all of the given parameters in the constraints - * set were passed to the CLI object; otherwise, issue a warning or fatal error, - * optionally with the given custom error message. - * - * This uses the correct binding type name for each parameter (i.e. - * '--parameter' for CLI bindings, 'parameter' for Python bindings). - * - * If you use a custom error message, be aware that the given output will be - * similar to, for example: - * - * @code - * Must pass none or all of '--codes_file (-c)', '--dictionary_file (-d)', and - * '--output_model_file (-M)'; ! - * @endcode - * - * so when you write your custom error message, be sure that the sentence makes - * sense. The custom error message should not have a capitalized first - * character and no ending punctuation (a '!' will be added by this function). - * - * @param constraints Set of parameters of which none or all should be passed. - * @param fatal If true, output goes to Log::Fatal instead of Log::Warn and an - * exception is thrown. - * @param customErrorMessage Error message to append. - */ -void RequireNoneOrAllPassed( - const std::vector& constraints, - const bool fatal = true, - const std::string& customErrorMessage = ""); - -/** - * Require that a given parameter is in a set of allowable parameters. This is - * probably most useful with T = std::string. If fatal is true, then an - * exception is thrown. An error message is not optional and must be specified. - * The error message does _not_ need to specify the values in the set; this - * function will already output them. So, for example, the output may be - * similar to: - * - * @code - * Invalid value of '--weak_learner (-w)' specified ('something'); ; must be one of 'decision_stump', or 'perceptron'! - * @endcode - * - * so when you write the error message, make sure that the message makes sense. - * For example, in the message above, a good error message might be "unknown - * weak learner type". - * - * @tparam T Type of parameter. - * @param paramName Name of parameter to check. - * @param set Set of valid values for parameter. - * @param fatal If true, an exception is thrown and output goes to Log::Fatal. - * @param errorMessage Error message to output. - */ -template -void RequireParamInSet(const std::string& paramName, - const std::vector& set, - const bool fatal, - const std::string& errorMessage); - -/** - * Require that a given parameter satisfies the given conditional function. - * This is useful for, e.g., checking that a given parameter is greater than 0. - * If fatal is true, then an exception is thrown. An error message is not - * optional and must be specified. The error message should specify, in clear - * terms, what the value of the parameter *should* be. So, for example, the - * output may be similar to: - * - * @code - * Invalid value of '--iterations (-i)' specified (-1); ! - * @endcode - * - * and in this case a good error message might be "number of iterations must be - * positive". Be sure that when you write the error message, the message makes - * sense. - * - * @tparam T Type of parameter to check. - * @param paramName Name of parameter to check. - * @param conditional Function to use to check parameter value; should return - * 'true' if the parameter value is okay. - * @param fatal If true, an exception is thrown and output goes to Log::Fatal. - * @param errorMessage Error message to output. - */ -template -void RequireParamValue(const std::string& paramName, - const std::function& conditional, - const bool fatal, - const std::string& errorMessage); - -/** - * Report that a parameter is ignored, if each of the constraints given are - * satisfied. The constraints should be a set of string/bool pairs. If all of - * the constraints are true, and the given parameter in 'paramName' is passed, - * then a warning will be issued noting that the parameter is ignored. The - * warning will go to Log::Warn. - * - * @param constraints Set of constraints. - * @param paramName Name of parameter to check. - */ -void ReportIgnoredParam( - const std::vector>& constraints, - const std::string& paramName); - -/** - * If the given parameter is passed, report that it is ignored, supplying a - * custom reason. The reason should specify, in short and clear terms, why the - * parameter is ignored. So, for example, the output may be similar to: - * - * @code - * --iterations (-i) ignored because . - * @endcode - * - * and in this case a good reason might be "SGD is not being used as an - * optimizer". Be sure that when you write the reason, the full message makes - * sense. - * - * @param paramName Name of parameter to check. - * @param reason Reason that parameter is ignored, if it is passed. - */ -void ReportIgnoredParam(const std::string& paramName, - const std::string& reason); - -} // namespace util -} // namespace mlpack - -// Include implementation. -#include "param_checks_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/param_checks_impl.hpp b/src/sdk/mlpack/include/mlpack/core/util/param_checks_impl.hpp deleted file mode 100644 index b05b2d50b..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/param_checks_impl.hpp +++ /dev/null @@ -1,304 +0,0 @@ -/** - * @file param_checks_impl.hpp - * @author Ryan Curtin - * - * Utility function implementation for checking arguments, and so forth. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_PARAM_CHECKS_IMPL_HPP -#define MLPACK_CORE_UTIL_PARAM_CHECKS_IMPL_HPP - -#include "param_checks.hpp" - -namespace mlpack { -namespace util { - -// Check that the arguments are given. -inline void RequireOnlyOnePassed( - const std::vector& constraints, - const bool fatal, - const std::string& errorMessage) -{ - if (BINDING_IGNORE_CHECK(constraints)) - return; - - size_t set = 0; - for (size_t i = 0; i < constraints.size(); ++i) - { - if (CLI::HasParam(constraints[i])) - ++set; - } - - util::PrefixedOutStream& stream = fatal ? Log::Fatal : Log::Warn; - if (set > 1) - { - // Give different output depending on whether 2 or more parameters are - // given. - if (constraints.size() == 2) - { - stream << "Can only pass one of " << PRINT_PARAM_STRING(constraints[0]) - << " or " << PRINT_PARAM_STRING(constraints[1]); - } - else - { - stream << "Can only pass one of "; - for (size_t i = 0 ; i < constraints.size() - 1; ++i) - stream << PRINT_PARAM_STRING(constraints[i]) << ", "; - stream << "or " - << PRINT_PARAM_STRING(constraints[constraints.size() - 1]); - } - - // Append a custom message. - if (!errorMessage.empty()) - stream << "; " << errorMessage; - stream << "!" << std::endl; - } - else if (set == 0) - { - stream << (fatal ? "Must " : "Should "); - - // Give different output depending on whether 1, 2, or more parameters are - // given. - if (constraints.size() == 1) - { - stream << "specify " << PRINT_PARAM_STRING(constraints[0]); - } - else if (constraints.size() == 2) - { - stream << "specify one of " << PRINT_PARAM_STRING(constraints[0]) - << " or " << PRINT_PARAM_STRING(constraints[1]); - } - else - { - stream << "specify one of "; - for (size_t i = 0; i < constraints.size() - 1; ++i) - stream << PRINT_PARAM_STRING(constraints[i]) << ", "; - stream << "or " - << PRINT_PARAM_STRING(constraints[constraints.size() - 1]); - } - - // Append a custom message. - if (!errorMessage.empty()) - stream << "; " << errorMessage; - stream << "!" << std::endl; - } -} - -inline void RequireAtLeastOnePassed( - const std::vector& constraints, - const bool fatal, - const std::string& errorMessage) -{ - if (BINDING_IGNORE_CHECK(constraints)) - return; - - size_t set = 0; - for (size_t i = 0; i < constraints.size(); ++i) - { - if (CLI::HasParam(constraints[i])) - ++set; - } - - if (set == 0) - { - util::PrefixedOutStream& stream = fatal ? Log::Fatal : Log::Warn; - stream << (fatal ? "Must " : "Should "); - if (constraints.size() == 1) - { - // This shouldn't happen... just use PARAM_*_REQ()... - stream << "pass " << PRINT_PARAM_STRING(constraints[0]); - } - else if (constraints.size() == 2) - { - stream << "pass either " << PRINT_PARAM_STRING(constraints[0]) - << " or " << PRINT_PARAM_STRING(constraints[1]) << " or both"; - } - else - { - stream << "pass one of "; - for (size_t i = 0; i < constraints.size() - 1; ++i) - stream << PRINT_PARAM_STRING(constraints[i]) << ", "; - stream << "or " - << PRINT_PARAM_STRING(constraints[constraints.size() - 1]); - } - - // Append custom error message. - if (!errorMessage.empty()) - stream << "; " << errorMessage << "!" << std::endl; - else - stream << "!" << std::endl; - } -} - -inline void RequireNoneOrAllPassed( - const std::vector& constraints, - const bool fatal, - const std::string& errorMessage) -{ - if (BINDING_IGNORE_CHECK(constraints)) - return; - - size_t set = 0; - for (size_t i = 0; i < constraints.size(); ++i) - { - if (CLI::HasParam(constraints[i])) - ++set; - } - - if (set != 0 && set < constraints.size()) - { - util::PrefixedOutStream& stream = fatal ? Log::Fatal : Log::Warn; - stream << (fatal ? "Must " : "Should "); - if (constraints.size() == 2) - { - stream << "pass none or both of " << PRINT_PARAM_STRING(constraints[0]) - << " and " << PRINT_PARAM_STRING(constraints[1]); - } - else - { - // constraints.size() > 2. - stream << "pass none or all of "; - for (size_t i = 0; i < constraints.size() - 1; ++i) - stream << PRINT_PARAM_STRING(constraints[i]) << ", "; - stream << "and " - << PRINT_PARAM_STRING(constraints[constraints.size() - 1]); - } - - // Append custom error message. - if (!errorMessage.empty()) - stream << "; " << errorMessage << "!" << std::endl; - else - stream << "!" << std::endl; - } -} - -template -void RequireParamInSet(const std::string& name, - const std::vector& set, - const bool fatal, - const std::string& errorMessage) -{ - if (BINDING_IGNORE_CHECK(name)) - return; - - if (std::find(set.begin(), set.end(), CLI::GetParam(name)) == set.end()) - { - // The item was not found in the set. - util::PrefixedOutStream& stream = fatal ? Log::Fatal : Log::Warn; - stream << "Invalid value of " << PRINT_PARAM_STRING(name) << " specified (" - << PRINT_PARAM_VALUE(CLI::GetParam(name), true) << "); "; - if (!errorMessage.empty()) - stream << errorMessage << "; "; - stream << "must be one of "; - for (size_t i = 0; i < set.size() - 1; ++i) - stream << PRINT_PARAM_VALUE(set[i], true) << ", "; - stream << "or " << PRINT_PARAM_VALUE(set[set.size() - 1], true) << "!" - << std::endl; - } -} - -template -void RequireParamValue(const std::string& name, - const std::function& conditional, - const bool fatal, - const std::string& errorMessage) -{ - if (BINDING_IGNORE_CHECK(name)) - return; - - // We need to make sure that the condition holds. - bool condition = conditional(CLI::GetParam(name)); - if (!condition) - { - // The condition failed. - util::PrefixedOutStream& stream = fatal ? Log::Fatal : Log::Warn; - stream << "Invalid value of " << PRINT_PARAM_STRING(name) << " specified (" - << PRINT_PARAM_VALUE(CLI::GetParam(name), false) << "); " - << errorMessage << "!" << std::endl; - } -} - -inline void ReportIgnoredParam( - const std::vector>& constraints, - const std::string& paramName) -{ - if (BINDING_IGNORE_CHECK(paramName)) - return; - - // Determine whether or not the condition is true. - bool condition = true; - for (size_t i = 0; i < constraints.size(); ++i) - { - if (CLI::HasParam(constraints[i].first) != constraints[i].second) - { - condition = false; - break; - } - } - - // If the condition is satisfied, then report that the parameter is ignored - // (if the user passed it). - if (condition && CLI::HasParam(paramName)) - { - // The output will be different depending on whether there are 1, 2, or more - // constraints. - Log::Warn << PRINT_PARAM_STRING(paramName) << " ignored because "; - if (constraints.size() == 1) - { - Log::Warn << PRINT_PARAM_STRING(constraints[0].first) - << ((constraints[0].second) ? " is " : " is not ") - << "specified!" << std::endl; - } - else if (constraints.size() == 2) - { - if (constraints[0].second == constraints[1].second) - { - Log::Warn << ((constraints[0].second) ? "both " : "neither ") - << PRINT_PARAM_STRING(constraints[0].first) - << ((constraints[0].second) ? "or " : "nor ") - << PRINT_PARAM_STRING(constraints[1].first) - << " are specified!" << std::endl; - } - else - { - Log::Warn << PRINT_PARAM_STRING(constraints[0].first) - << ((constraints[0].second) ? " is " : " is not ") - << "specified and " - << ((constraints[1].second) ? " is " : " is not ") - << "specified!" << std::endl; - } - } - else - { - // List each constraint and whether or not it was or wasn't specified. - for (size_t i = 0; i < constraints.size(); ++i) - { - Log::Warn << PRINT_PARAM_STRING(constraints[i].first) - << ((constraints[i].second) ? " is " : " is not ") - << ((i == constraints.size() - 1) ? "specified!" - : "specified and "); - } - Log::Warn << std::endl; - } - } -} - -inline void ReportIgnoredParam(const std::string& paramName, - const std::string& reason) -{ - // If the argument was passed, we need to print the reason. - if (CLI::HasParam(paramName)) - { - Log::Warn << PRINT_PARAM_STRING(paramName) << " ignored because " - << reason << "!" << std::endl; - } -} - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/param_data.hpp b/src/sdk/mlpack/include/mlpack/core/util/param_data.hpp deleted file mode 100644 index 278786d08..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/param_data.hpp +++ /dev/null @@ -1,90 +0,0 @@ -/** - * @file param_data.hpp - * @author Ryan Curtin - * - * This defines the structure that holds information for each command-line - * parameter, as well as utility functions it is used with. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_PARAM_DATA_HPP -#define MLPACK_CORE_UTIL_PARAM_DATA_HPP - -#include -#include - -/** - * The TYPENAME macro is used internally to convert a type into a string. - */ -#define TYPENAME(x) (std::string(typeid(x).name())) - -namespace mlpack { -namespace data { - -class IncrementPolicy; - -template -class DatasetMapper; - -using DatasetInfo = DatasetMapper; - -} // namespace data -} // namespace mlpack - -namespace mlpack { -namespace util { - -/** - * This structure holds all of the information about a single parameter, - * including its value (which is set when ParseCommandLine() is called). It - * does not hold any information about whether or not it was passed---that is - * handled elsewhere. A ParamData struct is only useful in order to get - * "static" information about a parameter. Note that some parameter types have - * internal types but also different types that are used by - * boost::program_options (specifically, matrix and model types map to strings). - * - * This structure is somewhat unwieldy and is likely to be refactored at some - * point in the future, but for now it does the job fine. - */ -struct ParamData -{ - //! Name of this parameter. This is the name used for HasParam() and - //! GetParam(). - std::string name; - //! Description of this parameter, if any. - std::string desc; - //! Type information of this parameter. Note that this is TYPENAME() of the - //! user-visible parameter type, not whatever is given by ParameterType<>. - std::string tname; - //! Alias for this parameter. - char alias; - //! True if the option was passed to the program. Note that wasPassed may be - //! set by either ParseCommandLine() or SetPassed(). - bool wasPassed; - //! True if this is a matrix that should not be transposed. Ignored if the - //! parameter is not a matrix. - bool noTranspose; - //! True if this option is required. - bool required; - //! True if this option is an input option (otherwise, it is output). - bool input; - //! If this is an input parameter that needs extra loading, this indicates - //! whether or not it has been loaded. - bool loaded; - //! If this should be preserved across different settings (i.e. if it should - //! exist for every binding), this should be set to true. - bool persistent; - //! The actual value that is held. If the user has passed a different type, - //! this may be a tuple containing multiple values. - boost::any value; - //! The true name of the type, as it would be written in C++. - std::string cppType; -}; - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/prefixedoutstream.hpp b/src/sdk/mlpack/include/mlpack/core/util/prefixedoutstream.hpp deleted file mode 100644 index 6078edde1..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/prefixedoutstream.hpp +++ /dev/null @@ -1,176 +0,0 @@ -/** - * @file prefixedoutstream.hpp - * @author Ryan Curtin - * @author Matthew Amidon - * - * Declaration of the PrefixedOutStream class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_PREFIXEDOUTSTREAM_HPP -#define MLPACK_CORE_UTIL_PREFIXEDOUTSTREAM_HPP - -#include - -namespace mlpack { -namespace util { - -/** - * Allows us to output to an ostream with a prefix at the beginning of each - * line, in the same way we would output to cout or cerr. The prefix is - * specified in the constructor (as well as the destination ostream). A newline - * must be passed to the stream, and then the prefix will be prepended to the - * next line. For example, - * - * @code - * PrefixedOutStream outstr(std::cout, "[TEST] "); - * outstr << "Hello world I like " << 7.5; - * outstr << "...Continue" << std::endl; - * outstr << "After the CR\n" << std::endl; - * @endcode - * - * would give, on std::cout, - * - * @code - * [TEST] Hello world I like 7.5...Continue - * [TEST] After the CR - * [TEST] - * @endcode - * - * These objects are used for the mlpack::Log levels (DEBUG, INFO, WARN, and - * FATAL). - */ -class PrefixedOutStream -{ - public: - /** - * Set up the PrefixedOutStream. - * - * @param destination ostream which receives output from this object. - * @param prefix The prefix to prepend to each line. - * @param ignoreInput If true, the stream will not be printed. - * @param fatal If true, a std::runtime_error exception is thrown after - * printing a newline. - * @param backtrace If true, attempt to print a backtrace (will only be - * done if HAS_BFD_DL is defined). - */ - PrefixedOutStream(std::ostream& destination, - const char* prefix, - bool ignoreInput = false, - bool fatal = false, - bool backtrace = true) : - destination(destination), - ignoreInput(ignoreInput), - backtrace(backtrace), - prefix(prefix), - // We want the first call to operator<< to prefix the prefix so we set - // carriageReturned to true. - carriageReturned(true), - fatal(fatal) - { /* nothing to do */ } - - //! Write a bool to the stream. - PrefixedOutStream& operator<<(bool val); - //! Write a short to the stream. - PrefixedOutStream& operator<<(short val); - //! Write an unsigned short to the stream. - PrefixedOutStream& operator<<(unsigned short val); - //! Write an int to the stream. - PrefixedOutStream& operator<<(int val); - //! Write an unsigned int to the stream. - PrefixedOutStream& operator<<(unsigned int val); - //! Write a long to the stream. - PrefixedOutStream& operator<<(long val); - //! Write an unsigned long to the stream. - PrefixedOutStream& operator<<(unsigned long val); - //! Write a float to the stream. - PrefixedOutStream& operator<<(float val); - //! Write a double to the stream. - PrefixedOutStream& operator<<(double val); - //! Write a long double to the stream. - PrefixedOutStream& operator<<(long double val); - //! Write a void pointer to the stream. - PrefixedOutStream& operator<<(void* val); - //! Write a character array to the stream. - PrefixedOutStream& operator<<(const char* str); - //! Write a string to the stream. - PrefixedOutStream& operator<<(std::string& str); - //! Write a streambuf to the stream. - PrefixedOutStream& operator<<(std::streambuf* sb); - //! Write an ostream manipulator function to the stream. - PrefixedOutStream& operator<<(std::ostream& (*pf)(std::ostream&)); - //! Write an ios manipulator function to the stream. - PrefixedOutStream& operator<<(std::ios& (*pf)(std::ios&)); - //! Write an ios_base manipulator function to the stream. - PrefixedOutStream& operator<<(std::ios_base& (*pf)(std::ios_base&)); - - //! Write anything else to the stream. - template - PrefixedOutStream& operator<<(const T& s); - - //! The output stream that all data is to be sent to; example: std::cout. - std::ostream& destination; - - //! Discards input, prints nothing if true. - bool ignoreInput; - - //! If true, on a fatal error, a backtrace will be printed if HAS_BFD_DL is - //! defined. - bool backtrace; - - private: - /** - * Conducts the base logic required in all the operator << overloads. Mostly - * just a good idea to reduce copy-pasta. - * - * This overload is for non-Armadillo objects, which need special handling - * during printing. - * - * @tparam T The type of the data to output. - * @param val The The data to be output. - */ - template - typename std::enable_if::value>::type - BaseLogic(const T& val); - - /** - * Conducts the base logic required in all the operator << overloads. Mostly - * just a good idea to reduce copy-pasta. - * - * This overload is for Armadillo objects, which need special handling during - * printing. - * - * @tparam T The type of the data to output. - * @param val The The data to be output. - */ - template - typename std::enable_if::value>::type - BaseLogic(const T& val); - - /** - * Output the prefix, but only if we need to and if we are allowed to. - */ - inline void PrefixIfNeeded(); - - //! Contains the prefix we must prepend to each line. - std::string prefix; - - //! If true, the previous call to operator<< encountered a CR, and a prefix - //! will be necessary. - bool carriageReturned; - - //! If true, a std::runtime_error exception will be thrown when a CR is - //! encountered. - bool fatal; -}; - -} // namespace util -} // namespace mlpack - -// Template definitions. -#include "prefixedoutstream_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/prefixedoutstream_impl.hpp b/src/sdk/mlpack/include/mlpack/core/util/prefixedoutstream_impl.hpp deleted file mode 100644 index 0ac5f06d7..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/prefixedoutstream_impl.hpp +++ /dev/null @@ -1,293 +0,0 @@ -/** - * @file prefixedoutstream.hpp - * @author Ryan Curtin - * @author Matthew Amidon - * - * Implementation of templated PrefixedOutStream member functions. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_PREFIXEDOUTSTREAM_IMPL_HPP -#define MLPACK_CORE_UTIL_PREFIXEDOUTSTREAM_IMPL_HPP - -// Just in case it hasn't been included. -#include "prefixedoutstream.hpp" - -#ifdef HAS_BFD_DL - #include "backtrace.hpp" -#endif - -#include -#include - -namespace mlpack { -namespace util { - -template -PrefixedOutStream& PrefixedOutStream::operator<<(const T& s) -{ - BaseLogic(s); - return *this; -} - -// For non-Armadillo types. -template -typename std::enable_if::value>::type -PrefixedOutStream::BaseLogic(const T& val) -{ - // We will use this to track whether or not we need to terminate at the end of - // this call (only for streams which terminate after a newline). - bool newlined = false; - std::string line; - - // If we need to, output the prefix. - PrefixIfNeeded(); - - std::ostringstream convert; - // Sync flags and precision with destination stream - convert.setf(destination.flags()); - convert.precision(destination.precision()); - convert << val; - - if (convert.fail()) - { - PrefixIfNeeded(); - if (!ignoreInput) - { - destination << "Failed type conversion to string for output; output not " - "shown." << std::endl; - newlined = true; - } - } - else - { - line = convert.str(); - - // If the length of the casted thing was 0, it may have been a stream - // manipulator, so send it directly to the stream and don't ask questions. - if (line.length() == 0) - { - // The prefix cannot be necessary at this point. - if (!ignoreInput) // Only if the user wants it. - destination << val; - - return; - } - - // Now, we need to check for newlines in the output and print it. - size_t nl; - size_t pos = 0; - while ((nl = line.find('\n', pos)) != std::string::npos) - { - PrefixIfNeeded(); - - // Only output if the user wants it. - if (!ignoreInput) - { - destination << line.substr(pos, nl - pos); - destination << std::endl; - } - - newlined = true; // Ensure this is set for the fatal exception if needed. - carriageReturned = true; // Regardless of whether or not we display it. - - pos = nl + 1; - } - - if (pos != line.length()) // We need to display the rest. - { - PrefixIfNeeded(); - if (!ignoreInput) - destination << line.substr(pos); - } - } - - // If we displayed a newline and we need to throw afterwards, do that. - if (fatal && newlined) - { - if (!ignoreInput) - destination << std::endl; - - // Print a backtrace, if we can. -#ifdef HAS_BFD_DL - if (fatal && !ignoreInput && backtrace) - { - size_t nl; - size_t pos = 0; - - Backtrace bt; - std::string btLine = bt.ToString(); - while ((nl = btLine.find('\n', pos)) != std::string::npos) - { - PrefixIfNeeded(); - - if (!ignoreInput) - { - destination << btLine.substr(pos, nl - pos); - destination << std::endl; - } - - carriageReturned = true; // Regardless of whether or not we display it. - - pos = nl + 1; - } - } -#endif - - throw std::runtime_error("fatal error; see Log::Fatal output"); - } -} - -// For Armadillo types. -template -typename std::enable_if::value>::type -PrefixedOutStream::BaseLogic(const T& val) -{ - // Extract printable object from the input. - const arma::Mat& printVal(val); - - // We will use this to track whether or not we need to terminate at the end of - // this call (only for streams which terminate after a newline). - bool newlined = false; - std::string line; - - // If we need to, output the prefix. - PrefixIfNeeded(); - - std::ostringstream convert; - - // Check if the stream is in the default state. - if (destination.flags() == convert.flags() && - destination.precision() == convert.precision()) - { - printVal.print(convert); - } - else - { - // Sync flags and precision with destination stream - convert.setf(destination.flags()); - convert.precision(destination.precision()); - - // Set width of the convert stream. - const arma::Mat& absVal(arma::abs(printVal)); - double maxVal = absVal.max(); - - if (maxVal == 0.0) - maxVal = 1; - - int maxLog = log10(maxVal); - maxLog = (maxLog > 0) ? floor(maxLog) + 1 : 1; - const int padding = 4; - convert.width(convert.precision() + maxLog + padding); - printVal.raw_print(convert); - } - - if (convert.fail()) - { - PrefixIfNeeded(); - if (!ignoreInput) - { - destination << "Failed type conversion to string for output; output not " - "shown." << std::endl; - newlined = true; - } - } - else - { - line = convert.str(); - - // If the length of the casted thing was 0, it may have been a stream - // manipulator, so send it directly to the stream and don't ask questions. - if (line.length() == 0) - { - // The prefix cannot be necessary at this point. - if (!ignoreInput) // Only if the user wants it. - destination << val; - - return; - } - - // Now, we need to check for newlines in the output and print it. - size_t nl; - size_t pos = 0; - while ((nl = line.find('\n', pos)) != std::string::npos) - { - PrefixIfNeeded(); - - // Only output if the user wants it. - if (!ignoreInput) - { - destination << line.substr(pos, nl - pos); - destination << std::endl; - } - - newlined = true; // Ensure this is set for the fatal exception if needed. - carriageReturned = true; // Regardless of whether or not we display it. - - pos = nl + 1; - } - - if (pos != line.length()) // We need to display the rest. - { - PrefixIfNeeded(); - if (!ignoreInput) - destination << line.substr(pos); - } - } - - // If we displayed a newline and we need to throw afterwards, do that. - if (fatal && newlined) - { - if (!ignoreInput) - destination << std::endl; - - // Print a backtrace, if we can. -#ifdef HAS_BFD_DL - if (fatal && !ignoreInput) - { - size_t nl; - size_t pos = 0; - - Backtrace bt; - std::string btLine = bt.ToString(); - while ((nl = btLine.find('\n', pos)) != std::string::npos) - { - PrefixIfNeeded(); - - if (!ignoreInput) - { - destination << btLine.substr(pos, nl - pos); - destination << std::endl; - } - - carriageReturned = true; // Regardless of whether or not we display it. - - pos = nl + 1; - } - } -#endif - - throw std::runtime_error("fatal error; see Log::Fatal output"); - } -} - -// This is an inline function (that is why it is here and not in .cc). -void PrefixedOutStream::PrefixIfNeeded() -{ - // If we need to, output a prefix. - if (carriageReturned) - { - if (!ignoreInput) // But only if we are allowed to. - destination << prefix; - - carriageReturned = false; // Denote that the prefix has been displayed. - } -} - -} // namespace util -} // namespace mlpack - -#endif // MLPACK_CORE_UTIL_PREFIXEDOUTSTREAM_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/util/program_doc.hpp b/src/sdk/mlpack/include/mlpack/core/util/program_doc.hpp deleted file mode 100644 index f5de89fe5..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/program_doc.hpp +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @file program_doc.hpp - * @author Matthew Amidon - * - * The structure used to store a program's name and documentation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_PROGRAM_DOC_HPP -#define MLPACK_CORE_UTIL_PROGRAM_DOC_HPP - -namespace mlpack { -namespace util { - -/** - * A static object whose constructor registers program documentation with the - * CLI class. This should not be used outside of CLI itself, and you should use - * the PROGRAM_INFO() macro to declare these objects. Only one ProgramDoc - * object should ever exist. - * - * @see core/util/cli.hpp, mlpack::CLI - */ -class ProgramDoc -{ - public: - /** - * Construct a ProgramDoc object. When constructed, it will register itself - * with CLI, and when the user calls --help (or whatever the option is named - * for the given binding type), the given function that returns a std::string - * will be returned. - * - * @param programName Short string representing the name of the program. - * @param documentation Long string containing documentation on how to use the - * program and what it is. No newline characters are necessary; this is - * taken care of by CLI later. - */ - ProgramDoc(const std::string& programName, - const std::function& documentation); - - //! The name of the program. - std::string programName; - //! Documentation for what the program does. - std::function documentation; -}; - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/sfinae_utility.hpp b/src/sdk/mlpack/include/mlpack/core/util/sfinae_utility.hpp deleted file mode 100644 index c0d3f6724..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/sfinae_utility.hpp +++ /dev/null @@ -1,321 +0,0 @@ -/** - * @file sfinae_utility.hpp - * @author Trironk Kiatkungwanglai, Kirill Mishchenko - * - * This file contains macro utilities for the SFINAE Paradigm. These utilities - * determine if classes passed in as template parameters contain members at - * compile time, which is useful for changing functionality depending on what - * operations an object is capable of performing. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_SFINAE_UTILITY -#define MLPACK_CORE_SFINAE_UTILITY - -#include -#include - -namespace mlpack { -namespace sfinae { - -/* - * MethodFormDetector is a tool that helps to find out whether a given class has - * a method of the requested form. For that purpose MethodFormDetector defines - * an operator() that accepts a class member pointer for the given class. If the - * operator()(&Class::Method) call can be compiled, then the given class has a - * method of the requested form. For any provided AdditionalArgsCount, the check - * succeeds only if the given class has exactly one method of the requested form - * with AdditionalArgsCount additional arguments. - * - * The tool is dedicated to be used in type functions (structs) generated by the - * macro HAS_METHOD_FORM. - * - * @tparam MethodForm A template class member pointer type to a method of the - * form to look for. - * @tparam Class A class in which a method of the requested form should be - * looked for. - * @tparam AdditionalArgsCount A number of additional arguments. - */ -template class MethodForm, - size_t AdditionalArgsCount> -struct MethodFormDetector; - -template class MethodForm> -struct MethodFormDetector -{ - void operator()(MethodForm); -}; - -template class MethodForm> -struct MethodFormDetector -{ - template - void operator()(MethodForm); -}; - -template class MethodForm> -struct MethodFormDetector -{ - template - void operator()(MethodForm); -}; - -template class MethodForm> -struct MethodFormDetector -{ - template - void operator()(MethodForm); -}; - -template class MethodForm> -struct MethodFormDetector -{ - template - void operator()(MethodForm); -}; - -template class MethodForm> -struct MethodFormDetector -{ - template - void operator()(MethodForm); -}; - -template class MethodForm> -struct MethodFormDetector -{ - template - void operator()(MethodForm); -}; - -template class MethodForm> -struct MethodFormDetector -{ - template - void operator()(MethodForm); -}; - -} // namespace sfinae -} // namespace mlpack - -//! Utility struct for checking signatures. -template struct SigCheck : std::true_type {}; - -/* - * Constructs a template supporting the SFINAE pattern. - * - * This macro generates a template struct that is useful for enabling/disabling - * a method if the template class passed in contains a member function matching - * a given signature with a specified name. - * - * The generated struct should be used in conjunction with std::enable_if_t. - * - * For general references, see: - * http://stackoverflow.com/a/264088/391618 - * - * For an mlpack specific use case, see /mlpack/core/util/prefixedoutstream.hpp - * and /mlpack/core/util/prefixedoutstream_impl.hpp - * - * @param NAME the name of the struct to construct. For example: HasToString - * @param FUNC the name of the function to check for. For example: ToString - */ -#define HAS_MEM_FUNC(FUNC, NAME) \ -template \ -struct NAME : std::false_type {}; \ - \ -template \ -struct NAME \ -< \ - T, \ - sig, \ - std::integral_constant::value> \ -> : std::true_type {}; - -/** - * Base macro for HAS_METHOD_FORM() and HAS_EXACT_METHOD_FORM() macros. - */ -#define HAS_METHOD_FORM_BASE(METHOD, NAME, MAXN) \ -template class MF /* MethodForm */, \ - size_t MinN = 0 /* MinNumberOfAdditionalArgs */> \ -struct NAME \ -{ \ - /* Making a short alias for MethodFormDetector */ \ - template class MethodForm, int N> \ - using MFD = mlpack::sfinae::MethodFormDetector; \ - \ - template \ - struct WithNAdditionalArgs \ - { \ - using yes = char[1]; \ - using no = char[2]; \ - \ - template \ - using EnableIfVoid = \ - typename std::enable_if::value, ResultType>::type; \ - \ - template \ - static EnableIfVoid()(&C::METHOD)), yes&> chk(int); \ - template \ - static no& chk(...); \ - \ - static const bool value = sizeof(chk(0)) == sizeof(yes); \ - }; \ - \ - template \ - struct WithGreaterOrEqualNumberOfAdditionalArgs \ - { \ - using type = typename std::conditional< \ - WithNAdditionalArgs::value, \ - std::true_type, \ - typename std::conditional< \ - N < MAXN, \ - WithGreaterOrEqualNumberOfAdditionalArgs, \ - std::false_type>::type>::type; \ - static const bool value = type::value; \ - }; \ - \ - static const bool value = \ - WithGreaterOrEqualNumberOfAdditionalArgs::value; \ -}; - -/** - * Constructs a template structure, which will define a boolean static - * variable, to true, if the passed template parameter, has a member function - * with the specified name. The check does not care about the signature or the - * function parameters. - * - * @param FUNC the name of the function, whose existence is to be detected - * @param NAME the name of the structure that will be generated - * - * Use this like: NAME::value to check for the existence of the - * function in the given class name. - * This can also be used in conjunction with std::enable_if. - */ -#define HAS_ANY_METHOD_FORM(FUNC, NAME) \ -template \ -struct NAME \ -{ \ - template \ - static typename \ - std::enable_if::value, \ - int>::type \ - f(int) { return 1;} \ - \ - template \ - static char f(char) { return 0; } \ - \ - static const bool value = sizeof(f(0)) != sizeof(char); \ -}; -/* - * A macro that can be used for passing arguments containing commas to other - * macros. - */ -#define SINGLE_ARG(...) __VA_ARGS__ - -/** - * HAS_METHOD_FORM generates a template that allows to check at compile time - * whether a given class has a method of the requested form. For example, for - * the following class - * - * class A - * { - * public: - * ... - * Train(const arma::mat&, const arma::Row&, double); - * ... - * }; - * - * and the following form of Train methods - * - * template - * using TrainForm = - * void(Class::*)(const arma::mat&, const arma::Row&, Ts...); - * - * we can check whether the class A has a Train method of the specified form: - * - * HAS_METHOD_FORM(Train, HasTrain); - * static_assert(HasTrain::value, "value should be true"); - * - * The class generated by this will also return true values if the given class - * has a method that also has extra parameters. - * - * @param METHOD The name of the method to check for. - * @param NAME The name of the struct to construct. - * @param MAXN The maximum number of additional arguments. - */ -#define HAS_METHOD_FORM(METHOD, NAME) \ - HAS_METHOD_FORM_BASE(SINGLE_ARG(METHOD), SINGLE_ARG(NAME), 7) - -/** - * HAS_EXACT_METHOD_FORM generates a template that allows to check at compile - * time whether a given class has a method of the requested form. For example, - * for the following class - * - * class A - * { - * public: - * ... - * Train(const arma::mat&, const arma::Row&); - * ... - * }; - * - * and the following form of Train methods - * - * template - * using TrainForm = - * void(Class::*)(const arma::mat&, const arma::Row&); - * - * we can check whether the class A has a Train method of the specified form: - * - * HAS_METHOD_FORM(Train, HasTrain); - * static_assert(HasTrain::value, "value should be true"); - * - * The class generated by this will only return true values if the signature - * matches exactly. - * - * @param METHOD The name of the method to check for. - * @param NAME The name of the struct to construct. - * @param MAXN The maximum number of additional arguments. - */ -#define HAS_EXACT_METHOD_FORM(METHOD, NAME) \ - HAS_METHOD_FORM_BASE(SINGLE_ARG(METHOD), SINGLE_ARG(NAME), 0) - -/** - * A version of HAS_METHOD_FORM() where the maximum number of extra arguments is - * set to the default of 7. - * - * HAS_METHOD_FORM generates a template that allows to check at compile time - * whether a given class has a method of the requested form. For example, for - * the following class - * - * class A - * { - * public: - * ... - * Train(const arma::mat&, const arma::Row&, double); - * ... - * }; - * - * and the following form of Train methods - * - * template - * using TrainForm = - * void(Class::*)(const arma::mat&, const arma::Row&, Ts...); - * - * we can check whether the class A has a Train method of the specified form: - * - * HAS_METHOD_FORM(Train, HasTrain); - * static_assert(HasTrain::value, "value should be true"); - * - * The implementation is analogous to implementation of the macro HAS_MEM_FUNC. - * - * @param METHOD The name of the method to check for. - * @param NAME The name of the struct to construct. - */ - -#endif diff --git a/src/sdk/mlpack/include/mlpack/core/util/timers.hpp b/src/sdk/mlpack/include/mlpack/core/util/timers.hpp deleted file mode 100644 index a52e66bdb..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/timers.hpp +++ /dev/null @@ -1,185 +0,0 @@ -/** - * @file timers.hpp - * @author Matthew Amidon - * @author Marcus Edel - * @author Ryan Curtin - * - * Timers for mlpack. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTILITIES_TIMERS_HPP -#define MLPACK_CORE_UTILITIES_TIMERS_HPP - -#include -#include -#include // chrono library for cross platform timer calculation. -#include // std::thread is used for thread safety. -#include -#include -#include - -#if defined(_WIN32) - // uint64_t isn't defined on every windows. - #if !defined(HAVE_UINT64_T) - #if SIZEOF_UNSIGNED_LONG == 8 - typedef unsigned long uint64_t; - #else - typedef unsigned long long uint64_t; - #endif // SIZEOF_UNSIGNED_LONG - #endif // HAVE_UINT64_T -#endif - -namespace mlpack { - -/** - * The timer class provides a way for mlpack methods to be timed. The three - * methods contained in this class allow a named timer to be started and - * stopped, and its value to be obtained. A named timer is specific to the - * thread it is running on, so if you start a timer in one thread, it cannot be - * stopped from a different thread. - */ -class Timer -{ - public: - /** - * Start the given timer. If a timer is started, then stopped, then - * re-started, then re-stopped, the final value of the timer is the length of - * both runs -- that is, mlpack timers are additive for each time they are - * run, and do not reset. - * - * @note A std::runtime_error exception will be thrown if a timer is started - * twice. - * - * @param name Name of timer to be started. - */ - static void Start(const std::string& name); - - /** - * Stop the given timer. - * - * @note A std::runtime_error exception will be thrown if a timer is started - * twice. - * - * @param name Name of timer to be stopped. - */ - static void Stop(const std::string& name); - - /** - * Get the value of the given timer. - * - * @param name Name of timer to return value of. - */ - static std::chrono::microseconds Get(const std::string& name); - - /** - * Enable timing of mlpack programs. Do not run this while timers are - * running! - */ - static void EnableTiming(); - - /** - * Disable timing of mlpack programs. Do not run this while timers are - * running! - */ - static void DisableTiming(); - - /** - * Stop and reset all running timers. This removes all knowledge of any - * existing timers. - */ - static void ResetAll(); -}; - -class Timers -{ - public: - //! Default to disabled. - Timers() : enabled(false) { } - - /** - * Returns a copy of all the timers used via this interface. - */ - std::map GetAllTimers(); - - /** - * Reset the timers. This stops all running timers and removes them. Whether - * or not timing is enabled will not be changed. - */ - void Reset(); - - /** - * Returns a copy of the timer specified. This contains the sum of the timing - * results for timers that have been stopped with this name. - * - * @param timerName The name of the timer in question. - */ - std::chrono::microseconds GetTimer(const std::string& timerName); - - /** - * Prints the specified timer. If it took longer than a minute to complete - * the timer will be displayed in days, hours, and minutes as well. - * - * @param timerName The name of the timer in question. - */ - void PrintTimer(const std::string& timerName); - - /** -  * Initializes a timer, available like a normal value specified on -  * the command line.  Timers are of type timeval. If a timer is started, then - * stopped, then re-started, then stopped, the final timer value will be the - * length of both runs of the timer. -  * -  * @param timerName The name of the timer in question. - * @param threadId Id of the thread accessing the timer. -  */ - void StartTimer(const std::string& timerName, - const std::thread::id& threadId = std::thread::id()); - - /** -  * Halts the timer, and replaces its value with the delta time from its start. -  * -  * @param timerName The name of the timer in question. - * @param threadId Id of the thread accessing the timer. -  */ - void StopTimer(const std::string& timerName, - const std::thread::id& threadId = std::thread::id()); - - /** - * Returns state of the given timer. - * - * @param timerName The name of the timer in question. - * @param threadId Id of the thread accessing the timer. - */ - bool GetState(const std::string& timerName, - const std::thread::id& threadId = std::thread::id()); - - /** - * Stop all timers. - */ - void StopAllTimers(); - - //! Modify whether or not timing is enabled. - std::atomic& Enabled() { return enabled; } - //! Get whether or not timing is enabled. - bool Enabled() const { return enabled; } - - private: - //! A map of all the timers that are being tracked. - std::map timers; - //! A mutex for modifying the timers. - std::mutex timersMutex; - //! A map for the starting values of the timers. - std::map> timerStartTime; - - //! Whether or not timing is enabled. - std::atomic enabled; -}; - -} // namespace mlpack - -#endif // MLPACK_CORE_UTILITIES_TIMERS_HPP diff --git a/src/sdk/mlpack/include/mlpack/core/util/version.hpp b/src/sdk/mlpack/include/mlpack/core/util/version.hpp deleted file mode 100644 index fcf5b6e02..000000000 --- a/src/sdk/mlpack/include/mlpack/core/util/version.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @file version.hpp - * @author Ryan Curtin - * - * The current version of mlpack, available as macros and as a string. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_CORE_UTIL_VERSION_HPP -#define MLPACK_CORE_UTIL_VERSION_HPP - -#include - -// The version of mlpack. If this is a git repository, this will be a version -// with higher number than the most recent release. -#define MLPACK_VERSION_MAJOR 3 -#define MLPACK_VERSION_MINOR 0 -#define MLPACK_VERSION_PATCH 4 - -// The name of the version (for use by --version). -namespace mlpack { -namespace util { - -/** - * This will return either "mlpack x.y.z" or "mlpack master-XXXXXXX" depending on - * whether or not this is a stable version of mlpack or a git repository. - */ -std::string GetVersion(); - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost.hpp b/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost.hpp deleted file mode 100644 index 094fa0386..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost.hpp +++ /dev/null @@ -1,186 +0,0 @@ -/** - * @file adaboost.hpp - * @author Udit Saxena - * - * The AdaBoost class. AdaBoost is a boosting algorithm, meaning that it - * combines an ensemble of weak learners to produce a strong learner. For more - * information on AdaBoost, see the following paper: - * - * @code - * @article{schapire1999improved, - * author = {Schapire, Robert E. and Singer, Yoram}, - * title = {Improved Boosting Algorithms Using Confidence-rated Predictions}, - * journal = {Machine Learning}, - * volume = {37}, - * number = {3}, - * month = dec, - * year = {1999}, - * issn = {0885-6125}, - * pages = {297--336}, - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ADABOOST_ADABOOST_HPP -#define MLPACK_METHODS_ADABOOST_ADABOOST_HPP - -#include -#include -#include - -namespace mlpack { -namespace adaboost { - -/** - * The AdaBoost class. AdaBoost is a boosting algorithm, meaning that it - * combines an ensemble of weak learners to produce a strong learner. For more - * information on AdaBoost, see the following paper: - * - * @code - * @article{schapire1999improved, - * author = {Schapire, Robert E. and Singer, Yoram}, - * title = {Improved Boosting Algorithms Using Confidence-rated Predictions}, - * journal = {Machine Learning}, - * volume = {37}, - * number = {3}, - * month = dec, - * year = {1999}, - * issn = {0885-6125}, - * pages = {297--336}, - * } - * @endcode - * - * This class is general, and can be used with any type of weak learner, so long - * as the learner implements the following functions: - * - * @code - * // A boosting constructor, which learns using the training parameters of the - * // given other WeakLearner, but uses the given instance weights for training. - * WeakLearner(WeakLearner& other, - * const MatType& data, - * const arma::Row& labels, - * const arma::rowvec& weights); - * - * // Given the test points, classify them and output predictions into - * // predictedLabels. - * void Classify(const MatType& data, arma::Row& predictedLabels); - * @endcode - * - * For more information on and examples of weak learners, see - * perceptron::Perceptron<> and decision_stump::DecisionStump<>. - * - * @tparam MatType Data matrix type (i.e. arma::mat or arma::sp_mat). - * @tparam WeakLearnerType Type of weak learner to use. - */ -template, - typename MatType = arma::mat> -class AdaBoost -{ - public: - /** - * Constructor. This runs the AdaBoost.MH algorithm to provide a trained - * boosting model. This constructor takes an already-initialized weak - * learner; all other weak learners will learn with the same parameters as the - * given weak learner. - * - * @param data Input data. - * @param labels Corresponding labels. - * @param iterations Number of boosting rounds. - * @param tol The tolerance for change in values of rt. - * @param other Weak learner that has already been initialized. - */ - AdaBoost(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const WeakLearnerType& other, - const size_t iterations = 100, - const double tolerance = 1e-6); - - /** - * Create the AdaBoost object without training. Be sure to call Train() - * before calling Classify()! - */ - AdaBoost(const double tolerance = 1e-6); - - // Return the value of ztProduct. - double ZtProduct() { return ztProduct; } - - //! Get the tolerance for stopping the optimization during training. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for stopping the optimization during training. - double& Tolerance() { return tolerance; } - - //! Get the number of classes this model is trained on. - size_t NumClasses() const { return numClasses; } - - //! Get the number of weak learners in the model. - size_t WeakLearners() const { return alpha.size(); } - - //! Get the weights for the given weak learner. - double Alpha(const size_t i) const { return alpha[i]; } - //! Modify the weight for the given weak learner (be careful!). - double& Alpha(const size_t i) { return alpha[i]; } - - //! Get the given weak learner. - const WeakLearnerType& WeakLearner(const size_t i) const { return wl[i]; } - //! Modify the given weak learner (be careful!). - WeakLearnerType& WeakLearner(const size_t i) { return wl[i]; } - - /** - * Train AdaBoost on the given dataset. This method takes an initialized - * WeakLearnerType; the parameters for this weak learner will be used to train - * each of the weak learners during AdaBoost training. Note that this will - * completely overwrite any model that has already been trained with this - * object. - * - * @param data Dataset to train on. - * @param labels Labels for each point in the dataset. - * @param learner Learner to use for training. - */ - void Train(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const WeakLearnerType& learner, - const size_t iterations = 100, - const double tolerance = 1e-6); - - /** - * Classify the given test points. - * - * @param test Testing data. - * @param predictedLabels Vector in which to the predicted labels of the test - * set will be stored. - */ - void Classify(const MatType& test, arma::Row& predictedLabels); - - /** - * Serialize the AdaBoost model. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! The number of classes in the model. - size_t numClasses; - // The tolerance for change in rt and when to stop. - double tolerance; - - //! The vector of weak learners. - std::vector wl; - //! The weights corresponding to each weak learner. - std::vector alpha; - - //! To check for the bound for the Hamming loss. - double ztProduct; -}; // class AdaBoost - -} // namespace adaboost -} // namespace mlpack - -#include "adaboost_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost_impl.hpp deleted file mode 100644 index 7348b6651..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost_impl.hpp +++ /dev/null @@ -1,261 +0,0 @@ -/* - * @file adaboost_impl.hpp - * @author Udit Saxena - * - * Implementation of the AdaBoost class. - * - * @code - * @article{schapire1999improved, - * author = {Schapire, Robert E. and Singer, Yoram}, - * title = {Improved Boosting Algorithms Using Confidence-rated Predictions}, - * journal = {Machine Learning}, - * volume = {37}, - * number = {3}, - * month = dec, - * year = {1999}, - * issn = {0885-6125}, - * pages = {297--336}, - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ADABOOST_ADABOOST_IMPL_HPP -#define MLPACK_METHODS_ADABOOST_ADABOOST_IMPL_HPP - -#include "adaboost.hpp" - -namespace mlpack { -namespace adaboost { - -/** - * Constructor. Currently runs the AdaBoost.MH algorithm. - * - * @param data Input data - * @param labels Corresponding labels - * @param iterations Number of boosting rounds - * @param tol Tolerance for termination of Adaboost.MH. - * @param other Weak Learner, which has been initialized already. - */ -template -AdaBoost::AdaBoost( - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const WeakLearnerType& other, - const size_t iterations, - const double tol) -{ - Train(data, labels, numClasses, other, iterations, tol); -} - -// Empty constructor. -template -AdaBoost::AdaBoost(const double tolerance) : - tolerance(tolerance) -{ - // Nothing to do. -} - -// Train AdaBoost. -template -void AdaBoost::Train( - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const WeakLearnerType& other, - const size_t iterations, - const double tolerance) -{ - // Clear information from previous runs. - wl.clear(); - alpha.clear(); - - this->tolerance = tolerance; - this->numClasses = numClasses; - - // crt is the cumulative rt value for terminating the optimization when rt is - // changing by less than the tolerance. - double rt, crt = 0.0, alphat = 0.0, zt; - - ztProduct = 1.0; - - // To be used for prediction by the weak learner. - arma::Row predictedLabels(labels.n_cols); - - // Use tempData to modify input data for incorporating weights. - MatType tempData(data); - - // This matrix is a helper matrix used to calculate the final hypothesis. - arma::mat sumFinalH = arma::zeros(numClasses, - predictedLabels.n_cols); - - // Load the initial weights into a 2-D matrix. - const double initWeight = 1.0 / double(data.n_cols * numClasses); - arma::mat D(numClasses, data.n_cols); - D.fill(initWeight); - - // Weights are stored in this row vector. - arma::rowvec weights(predictedLabels.n_cols); - - // This is the final hypothesis. - arma::Row finalH(predictedLabels.n_cols); - - // Now, start the boosting rounds. - for (size_t i = 0; i < iterations; i++) - { - // Initialized to zero in every round. rt is used for calculation of - // alphat; it is the weighted error. - // rt = (sum) D(i) y(i) ht(xi) - rt = 0.0; - - // zt is used for weight normalization. - zt = 0.0; - - // Build the weight vectors. - weights = arma::sum(D); - - // Use the existing weak learner to train a new one with new weights. - WeakLearnerType w(other, tempData, labels, numClasses, weights); - w.Classify(tempData, predictedLabels); - - // Now from predictedLabels, build ht, the weak hypothesis - // buildClassificationMatrix(ht, predictedLabels); - - // Now, calculate alpha(t) using ht. - for (size_t j = 0; j < D.n_cols; j++) // instead of D, ht - { - if (predictedLabels(j) == labels(j)) - rt += arma::accu(D.col(j)); - else - rt -= arma::accu(D.col(j)); - } - - if ((i > 0) && (std::abs(rt - crt) < tolerance)) - break; - - // Check if model has converged. - if (rt >= 1.0) - { - // Save the weak learner and terminate. - alpha.push_back(1.0); - wl.push_back(w); - break; - } - - crt = rt; - - // Our goal is to find alphat which mizimizes or approximately minimizes the - // value of Z as a function of alpha. - alphat = 0.5 * log((1 + rt) / (1 - rt)); - - alpha.push_back(alphat); - wl.push_back(w); - - // Now start modifying the weights. - for (size_t j = 0; j < D.n_cols; j++) - { - const double expo = exp(alphat); - if (predictedLabels(j) == labels(j)) - { - for (size_t k = 0; k < D.n_rows; k++) - { - // We calculate zt, the normalization constant. - D(k, j) /= expo; - zt += D(k, j); // * exp(-1 * alphat * yt(j,k) * ht(j,k)); - - // Add to the final hypothesis matrix. - // sumFinalH(k, j) += (alphat * ht(k, j)); - if (k == labels(j)) - sumFinalH(k, j) += (alphat); // * ht(k, j)); - else - sumFinalH(k, j) -= (alphat); - } - } - else - { - for (size_t k = 0; k < D.n_rows; k++) - { - // We calculate zt, the normalization constant. - D(k, j) *= expo; - zt += D(k, j); - - // Add to the final hypothesis matrix. - if (k == labels(j)) - sumFinalH(k, j) += alphat; // * ht(k, j)); - else - sumFinalH(k, j) -= alphat; - } - } - } - - // Normalize D. - D /= zt; - - // Accumulate the value of zt for the Hamming loss bound. - ztProduct *= zt; - } -} - -/** - * Classify the given test points. - */ -template -void AdaBoost::Classify( - const MatType& test, - arma::Row& predictedLabels) -{ - arma::Row tempPredictedLabels(test.n_cols); - arma::mat cMatrix(numClasses, test.n_cols); - - cMatrix.zeros(); - predictedLabels.set_size(test.n_cols); - - for (size_t i = 0; i < wl.size(); i++) - { - wl[i].Classify(test, tempPredictedLabels); - - for (size_t j = 0; j < tempPredictedLabels.n_cols; j++) - cMatrix(tempPredictedLabels(j), j) += alpha[i]; - } - - arma::colvec cMRow; - arma::uword maxIndex = 0; - - for (size_t i = 0; i < predictedLabels.n_cols; i++) - { - cMRow = cMatrix.unsafe_col(i); - cMRow.max(maxIndex); - predictedLabels(i) = maxIndex; - } -} - -/** - * Serialize the AdaBoost model. - */ -template -template -void AdaBoost::serialize(Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(numClasses); - ar & BOOST_SERIALIZATION_NVP(tolerance); - ar & BOOST_SERIALIZATION_NVP(ztProduct); - ar & BOOST_SERIALIZATION_NVP(alpha); - - // Now serialize each weak learner. - if (Archive::is_loading::value) - { - wl.clear(); - wl.resize(alpha.size()); - } - ar & BOOST_SERIALIZATION_NVP(wl); -} - -} // namespace adaboost -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost_model.hpp b/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost_model.hpp deleted file mode 100644 index 95ac52b19..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/adaboost/adaboost_model.hpp +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @file adaboost_model.hpp - * @author Ryan Curtin - * - * A serializable AdaBoost model, used by the main program. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ADABOOST_ADABOOST_MODEL_HPP -#define MLPACK_METHODS_ADABOOST_ADABOOST_MODEL_HPP - -#include - -// Use forward declaration instead of include to accelerate compilation. -class AdaBoost; - -namespace mlpack { -namespace adaboost { - -/** - * The model to save to disk. - */ -class AdaBoostModel -{ - public: - enum WeakLearnerTypes - { - DECISION_STUMP, - PERCEPTRON - }; - - private: - //! The mappings for the labels. - arma::Col mappings; - //! The type of weak learner. - size_t weakLearnerType; - //! Non-NULL if using decision stumps. - AdaBoost>* dsBoost; - //! Non-NULL if using perceptrons. - AdaBoost>* pBoost; - //! Number of dimensions in training data. - size_t dimensionality; - - public: - //! Create an empty AdaBoost model. - AdaBoostModel(); - - //! Create the AdaBoost model with the given mappings and type. - AdaBoostModel(const arma::Col& mappings, - const size_t weakLearnerType); - - //! Copy constructor. - AdaBoostModel(const AdaBoostModel& other); - - //! Move constructor. - AdaBoostModel(AdaBoostModel&& other); - - //! Copy assignment operator. - AdaBoostModel& operator=(const AdaBoostModel& other); - - //! Clean up memory. - ~AdaBoostModel(); - - //! Get the mappings. - const arma::Col& Mappings() const { return mappings; } - //! Modify the mappings. - arma::Col& Mappings() { return mappings; } - - //! Get the weak learner type. - size_t WeakLearnerType() const { return weakLearnerType; } - //! Modify the weak learner type. - size_t& WeakLearnerType() { return weakLearnerType; } - - //! Get the dimensionality of the model. - size_t Dimensionality() const { return dimensionality; } - //! Modify the dimensionality of the model. - size_t& Dimensionality() { return dimensionality; } - - //! Train the model. - void Train(const arma::mat& data, - const arma::Row& labels, - const size_t numClasses, - const size_t iterations, - const double tolerance); - - //! Classify test points. - void Classify(const arma::mat& testData, arma::Row& predictions); - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - if (Archive::is_loading::value) - { - if (dsBoost) - delete dsBoost; - if (pBoost) - delete pBoost; - - dsBoost = NULL; - pBoost = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(mappings); - ar & BOOST_SERIALIZATION_NVP(weakLearnerType); - if (weakLearnerType == WeakLearnerTypes::DECISION_STUMP) - ar & BOOST_SERIALIZATION_NVP(dsBoost); - else if (weakLearnerType == WeakLearnerTypes::PERCEPTRON) - ar & BOOST_SERIALIZATION_NVP(pBoost); - ar & BOOST_SERIALIZATION_NVP(dimensionality); - } -}; - -} // namespace adaboost -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/amf.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/amf.hpp deleted file mode 100644 index e88b69afb..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/amf.hpp +++ /dev/null @@ -1,193 +0,0 @@ -/** - * @file amf.hpp - * @author Sumedh Ghaisas - * @author Mohan Rajendran - * @author Ryan Curtin - * - * Alternating Matrix Factorization - * - * The AMF (alternating matrix factorization) class, from which more commonly - * known techniques such as incremental SVD, NMF, and batch-learning SVD can be - * derived. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AMF_AMF_HPP -#define MLPACK_METHODS_AMF_AMF_HPP - -#include - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -namespace mlpack { -namespace amf /** Alternating Matrix Factorization **/ { - -/** - * This class implements AMF (alternating matrix factorization) on the given - * matrix V. Alternating matrix factorization decomposes V in the form - * \f$ V \approx WH \f$ where W is called the basis matrix and H is called the - * encoding matrix. V is taken to be of size n x m and the obtained W is n x r - * and H is r x m. The size r is called the rank of the factorization. - * - * The implementation requires three template types; the first contains the - * policy used to determine when the algorithm has converged; the second - * contains the initialization rule for the W and H matrix; the last contains - * the update rule to be used during each iteration. This templatization allows - * the user to try various update rules, initialization rules, and termination - * policies (including ones not supplied with mlpack) for factorization. By - * default, the template parameters to AMF implement non-negative matrix - * factorization with the multiplicative distance update. - * - * A simple example of how to run AMF (or NMF) is shown below. - * - * @code - * extern arma::mat V; // Matrix that we want to perform LMF on. - * size_t r = 10; // Rank of decomposition - * arma::mat W; // Basis matrix - * arma::mat H; // Encoding matrix - * - * AMF<> amf; // Default options: NMF with multiplicative distance update rules. - * amf.Apply(V, r, W, H); - * @endcode - * - * @tparam TerminationPolicy The policy to use for determining when the - * factorization has converged. - * @tparam InitializationRule The initialization rule for initializing W and H - * matrix. - * @tparam UpdateRule The update rule for calculating W and H matrix at each - * iteration. - * - * @see NMFMultiplicativeDistanceUpdate, SimpleResidueTermination - */ -template, - typename UpdateRuleType = NMFMultiplicativeDistanceUpdate> -class AMF -{ - public: - /** - * Create the AMF object and (optionally) set the parameters which AMF will - * run with. The minimum residue refers to the root mean square of the - * difference between two subsequent iterations of the product W * H. A low - * residue indicates that subsequent iterations are not producing much change - * in W and H. Once the residue goes below the specified minimum residue, the - * algorithm terminates. - * - * @param initializationRule Optional instantiated InitializationRule object - * for initializing the W and H matrices. - * @param updateRule Optional instantiated UpdateRule object; this parameter - * is useful when the update rule for the W and H vector has state that - * it needs to store (i.e. HUpdate() and WUpdate() are not static - * functions). - * @param terminationPolicy Optional instantiated TerminationPolicy object. - */ - AMF(const TerminationPolicyType& terminationPolicy = TerminationPolicyType(), - const InitializationRuleType& initializeRule = InitializationRuleType(), - const UpdateRuleType& update = UpdateRuleType()); - - /** - * Apply Alternating Matrix Factorization to the provided matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix to be output. - * @param H Encoding matrix to output. - * @param r Rank r of the factorization. - */ - template - double Apply(const MatType& V, - const size_t r, - arma::mat& W, - arma::mat& H); - - //! Access the termination policy. - const TerminationPolicyType& TerminationPolicy() const - { return terminationPolicy; } - //! Modify the termination policy. - TerminationPolicyType& TerminationPolicy() { return terminationPolicy; } - - //! Access the initialization rule. - const InitializationRuleType& InitializeRule() const - { return initializationRule; } - //! Modify the initialization rule. - InitializationRuleType& InitializeRule() { return initializationRule; } - - //! Access the update rule. - const UpdateRuleType& Update() const { return update; } - //! Modify the update rule. - UpdateRuleType& Update() { return update; } - - private: - //! Termination policy. - TerminationPolicyType terminationPolicy; - //! Instantiated initialization Rule. - InitializationRuleType initializationRule; - //! Instantiated update rule. - UpdateRuleType update; -}; // class AMF - -typedef amf::AMF, - amf::NMFALSUpdate> NMFALSFactorizer; - -//! Convenience typedefs. - -/** - * SVDBatchFactorizer factorizes given matrix V into two matrices W and H by - * gradient descent. SVD batch learning is described in paper 'A Guide to - * singular Value Decomposition' by Chih-Chao Ma. - * - * @see SVDBatchLearning - */ -template -using SVDBatchFactorizer = amf::AMF< - amf::SimpleResidueTermination, - amf::RandomAcolInitialization<>, - amf::SVDBatchLearning>; - -/** - * SVDIncompleteIncrementalFactorizer factorizes given matrix V into two - * matrices W and H by incomplete incremental gradient descent. SVD incomplete - * incremental learning is described in paper 'A Guide to singular Value - * Decomposition' by Chih-Chao Ma. - * - * @see SVDIncompleteIncrementalLearning - */ -template -using SVDIncompleteIncrementalFactorizer = amf::AMF< - amf::SimpleResidueTermination, - amf::RandomAcolInitialization<>, - amf::SVDIncompleteIncrementalLearning>; -/** - * SVDCompleteIncrementalFactorizer factorizes given matrix V into two matrices - * W and H by complete incremental gradient descent. SVD complete incremental - * learning is described in paper 'A Guide to singular Value Decomposition' - * by Chih-Chao Ma. - * - * @see SVDCompleteIncrementalLearning - */ -template -using SVDCompleteIncrementalFactorizer = amf::AMF< - amf::SimpleResidueTermination, - amf::RandomAcolInitialization<>, - amf::SVDCompleteIncrementalLearning>; -} // namespace amf -} // namespace mlpack - -// Include implementation. -#include "amf_impl.hpp" - -#endif // MLPACK_METHODS_AMF_AMF_HPP - diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/amf_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/amf_impl.hpp deleted file mode 100644 index 8a346b928..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/amf_impl.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file amf_impl.hpp - * @author Sumedh Ghaisas - * @author Mohan Rajendran - * @author Ryan Curtin - * - * Implementation of AMF class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -namespace mlpack { -namespace amf { - -/** - * Construct the AMF object. - */ -template -AMF::AMF( - const TerminationPolicyType& terminationPolicy, - const InitializationRuleType& initializationRule, - const UpdateRuleType& update) : - terminationPolicy(terminationPolicy), - initializationRule(initializationRule), - update(update) -{ } - -/** - * Apply Alternating Matrix Factorization to the provided matrix. - * - * @param V Input matrix to be factorized - * @param W Basis matrix to be output - * @param H Encoding matrix to output - * @param r Rank r of the factorization - */ -template -template -double AMF:: -Apply(const MatType& V, - const size_t r, - arma::mat& W, - arma::mat& H) -{ - // Initialize W and H. - initializationRule.Initialize(V, r, W, H); - - Log::Info << "Initialized W and H." << std::endl; - - // initialize the update rule - update.Initialize(V, r); - // initialize the termination policy - terminationPolicy.Initialize(V); - - // check if termination conditions are met - while (!terminationPolicy.IsConverged(W, H)) - { - // Update the values of W and H based on the update rules provided. - update.WUpdate(V, W, H); - update.HUpdate(V, W, H); - } - - // get final residue and iteration count from termination policy - const double residue = terminationPolicy.Index(); - const size_t iteration = terminationPolicy.Iteration(); - - Log::Info << "AMF converged to residue of " << residue << " in " - << iteration << " iterations." << std::endl; - - return residue; -} - -} // namespace amf -} // namespace mlpack diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/average_init.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/average_init.hpp deleted file mode 100644 index 89ca5abf7..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/average_init.hpp +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @file averge_init.hpp - * @author Sumedh Ghaisas - * - * Initialization rule for Alternating Matrix Factorization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AMF_AVERAGE_INIT_HPP -#define MLPACK_METHODS_AMF_AVERAGE_INIT_HPP - -#include - -namespace mlpack { -namespace amf { - -/** - * This initialization rule initializes matrix W and H to root of the average of - * V, perturbed with uniform noise. Uniform noise is generated by Armadillo's - * 'randu' function. For better performance, the lowest element of the matrix - * is subtracted from the average before dividing it by the factorization rank. - * This computed value is added with the random noise. - */ -class AverageInitialization -{ - public: - // Empty constructor required for the InitializeRule template - AverageInitialization() { } - - /** - * Initialize the matrices W and H to the average value of V with uniform - * random noise added. - * - * @param V Input matrix. - * @param r Rank of matrix. - * @param W W matrix, to be initialized. - * @param H H matrix, to be initialized. - */ - template - inline static void Initialize(const MatType& V, - const size_t r, - arma::mat& W, - arma::mat& H) - { - const size_t n = V.n_rows; - const size_t m = V.n_cols; - - double avgV = 0; - size_t count = 0; - double min = DBL_MAX; - - // Iterate over all elements in the matrix (for sparse matrices, this only - // iterates over nonzeros). - for (typename MatType::const_row_col_iterator it = V.begin(); - it != V.end(); ++it) - { - ++count; - avgV += *it; - // Track the minimum value. - if (*it < min) - min = *it; - } - - avgV = sqrt(((avgV / (n * m)) - min) / r); - - // Initialize to random values. - W.randu(n, r); - H.randu(r, m); - - W = W + avgV; - H = H + avgV; - } - - //! Serialize the object (in this case, there is nothing to do). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/given_init.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/given_init.hpp deleted file mode 100644 index 8da473678..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/given_init.hpp +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @file given_initialization.hpp - * @author Ryan Curtin - * - * Initialization rule for alternating matrix factorization (AMF). This simple - * initialization is performed by assigning a given matrix to W and H. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AMF_INIT_RULES_GIVEN_INIT_HPP -#define MLPACK_METHODS_AMF_INIT_RULES_GIVEN_INIT_HPP - -#include - -namespace mlpack { -namespace amf { - -/** - * This initialization rule for AMF simply fills the W and H matrices with the - * matrices given to the constructor of this object. Note that this object does - * not use std::move() during the Initialize() method, so it can be reused for - * multiple AMF objects, but will incur copies of the W and H matrices. - */ -class GivenInitialization -{ - public: - // Empty constructor required for the InitializeRule template. - GivenInitialization() { } - - // Initialize the GivenInitialization object with the given matrices. - GivenInitialization(const arma::mat& w, const arma::mat& h) : w(w), h(h) { } - - // Initialize the GivenInitialization object, taking control of the given - // matrices. - GivenInitialization(const arma::mat&& w, const arma::mat&& h) : - w(std::move(w)), - h(std::move(h)) - { } - - /** - * Fill W and H with random uniform noise. - * - * @param V Input matrix. - * @param r Rank of decomposition. - * @param W W matrix, to be filled with random noise. - * @param H H matrix, to be filled with random noise. - */ - template - inline void Initialize(const MatType& V, - const size_t r, - arma::mat& W, - arma::mat& H) - { - // Make sure the initial W, H matrices have correct size. - if (w.n_rows != V.n_rows) - { - Log::Fatal << "The number of rows in given W (" << w.n_rows - << ") doesn't equal the number of rows in V (" << V.n_rows - << ") !" << std::endl; - } - if (w.n_cols != r) - { - Log::Fatal << "The number of columns in given W (" << w.n_cols - << ") doesn't equal the rank of factorization (" << r - << ") !" << std::endl; - } - if (h.n_cols != V.n_cols) - { - Log::Fatal << "The number of columns in given H (" << h.n_cols - << ") doesn't equal the number of columns in V (" << V.n_cols - << ") !" << std::endl; - } - if (h.n_rows != r) - { - Log::Fatal << "The number of rows in given H (" << h.n_rows - << ") doesn't equal the rank of factorization (" << r - << ") !"<< std::endl; - } - - // Initialize to the given matrices. - W = w; - H = h; - } - - //! Serialize the object (in this case, there is nothing to serialize). - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(w); - ar & BOOST_SERIALIZATION_NVP(h); - } - - private: - //! The W matrix for initialization. - arma::mat w; - //! The H matrix for initialization. - arma::mat h; -}; - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/random_acol_init.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/random_acol_init.hpp deleted file mode 100644 index 796de7faf..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/random_acol_init.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file random_acol_init.hpp - * @author Mohan Rajendran - * - * Initialization rule for Alternating Matrix Factorization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LMF_RANDOM_ACOL_INIT_HPP -#define MLPACK_METHODS_LMF_RANDOM_ACOL_INIT_HPP - -#include -#include - -namespace mlpack { -namespace amf { - -/** - * This class initializes the W matrix of the AMF algorithm by averaging p - * randomly chosen columns of V. In this case, p is a template parameter. H is - * then filled using a uniform distribution in the range [0, 1]. - * - * This simple initialization is the "random Acol initialization" found in the - * following paper: - * - * @code - * @techreport{langville2014algorithms, - * title = {Algorithms, Initializations, and Convergence for the Nonnegative - * Matrix Factorization}, - * author = {Langville, A.N. and Meyer, C.D. and Albright, R. and Cox, J. and - * Duling, D.}, - * year = {2014}, - * institution = {NCSU Technical Report Math 81706} - * } - * @endcode - * - * @tparam columnsToAverage The number of random columns to average for each - * column of W. - */ -template -class RandomAcolInitialization -{ - public: - // Empty constructor required for the InitializeRule template - RandomAcolInitialization() - { } - - template - inline static void Initialize(const MatType& V, - const size_t r, - arma::mat& W, - arma::mat& H) - { - const size_t n = V.n_rows; - const size_t m = V.n_cols; - - if (columnsToAverage > m) - { - Log::Warn << "Number of random columns (columnsToAverage) is more than " - << "the number of columns available in the V matrix; weird results " - << "may ensue!" << std::endl; - } - - W.zeros(n, r); - - // Initialize W matrix with random columns. - for (size_t col = 0; col < r; col++) - { - for (size_t randCol = 0; randCol < columnsToAverage; randCol++) - { - // .col() does not work in this case, as of Armadillo 3.920. - W.unsafe_col(col) += V.col(math::RandInt(0, m)); - } - } - - // Now divide by p. - W /= columnsToAverage; - - // Initialize H to random values. - H.randu(r, m); - } - - //! Serialize the object (in this case, there is nothing to serialize). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/random_init.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/random_init.hpp deleted file mode 100644 index 1f775a12c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/init_rules/random_init.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file random_init.hpp - * @author Mohan Rajendran - * - * Initialization rule for alternating matrix factorization (AMF). This simple - * initialization is performed by assigning a random matrix to W and H. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LMF_RANDOM_INIT_HPP -#define MLPACK_METHODS_LMF_RANDOM_INIT_HPP - -#include - -namespace mlpack { -namespace amf { - -/** - * This initialization rule for AMF simply fills the W and H matrices with - * uniform random noise in [0, 1]. - */ -class RandomInitialization -{ - public: - // Empty constructor required for the InitializeRule template - RandomInitialization() { } - - /** - * Fill W and H with random uniform noise. - * - * @param V Input matrix. - * @param r Rank of decomposition. - * @param W W matrix, to be filled with random noise. - * @param H H matrix, to be filled with random noise. - */ - template - inline static void Initialize(const MatType& V, - const size_t r, - arma::mat& W, - arma::mat& H) - { - // Simple implementation (left in the header file due to its simplicity). - const size_t n = V.n_rows; - const size_t m = V.n_cols; - - // Initialize to random values. - W.randu(n, r); - H.randu(r, m); - } - - //! Serialize the object (in this case, there is nothing to serialize). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/complete_incremental_termination.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/complete_incremental_termination.hpp deleted file mode 100644 index 479acbef4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/complete_incremental_termination.hpp +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @file complete_incremental_termination.hpp - * @author Sumedh Ghaisas - * - * Termination policy used in AMF (Alternating Matrix Factorization). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AMF_COMPLETE_INCREMENTAL_TERMINATION_HPP -#define MLPACK_METHODS_AMF_COMPLETE_INCREMENTAL_TERMINATION_HPP - -namespace mlpack { -namespace amf { - -/** - * This class acts as a wrapper for basic termination policies to be used by - * SVDCompleteIncrementalLearning. This class calls the wrapped class functions - * after every n calls to main class functions where n is the number of non-zero - * entries in the matrix being factorized. This is necessary for - * SVDCompleteIncrementalLearning, because otherwise IsConverged() is called - * after every point, which is very slow. - * - * @see AMF, SVDCompleteIncrementalLearning - */ -template -class CompleteIncrementalTermination -{ - public: - /** - * Empty constructor. - * - * @param tPolicy object of wrapped class. - */ - CompleteIncrementalTermination( - TerminationPolicy tPolicy = TerminationPolicy()) : - tPolicy(tPolicy) { } - - /** - * Initializes the termination policy before stating the factorization. - * - * @param V Input matrix to be factorized. - */ - template - void Initialize(const MatType& V) - { - tPolicy.Initialize(V); - - // Get the number of non-zero entries. - incrementalIndex = arma::accu(V != 0); - iteration = 0; - } - - /** - * Initializes the termination policy before stating the factorization. This - * is a specialization for sparse matrices. - * - * @param V Input matrix to be factorized. - */ - void Initialize(const arma::sp_mat& V) - { - tPolicy.Initialize(V); - - // Get number of non-zero entries - incrementalIndex = V.n_nonzero; - iteration = 0; - } - - /** - * Check if termination criterion is met, if the current iteration means that - * each point has been visited. - * - * @param W Basis matrix of output. - * @param H Encoding matrix of output. - */ - bool IsConverged(arma::mat& W, arma::mat& H) - { - // Increment iteration count. - iteration++; - - // If iteration count is multiple of incremental index, return wrapped class - // function. - if (iteration % incrementalIndex == 0) - return tPolicy.IsConverged(W, H); - else - return false; - } - - //! Get current value of residue - const double& Index() const { return tPolicy.Index(); } - - //! Get current iteration count - const size_t& Iteration() const { return iteration; } - - //! Access upper limit of iteration count. - const size_t& MaxIterations() const { return tPolicy.MaxIterations(); } - //! Modify maximum number of iterations. - size_t& MaxIterations() { return tPolicy.MaxIterations(); } - - //! Access the wrapped termination policy. - const TerminationPolicy& TPolicy() const { return tPolicy; } - //! Modify the wrapped termination policy. - TerminationPolicy& TPolicy() { return tPolicy; } - - private: - //! Wrapped termination policy. - TerminationPolicy tPolicy; - - //! Number of iterations after which wrapped termination policy will be - //! called. - size_t incrementalIndex; - //! Current iteration number. - size_t iteration; -}; // class CompleteIncrementalTermination - -} // namespace amf -} // namespace mlpack - -#endif // MLPACK_METHODS_AMF_COMPLETE_INCREMENTAL_TERMINATION_HPP - diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/incomplete_incremental_termination.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/incomplete_incremental_termination.hpp deleted file mode 100644 index 35045c4b8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/incomplete_incremental_termination.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @file incomplete_incremental_termination.hpp - * @author Sumedh Ghaisas - * - * Termination policy used in AMF (Alternating Matrix Factorization). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef _MLPACK_METHODS_AMF_INCOMPLETE_INCREMENTAL_TERMINATION_HPP -#define _MLPACK_METHODS_AMF_INCOMPLETE_INCREMENTAL_TERMINATION_HPP - -#include - -namespace mlpack { -namespace amf { - -/** - * This class acts as a wrapper for basic termination policies to be used by - * SVDIncompleteIncrementalLearning. This class calls the wrapped class functions - * after every n calls to main class functions where n is the number of rows. - * - * @see AMF, SVDIncompleteIncrementalLearning - */ -template -class IncompleteIncrementalTermination -{ - public: - /** - * Empty constructor - * - * @param tPolicy object of wrapped class. - */ - IncompleteIncrementalTermination( - TerminationPolicy tPolicy = TerminationPolicy()) : - tPolicy(tPolicy) { } - - /** - * Initializes the termination policy before stating the factorization. - * - * @param V Input matrix to be factorized. - */ - template - void Initialize(const MatType& V) - { - tPolicy.Initialize(V); - - // Initialize incremental index to number of rows. - incrementalIndex = V.n_rows; - iteration = 0; - } - - /** - * Check if termination criterio is met. - * - * @param W Basis matrix of output. - * @param H Encoding matrix of output. - */ - bool IsConverged(arma::mat& W, arma::mat& H) - { - // increment iteration count - iteration++; - - // If the iteration count is a multiple of incremental index, return the - // wrapped termination policy result. - if (iteration % incrementalIndex == 0) - return tPolicy.IsConverged(W, H); - else - return false; - } - - //! Get current value of residue. - const double& Index() const { return tPolicy.Index(); } - - //! Get current iteration count. - const size_t& Iteration() const { return iteration; } - - //! Access maximum number of iterations. - size_t MaxIterations() const { return tPolicy.MaxIterations(); } - //! Modify maximum number of iterations. - size_t& MaxIterations() { return tPolicy.MaxIterations(); } - - //! Access the wrapped termination policy. - const TerminationPolicy& TPolicy() const { return tPolicy; } - //! Modify the wrapped termination policy. - TerminationPolicy& TPolicy() { return tPolicy; } - - private: - //! Wrapped termination policy. - TerminationPolicy tPolicy; - - //! Number of iterations after which wrapped class object will be called. - size_t incrementalIndex; - //! Current iteration count. - size_t iteration; -}; // class IncompleteIncrementalTermination - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/max_iteration_termination.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/max_iteration_termination.hpp deleted file mode 100644 index 622a6b564..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/max_iteration_termination.hpp +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @file max_iteration_termination.hpp - * @author Ryan Curtin - * - * A termination policy which only terminates when the maximum number of - * iterations is reached. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AMF_TERMINATION_POLICIES_MAX_ITERATION_TERMINATION_HPP -#define MLPACK_METHODS_AMF_TERMINATION_POLICIES_MAX_ITERATION_TERMINATION_HPP - -namespace mlpack { -namespace amf { - -/** - * This termination policy only terminates when the maximum number of iterations - * has been reached. - */ -class MaxIterationTermination -{ - public: - /** - * Construct the termination policy with the given number of iterations - * allowed (default 1000). If maxIterations is 0, then termination will never - * occur. - * - * @param maxIterations Maximum number of allowed iterations. - */ - MaxIterationTermination(const size_t maxIterations) : - maxIterations(maxIterations), - iteration(0) - { - if (maxIterations == 0) - Log::Warn << "MaxIterationTermination::MaxIterationTermination(): given " - << "number of iterations is 0, so algorithm will never terminate!" - << std::endl; - } - - /** - * Initialize for the given matrix V (there is nothing to do). - */ - template - void Initialize(const MatType& /* V */) { } - - /** - * Check if convergence has occurred. - */ - bool IsConverged(const arma::mat& /* H */, const arma::mat& /* W */) - { - // Return true if we have performed the correct number of iterations. - return (++iteration >= maxIterations); - } - - //! Return something similar to the residue, which in this case is just the - //! number of iterations left, since we don't have access to anything else. - size_t Index() - { - return (iteration > maxIterations) ? 0 : maxIterations - iteration; - } - - //! Get the current iteration. - size_t Iteration() const { return iteration; } - //! Modify the current iteration. - size_t& Iteration() { return iteration; } - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - private: - //! The maximum number of allowed iterations. - size_t maxIterations; - //! The number of the current iteration. - size_t iteration; -}; - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/simple_residue_termination.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/simple_residue_termination.hpp deleted file mode 100644 index da1313633..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/simple_residue_termination.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @file simple_residue_termination.hpp - * @author Sumedh Ghaisas - * - * Termination policy used in AMF (Alternating Matrix Factorization). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef _MLPACK_METHODS_AMF_SIMPLERESIDUETERMINATION_HPP_INCLUDED -#define _MLPACK_METHODS_AMF_SIMPLERESIDUETERMINATION_HPP_INCLUDED - -#include - -namespace mlpack { -namespace amf { - -/** - * This class implements a simple residue-based termination policy. The - * termination decision depends on two factors: the value of the residue (the - * difference between the norm of WH this iteration and the previous iteration), - * and the number of iterations. If the current value of residue drops below - * the threshold or the number of iterations goes above the iteration limit, - * IsConverged() will return true. This class is meant for use with the AMF - * (alternating matrix factorization) class. - * - * @see AMF - */ -class SimpleResidueTermination -{ - public: - /** - * Construct the SimpleResidueTermination object with the given minimum - * residue (or the default) and the given maximum number of iterations (or the - * default). 0 indicates no iteration limit. - * - * @param minResidue Minimum residue for termination. - * @param maxIterations Maximum number of iterations. - */ - SimpleResidueTermination(const double minResidue = 1e-5, - const size_t maxIterations = 10000) - : minResidue(minResidue), maxIterations(maxIterations) { } - - /** - * Initializes the termination policy before stating the factorization. - * - * @param V Input matrix being factorized. - */ - template - void Initialize(const MatType& V) - { - // Initialize the things we keep track of. - residue = DBL_MAX; - iteration = 0; - nm = V.n_rows * V.n_cols; - // Remove history. - normOld = 0; - } - - /** - * Check if termination criterion is met. - * - * @param W Basis matrix of output. - * @param H Encoding matrix of output. - */ - bool IsConverged(arma::mat& W, arma::mat& H) - { - // Calculate the norm and compute the residue, but do it by hand, so as to - // avoid calculating (W*H), which may be very large. - double norm = 0.0; - for (size_t j = 0; j < H.n_cols; ++j) - norm += arma::norm(W * H.col(j), "fro"); - residue = fabs(normOld - norm) / normOld; - - // Store the norm. - normOld = norm; - - // Increment iteration count - iteration++; - Log::Info << "Iteration " << iteration << "; residue " << residue << ".\n"; - - // Check if termination criterion is met. - // If maxIterations == 0, there is no iteration limit. - return (residue < minResidue || iteration == maxIterations); - } - - //! Get current value of residue - const double& Index() const { return residue; } - - //! Get current iteration count - const size_t& Iteration() const { return iteration; } - - //! Access max iteration count - const size_t& MaxIterations() const { return maxIterations; } - size_t& MaxIterations() { return maxIterations; } - - //! Access minimum residue value - const double& MinResidue() const { return minResidue; } - double& MinResidue() { return minResidue; } - - public: - //! residue threshold - double minResidue; - //! iteration threshold - size_t maxIterations; - - //! current value of residue - double residue; - //! current iteration count - size_t iteration; - //! norm of previous iteration - double normOld; - - size_t nm; -}; // class SimpleResidueTermination - -} // namespace amf -} // namespace mlpack - - -#endif // _MLPACK_METHODS_AMF_SIMPLERESIDUETERMINATION_HPP_INCLUDED diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/simple_tolerance_termination.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/simple_tolerance_termination.hpp deleted file mode 100644 index f645494c3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/simple_tolerance_termination.hpp +++ /dev/null @@ -1,199 +0,0 @@ -/** - * @file simple_tolerance_termination.hpp - * @author Sumedh Ghaisas - * - * Termination policy used in AMF (Alternating Matrix Factorization). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef _MLPACK_METHODS_AMF_SIMPLE_TOLERANCE_TERMINATION_HPP_INCLUDED -#define _MLPACK_METHODS_AMF_SIMPLE_TOLERANCE_TERMINATION_HPP_INCLUDED - -#include - -namespace mlpack { -namespace amf { - -/** - * This class implements residue tolerance termination policy. Termination - * criterion is met when increase in residue value drops below the given tolerance. - * To accommodate spikes certain number of successive residue drops are accepted. - * This upper imit on successive drops can be adjusted with reverseStepCount. - * Secondary termination criterion terminates algorithm when iteration count - * goes above the threshold. - * - * @see AMF - */ -template -class SimpleToleranceTermination -{ - public: - //! empty constructor - SimpleToleranceTermination(const double tolerance = 1e-5, - const size_t maxIterations = 10000, - const size_t reverseStepTolerance = 3) - : tolerance(tolerance), - maxIterations(maxIterations), - reverseStepTolerance(reverseStepTolerance) {} - - /** - * Initializes the termination policy before stating the factorization. - * - * @param V Input matrix to be factorized. - */ - void Initialize(const MatType& V) - { - residueOld = DBL_MAX; - iteration = 1; - residue = DBL_MIN; - reverseStepCount = 0; - isCopy = false; - - this->V = &V; - - c_index = 0; - c_indexOld = 0; - - reverseStepCount = 0; - } - - /** - * Check if termination criterio is met. - * - * @param W Basis matrix of output. - * @param H Encoding matrix of output. - */ - bool IsConverged(arma::mat& W, arma::mat& H) - { - arma::mat WH; - - WH = W * H; - - // compute residue - residueOld = residue; - size_t n = V->n_rows; - size_t m = V->n_cols; - double sum = 0; - size_t count = 0; - for (size_t i = 0; i < n; i++) - { - for (size_t j = 0; j < m; j++) - { - double temp = 0; - if ((temp = (*V)(i, j)) != 0) - { - temp = (temp - WH(i, j)); - temp = temp * temp; - sum += temp; - count++; - } - } - } - residue = sum / count; - residue = sqrt(residue); - - // increment iteration count - iteration++; - Log::Info << "Iteration " << iteration << "; residue " - << ((residueOld - residue) / residueOld) << ".\n"; - - // if residue tolerance is not satisfied - if ((residueOld - residue) / residueOld < tolerance && iteration > 4) - { - // check if this is a first of successive drops - if (reverseStepCount == 0 && isCopy == false) - { - // store a copy of W and H matrix - isCopy = true; - this->W = W; - this->H = H; - // store residue values - c_index = residue; - c_indexOld = residueOld; - } - // increase successive drop count - reverseStepCount++; - } - // if tolerance is satisfied - else - { - // initialize successive drop count - reverseStepCount = 0; - // if residue is droped below minimum scrap stored values - if (residue <= c_indexOld && isCopy == true) - { - isCopy = false; - } - } - - // check if termination criterion is met - if (reverseStepCount == reverseStepTolerance || iteration > maxIterations) - { - // if stored values are present replace them with current value as they - // represent the minimum residue point - if (isCopy) - { - W = this->W; - H = this->H; - residue = c_index; - } - return true; - } - else return false; - } - - //! Get current value of residue - const double& Index() const { return residue; } - - //! Get current iteration count - const size_t& Iteration() const { return iteration; } - - //! Access upper limit of iteration count - const size_t& MaxIterations() const { return maxIterations; } - size_t& MaxIterations() { return maxIterations; } - - //! Access tolerance value - const double& Tolerance() const { return tolerance; } - double& Tolerance() { return tolerance; } - - private: - //! tolerance - double tolerance; - //! iteration threshold - size_t maxIterations; - - //! pointer to matrix being factorized - const MatType* V; - - //! current iteration count - size_t iteration; - - //! residue values - double residueOld; - double residue; - double normOld; - - //! tolerance on successive residue drops - size_t reverseStepTolerance; - //! successive residue drops - size_t reverseStepCount; - - //! indicates whether a copy of information is available which corresponds to - //! minimum residue point - bool isCopy; - - //! variables to store information of minimum residue poi - arma::mat W; - arma::mat H; - double c_indexOld; - double c_index; -}; // class SimpleToleranceTermination - -} // namespace amf -} // namespace mlpack - -#endif // _MLPACK_METHODS_AMF_SIMPLE_TOLERANCE_TERMINATION_HPP_INCLUDED - diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/validation_rmse_termination.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/validation_rmse_termination.hpp deleted file mode 100644 index 9171aa0ae..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/termination_policies/validation_rmse_termination.hpp +++ /dev/null @@ -1,241 +0,0 @@ -/** - * @file validation_RMSE_termination.hpp - * @author Sumedh Ghaisas - * - * Termination policy used in AMF (Alternating Matrix Factorization). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef _MLPACK_METHODS_AMF_VALIDATIONRMSETERMINATION_HPP_INCLUDED -#define _MLPACK_METHODS_AMF_VALIDATIONRMSETERMINATION_HPP_INCLUDED - -#include - -namespace mlpack -{ -namespace amf -{ - -/** - * This class implements validation termination policy based on RMSE index. - * The input data matrix is divided into 2 sets, training set and validation set. - * Entries of validation set are nullifed in the input matrix. Termination - * criterion is met when increase in validation set RMSe value drops below the - * given tolerance. To accommodate spikes certain number of successive validation - * RMSE drops are accepted. This upper imit on successive drops can be adjusted - * with reverseStepCount. Secondary termination criterion terminates algorithm - * when iteration count goes above the threshold. - * - * @note The input matrix is modified by this termination policy. - * - * @see AMF - */ -template -class ValidationRMSETermination -{ - public: - /** - * Create a validation set according to given parameters and nullifies this - * set in data matrix(training set). - * - * @param V Input matrix to be factorized. - * @param num_test_points number of validation test points - * @param maxIterations max iteration count before termination - * @param reverseStepTolerance max successive RMSE drops allowed - */ - ValidationRMSETermination(MatType& V, - size_t num_test_points, - double tolerance = 1e-5, - size_t maxIterations = 10000, - size_t reverseStepTolerance = 3) - : tolerance(tolerance), - maxIterations(maxIterations), - num_test_points(num_test_points), - reverseStepTolerance(reverseStepTolerance) - { - size_t n = V.n_rows; - size_t m = V.n_cols; - - // initialize validation set matrix - test_points.zeros(num_test_points, 3); - - // fill validation set matrix with random chosen entries - for (size_t i = 0; i < num_test_points; i++) - { - double t_val; - size_t t_row; - size_t t_col; - - // pick a random non-zero entry - do - { - t_row = rand() % n; - t_col = rand() % m; - } while ((t_val = V(t_row, t_col)) == 0); - - // add the entry to the validation set - test_points(i, 0) = t_row; - test_points(i, 1) = t_col; - test_points(i, 2) = t_val; - - // nullify the added entry from data matrix (training set) - V(t_row, t_col) = 0; - } - } - - /** - * Initializes the termination policy before stating the factorization. - * - * @param V Input matrix to be factorized. - */ - void Initialize(const MatType& /* V */) - { - iteration = 1; - - rmse = DBL_MAX; - rmseOld = DBL_MAX; - - c_index = 0; - c_indexOld = 0; - - reverseStepCount = 0; - isCopy = false; - } - - /** - * Check if termination criterio is met. - * - * @param W Basis matrix of output. - * @param H Encoding matrix of output. - */ - bool IsConverged(arma::mat& W, arma::mat& H) - { - arma::mat WH; - - WH = W * H; - - // compute validation RMSE - if (iteration != 0) - { - rmseOld = rmse; - rmse = 0; - for (size_t i = 0; i < num_test_points; i++) - { - size_t t_row = test_points(i, 0); - size_t t_col = test_points(i, 1); - double t_val = test_points(i, 2); - double temp = (t_val - WH(t_row, t_col)); - temp *= temp; - rmse += temp; - } - rmse /= num_test_points; - rmse = sqrt(rmse); - } - - // increment iteration count - iteration++; - - // if RMSE tolerance is not satisfied - if ((rmseOld - rmse) / rmseOld < tolerance && iteration > 4) - { - // check if this is a first of successive drops - if (reverseStepCount == 0 && isCopy == false) - { - // store a copy of W and H matrix - isCopy = true; - this->W = W; - this->H = H; - // store residue values - c_indexOld = rmseOld; - c_index = rmse; - } - // increase successive drop count - reverseStepCount++; - } - // if tolerance is satisfied - else - { - // initialize successive drop count - reverseStepCount = 0; - // if residue is droped below minimum scrap stored values - if (rmse <= c_indexOld && isCopy == true) - { - isCopy = false; - } - } - - // check if termination criterion is met - if (reverseStepCount == reverseStepTolerance || iteration > maxIterations) - { - // if stored values are present replace them with current value as they - // represent the minimum residue point - if (isCopy) - { - W = this->W; - H = this->H; - rmse = c_index; - } - return true; - } - else return false; - } - - //! Get current value of residue - const double& Index() const { return rmse; } - - //! Get current iteration count - const size_t& Iteration() const { return iteration; } - - //! Get number of validation points - const size_t& NumTestPoints() const { return num_test_points; } - - //! Access upper limit of iteration count - const size_t& MaxIterations() const { return maxIterations; } - size_t& MaxIterations() { return maxIterations; } - - //! Access tolerance value - const double& Tolerance() const { return tolerance; } - double& Tolerance() { return tolerance; } - - private: - //! tolerance - double tolerance; - //! max iteration limit - size_t maxIterations; - //! number of validation test points - size_t num_test_points; - - //! current iteration count - size_t iteration; - - //! validation point matrix - arma::mat test_points; - - //! rmse values - double rmseOld; - double rmse; - - //! tolerance on successive residue drops - size_t reverseStepTolerance; - //! successive residue drops - size_t reverseStepCount; - - //! indicates whether a copy of information is available which corresponds to - //! minimum residue point - bool isCopy; - - //! variables to store information of minimum residue point - arma::mat W; - arma::mat H; - double c_indexOld; - double c_index; -}; // class ValidationRMSETermination - -} // namespace amf -} // namespace mlpack - - -#endif // _MLPACK_METHODS_AMF_VALIDATIONRMSETERMINATION_HPP_INCLUDED diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_als.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_als.hpp deleted file mode 100644 index 8d860cc50..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_als.hpp +++ /dev/null @@ -1,129 +0,0 @@ -/** - * @file nmf_als.hpp - * @author Mohan Rajendran - * - * Update rules for the Non-negative Matrix Factorization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LMF_UPDATE_RULES_NMF_ALS_HPP -#define MLPACK_METHODS_LMF_UPDATE_RULES_NMF_ALS_HPP - -#include - -namespace mlpack { -namespace amf { - -/** - * This class implements a method titled 'Alternating Least Squares' described - * in the following paper: - * - * @code - * @article{paatero1994positive, - * title={Positive matrix factorization: A non-negative factor model with - * optimal utilization of error estimates of data values}, - * author={Paatero, P. and Tapper, U.}, - * journal={Environmetrics}, - * volume={5}, - * number={2}, - * pages={111--126}, - * year={1994} - * } - * @endcode - * - * It uses the least squares projection formula to reduce the error value of - * \f$ \sqrt{\sum_i \sum_j(V-WH)^2} \f$ by alternately calculating W and H - * respectively while holding the other matrix constant. - */ -class NMFALSUpdate -{ - public: - //! Empty constructor required for the UpdateRule template. - NMFALSUpdate() { } - - /** - * Set initial values for the factorization. In this case, we don't need to - * set anything. - */ - template - void Initialize(const MatType& /* dataset */, const size_t /* rank */) - { - // Nothing to do. - } - - /** - * The update rule for the basis matrix W. The formula used isa - * - * \f[ - * W^T = \frac{H V^T}{H H^T} - * \f] - * - * The function takes in all the matrices and only changes the value of the W - * matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix to be updated. - * @param H Encoding matrix. - */ - template - inline static void WUpdate(const MatType& V, - arma::mat& W, - const arma::mat& H) - { - // The call to inv() sometimes fails; so we are using the psuedoinverse. - // W = (inv(H * H.t()) * H * V.t()).t(); - W = V * H.t() * pinv(H * H.t()); - - // Set all negative numbers to machine epsilon. - for (size_t i = 0; i < W.n_elem; i++) - { - if (W(i) < 0.0) - { - W(i) = 0.0; - } - } - } - - /** - * The update rule for the encoding matrix H. The formula used is - * - * \f[ - * H = \frac{W^T V}{W^T W} - * \f] - * - * The function takes in all the matrices and only changes the value of the H - * matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix. - * @param H Encoding matrix to be updated. - */ - template - inline static void HUpdate(const MatType& V, - const arma::mat& W, - arma::mat& H) - { - H = pinv(W.t() * W) * W.t() * V; - - // Set all negative numbers to 0. - for (size_t i = 0; i < H.n_elem; i++) - { - if (H(i) < 0.0) - { - H(i) = 0.0; - } - } - } - - //! Serialize the object (in this case, there is nothing to serialize). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; // class NMFALSUpdate - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_mult_dist.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_mult_dist.hpp deleted file mode 100644 index 22e95ae17..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_mult_dist.hpp +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file nmf_mult_dist.hpp - * @author Mohan Rajendran - * - * Update rules for the Non-negative Matrix Factorization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LMF_UPDATE_RULES_NMF_MULT_DIST_UPDATE_RULES_HPP -#define MLPACK_METHODS_LMF_UPDATE_RULES_NMF_MULT_DIST_UPDATE_RULES_HPP - -#include - -namespace mlpack { -namespace amf { - -/** - * The multiplicative distance update rules for matrices W and H. This follows - * a method described in the following paper: - * - * @code - * @inproceedings{lee2001algorithms, - * title={Algorithms for non-negative matrix factorization}, - * author={Lee, D.D. and Seung, H.S.}, - * booktitle={Advances in Neural Information Processing Systems 13 - * (NIPS 2000)}, - * pages={556--562}, - * year={2001} - * } - * @endcode - * - * This is a multiplicative rule that ensures that the Frobenius norm - * \f$ \sqrt{\sum_i \sum_j(V-WH)^2} \f$ is non-increasing between subsequent - * iterations. Both of the update rules for W and H are defined in this file. - */ -class NMFMultiplicativeDistanceUpdate -{ - public: - // Empty constructor required for the UpdateRule template. - NMFMultiplicativeDistanceUpdate() { } - - /** - * Initialize the factorization. These update rules hold no information, so - * the input parameters are ignored. - */ - template - void Initialize(const MatType& /* dataset */, const size_t /* rank */) - { - // Nothing to do. - } - - /** - * The update rule for the basis matrix W. The formula used isa - * - * \f[ - * W_{ia} \leftarrow W_{ia} \frac{(VH^T)_{ia}}{(WHH^T)_{ia}} - * \f] - * - * The function takes in all the matrices and only changes the value of the W - * matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix to be updated. - * @param H Encoding matrix. - */ - template - inline static void WUpdate(const MatType& V, - arma::mat& W, - const arma::mat& H) - { - W = (W % (V * H.t())) / (W * H * H.t()); - } - - /** - * The update rule for the encoding matrix H. The formula used is - * - * \f[ - * H_{a\mu} \leftarrow H_{a\mu} \frac{(W^T V)_{a\mu}}{(W^T WH)_{a\mu}} - * \f] - * - * The function takes in all the matrices and only changes the value of the H - * matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix. - * @param H Encoding matrix to be updated. - */ - template - inline static void HUpdate(const MatType& V, - const arma::mat& W, - arma::mat& H) - { - H = (H % (W.t() * V)) / (W.t() * W * H); - } - - //! Serialize the object (in this case, there is nothing to serialize). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_mult_div.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_mult_div.hpp deleted file mode 100644 index 60310a8ec..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/nmf_mult_div.hpp +++ /dev/null @@ -1,160 +0,0 @@ -/** - * @file mult_div_update_rules.hpp - * @author Mohan Rajendran - * - * Update rules for the Non-negative Matrix Factorization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LMF_UPDATE_RULES_NMF_MULT_DIV_HPP -#define MLPACK_METHODS_LMF_UPDATE_RULES_NMF_MULT_DIV_HPP - -#include - -namespace mlpack { -namespace amf { - -/** - * This follows a method described in the paper 'Algorithms for Non-negative - * - * @code - * @inproceedings{lee2001algorithms, - * title={Algorithms for non-negative matrix factorization}, - * author={Lee, D.D. and Seung, H.S.}, - * booktitle={Advances in Neural Information Processing Systems 13 - * (NIPS 2000)}, - * pages={556--562}, - * year={2001} - * } - * @endcode - * - * This is a multiplicative rule that ensures that the Kullback–Leibler - * divergence - * - * \f[ - * \sum_i \sum_j (V_{ij} \log\frac{V_{ij}}{(W H)_{ij}} - V_{ij} + (W H)_{ij}) - * \f] - * - * is non-increasing between subsequent iterations. Both of the update rules - * for W and H are defined in this file. - * - * This set of update rules is not meant to work with sparse matrices. Using - * sparse matrices often causes NaNs in the output, so other choices of update - * rules are better in that situation. - */ -class NMFMultiplicativeDivergenceUpdate -{ - public: - // Empty constructor required for the WUpdateRule template. - NMFMultiplicativeDivergenceUpdate() { } - - /** - * Initialize the factorization. These rules don't store any state, so the - * input values are ignore. - */ - template - void Initialize(const MatType& /* dataset */, const size_t /* rank */) - { - // Nothing to do. - } - - /** - * The update rule for the basis matrix W. The formula used is - * - * \f[ - * W_{ia} \leftarrow W_{ia} \frac{\sum_{\mu} H_{a\mu} V_{i\mu} / (W H)_{i\mu}} - * {\sum_{\nu} H_{a\nu}} - * \f] - * - * The function takes in all the matrices and only changes the value of the W - * matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix to be updated. - * @param H Encoding matrix. - */ - template - inline static void WUpdate(const MatType& V, - arma::mat& W, - const arma::mat& H) - { - // Simple implementation left in the header file. - arma::mat t1; - arma::rowvec t2; - - t1 = W * H; - for (size_t i = 0; i < W.n_rows; ++i) - { - for (size_t j = 0; j < W.n_cols; ++j) - { - // Writing this as a single expression does not work as of Armadillo - // 3.920. This should be fixed in a future release, and then the code - // below can be fixed. - // t2 = H.row(j) % V.row(i) / t1.row(i); - t2.set_size(H.n_cols); - for (size_t k = 0; k < t2.n_elem; ++k) - { - t2(k) = H(j, k) * V(i, k) / t1(i, k); - } - - W(i, j) = W(i, j) * sum(t2) / sum(H.row(j)); - } - } - } - - /** - * The update rule for the encoding matrix H. The formula used is - * - * \f[ - * H_{a\mu} \leftarrow H_{a\mu} \frac{\sum_{i} W_{ia} V_{i\mu}/(WH)_{i\mu}} - * {\sum_{k} H_{ka}} - * \f] - * - * The function takes in all the matrices and only changes the value of the H - * matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix. - * @param H Encoding matrix to updated. - */ - template - inline static void HUpdate(const MatType& V, - const arma::mat& W, - arma::mat& H) - { - // Simple implementation left in the header file. - arma::mat t1; - arma::colvec t2; - - t1 = W * H; - for (size_t i = 0; i < H.n_rows; i++) - { - for (size_t j = 0; j < H.n_cols; j++) - { - // Writing this as a single expression does not work as of Armadillo - // 3.920. This should be fixed in a future release, and then the code - // below can be fixed. - // t2 = W.col(i) % V.col(j) / t1.col(j); - t2.set_size(W.n_rows); - for (size_t k = 0; k < t2.n_elem; ++k) - { - t2(k) = W(k, i) * V(k, j) / t1(k, j); - } - - H(i, j) = H(i, j) * sum(t2) / sum(W.col(i)); - } - } - } - - //! Serialize the object (in this case, there is nothing to serialize). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_batch_learning.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_batch_learning.hpp deleted file mode 100644 index 63e8d9d03..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_batch_learning.hpp +++ /dev/null @@ -1,260 +0,0 @@ -/** - * @file svd_batch_learning.hpp - * @author Sumedh Ghaisas - * - * SVD factorizer used in AMF (Alternating Matrix Factorization). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AMF_UPDATE_RULES_SVD_BATCH_LEARNING_HPP -#define MLPACK_METHODS_AMF_UPDATE_RULES_SVD_BATCH_LEARNING_HPP - -#include - -namespace mlpack { -namespace amf { - -/** - * This class implements SVD batch learning with momentum. This procedure is - * described in the following paper: - * - * @code - * @techreport{ma2008guide, - * title={A Guide to Singular Value Decomposition for Collaborative - * Filtering}, - * author={Ma, Chih-Chao}, - * year={2008}, - * institution={Department of Computer Science, National Taiwan University} - * } - * @endcode - * - * This class implements 'Algorithm 4' as given in the paper. - * - * The factorizer decomposes the matrix V into two matrices W and H such that - * sum of sum of squared error between V and W * H is minimum. This optimization - * is performed with gradient descent. To make gradient descent faster, momentum - * is added. - */ -class SVDBatchLearning -{ - public: - /** - * SVD Batch learning constructor. - * - * @param u step value used in batch learning - * @param kw regularization constant for W matrix - * @param kh regularization constant for H matrix - * @param momentum momentum applied to batch learning process - */ - SVDBatchLearning(double u = 0.0002, - double kw = 0, - double kh = 0, - double momentum = 0.9) - : u(u), kw(kw), kh(kh), momentum(momentum) - { - // empty constructor - } - - /** - * Initialize parameters before factorization. This function must be called - * before a new factorization. This resets the internally-held momentum. - * - * @param dataset Input matrix to be factorized. - * @param rank rank of factorization - */ - template - void Initialize(const MatType& dataset, const size_t rank) - { - const size_t n = dataset.n_rows; - const size_t m = dataset.n_cols; - - mW.zeros(n, rank); - mH.zeros(rank, m); - } - - /** - * The update rule for the basis matrix W. - * The function takes in all the matrices and only changes the - * value of the W matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix to be updated. - * @param H Encoding matrix. - */ - template - inline void WUpdate(const MatType& V, - arma::mat& W, - const arma::mat& H) - { - size_t n = V.n_rows; - size_t m = V.n_cols; - - size_t r = W.n_cols; - - // initialize the momentum of this iteration. - mW = momentum * mW; - - // Compute the step. - arma::mat deltaW; - deltaW.zeros(n, r); - for (size_t i = 0; i < n; i++) - { - for (size_t j = 0; j < m; j++) - { - const double val = V(i, j); - if (val != 0) - deltaW.row(i) += (val - arma::dot(W.row(i), H.col(j))) * - arma::trans(H.col(j)); - } - // Add regularization. - if (kw != 0) - deltaW.row(i) -= kw * W.row(i); - } - - // Add the step to the momentum. - mW += u * deltaW; - // Add the momentum to the W matrix. - W += mW; - } - - /** - * The update rule for the encoding matrix H. - * The function takes in all the matrices and only changes the - * value of the H matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix. - * @param H Encoding matrix to be updated. - */ - template - inline void HUpdate(const MatType& V, - const arma::mat& W, - arma::mat& H) - { - size_t n = V.n_rows; - size_t m = V.n_cols; - - size_t r = W.n_cols; - - // Initialize the momentum of this iteration. - mH = momentum * mH; - - // Compute the step. - arma::mat deltaH; - deltaH.zeros(r, m); - for (size_t j = 0; j < m; j++) - { - for (size_t i = 0; i < n; i++) - { - const double val = V(i, j); - if (val != 0) - deltaH.col(j) += (val - arma::dot(W.row(i), H.col(j))) * W.row(i).t(); - } - // Add regularization. - if (kh != 0) - deltaH.col(j) -= kh * H.col(j); - } - - // Add this step to the momentum. - mH += u * deltaH; - // Add the momentum to H. - H += mH; - } - - //! Serialize the SVDBatch object. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(u); - ar & BOOST_SERIALIZATION_NVP(kw); - ar & BOOST_SERIALIZATION_NVP(kh); - ar & BOOST_SERIALIZATION_NVP(momentum); - ar & BOOST_SERIALIZATION_NVP(mW); - ar & BOOST_SERIALIZATION_NVP(mH); - } - - private: - //! Step size of the algorithm. - double u; - //! Regularization parameter for matrix W. - double kw; - //! Regularization parameter for matrix H. - double kh; - //! Momentum value (between 0 and 1). - double momentum; - - //! Momentum matrix for matrix W - arma::mat mW; - //! Momentum matrix for matrix H - arma::mat mH; -}; // class SVDBatchLearning - -//! TODO : Merge this template specialized function for sparse matrix using -//! common row_col_iterator - -/** - * WUpdate function specialization for sparse matrix - */ -template<> -inline void SVDBatchLearning::WUpdate(const arma::sp_mat& V, - arma::mat& W, - const arma::mat& H) -{ - const size_t n = V.n_rows; - const size_t r = W.n_cols; - - mW = momentum * mW; - - arma::mat deltaW; - deltaW.zeros(n, r); - - for (arma::sp_mat::const_iterator it = V.begin(); it != V.end(); ++it) - { - const size_t row = it.row(); - const size_t col = it.col(); - deltaW.row(it.row()) += (*it - arma::dot(W.row(row), H.col(col))) * - arma::trans(H.col(col)); - } - - if (kw != 0) - deltaW -= kw * W; - - mW += u * deltaW; - W += mW; -} - -template<> -inline void SVDBatchLearning::HUpdate(const arma::sp_mat& V, - const arma::mat& W, - arma::mat& H) -{ - const size_t m = V.n_cols; - const size_t r = W.n_cols; - - mH = momentum * mH; - - arma::mat deltaH; - deltaH.zeros(r, m); - - for (arma::sp_mat::const_iterator it = V.begin(); it != V.end(); ++it) - { - const size_t row = it.row(); - const size_t col = it.col(); - deltaH.col(col) += (*it - arma::dot(W.row(row), H.col(col))) * - W.row(row).t(); - } - - if (kh != 0) - deltaH -= kh * H; - - mH += u * deltaH; - H += mH; -} - -} // namespace amf -} // namespace mlpack - -#endif // MLPACK_METHODS_AMF_UPDATE_RULES_SVD_BATCH_LEARNING_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_complete_incremental_learning.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_complete_incremental_learning.hpp deleted file mode 100644 index 25c935cd1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_complete_incremental_learning.hpp +++ /dev/null @@ -1,273 +0,0 @@ -/** - * @file svd_complete_incremental_learning.hpp - * @author Sumedh Ghaisas - * - * SVD factorizer used in AMF (Alternating Matrix Factorization). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AMF_SVD_COMPLETE_INCREMENTAL_LEARNING_HPP -#define MLPACK_METHODS_AMF_SVD_COMPLETE_INCREMENTAL_LEARNING_HPP - -#include - -namespace mlpack -{ -namespace amf -{ - -/** - * This class computes SVD using complete incremental batch learning, as - * described in the following paper: - * - * @code - * @techreport{ma2008guide, - * title={A Guide to Singular Value Decomposition for Collaborative - * Filtering}, - * author={Ma, Chih-Chao}, - * year={2008}, - * institution={Department of Computer Science, National Taiwan University} - * } - * @endcode - * - * This class implements 'Algorithm 3' given in the paper. Complete incremental - * learning is an extreme case of incremental learning, where feature vectors - * are updated after looking at each single element in the input matrix (V). - * This approach differs from incomplete incremental learning where feature - * vectors are updated after seeing columns of elements in the input matrix. - * - * @see SVDIncompleteIncrementalLearning - */ -template -class SVDCompleteIncrementalLearning -{ - public: - /** - * Initialize the SVDCompleteIncrementalLearning class with the given - * parameters. - * - * @param u Step value used in batch learning. - * @param kw Regularization constant for W matrix. - * @param kh Regularization constant for H matrix. - */ - SVDCompleteIncrementalLearning(double u = 0.0001, - double kw = 0, - double kh = 0) - : u(u), kw(kw), kh(kh) - { - // Nothing to do. - } - - /** - * Initialize parameters before factorization. This function must be called - * before a new factorization. For this initialization, the input parameters - * are unnecessary; we are only setting the current element index to 0. - * - * @param dataset Input matrix to be factorized. - * @param rank rank of factorization - */ - void Initialize(const MatType& /* dataset */, const size_t /* rank */) - { - // Initialize the current score counters. - currentUserIndex = 0; - currentItemIndex = 0; - } - - /** - * The update rule for the basis matrix W. The function takes in all the - * matrices and only changes the value of the W matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix to be updated. - * @param H Encoding matrix. - */ - inline void WUpdate(const MatType& V, - arma::mat& W, - const arma::mat& H) - { - arma::mat deltaW; - deltaW.zeros(1, W.n_cols); - - // Loop until a non-zero entry is found. - while (true) - { - const double val = V(currentItemIndex, currentUserIndex); - // Update feature vector if current entry is non-zero and break the loop. - if (val != 0) - { - deltaW += (val - arma::dot(W.row(currentItemIndex), - H.col(currentUserIndex))) * H.col(currentUserIndex).t(); - - // Add regularization. - if (kw != 0) - deltaW -= kw * W.row(currentItemIndex); - break; - } - } - - W.row(currentItemIndex) += u * deltaW; - } - - /** - * The update rule for the encoding matrix H. - * The function takes in all the matrices and only changes the - * value of the H matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix. - * @param H Encoding matrix to be updated. - */ - inline void HUpdate(const MatType& V, - const arma::mat& W, - arma::mat& H) - { - arma::mat deltaH; - deltaH.zeros(H.n_rows, 1); - - const double val = V(currentItemIndex, currentUserIndex); - - // Update H matrix based on the non-zero entry found in WUpdate function. - deltaH += (val - arma::dot(W.row(currentItemIndex), - H.col(currentUserIndex))) * W.row(currentItemIndex).t(); - // Add regularization. - if (kh != 0) - deltaH -= kh * H.col(currentUserIndex); - - // Move on to the next entry. - currentUserIndex = currentUserIndex + 1; - if (currentUserIndex == V.n_rows) - { - currentUserIndex = 0; - currentItemIndex = (currentItemIndex + 1) % V.n_cols; - } - - H.col(currentUserIndex++) += u * deltaH; - } - - private: - //! Step count of batch learning. - double u; - //! Regularization parameter for matrix W. - double kw; - //! Regularization parameter for matrix H. - double kh; - - //! User of index of current entry. - size_t currentUserIndex; - //! Item index of current entry. - size_t currentItemIndex; -}; - -//! TODO : Merge this template specialized function for sparse matrix using -//! common row_col_iterator - -//! template specialiazed functions for sparse matrices -template<> -class SVDCompleteIncrementalLearning -{ - public: - SVDCompleteIncrementalLearning(double u = 0.01, - double kw = 0, - double kh = 0) - : u(u), kw(kw), kh(kh), it(NULL) - {} - - ~SVDCompleteIncrementalLearning() - { - delete it; - } - - void Initialize(const arma::sp_mat& dataset, const size_t rank) - { - (void)rank; - n = dataset.n_rows; - m = dataset.n_cols; - - it = new arma::sp_mat::const_iterator(dataset.begin()); - isStart = true; - } - - /** - * The update rule for the basis matrix W. - * The function takes in all the matrices and only changes the - * value of the W matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix to be updated. - * @param H Encoding matrix. - */ - inline void WUpdate(const arma::sp_mat& V, - arma::mat& W, - const arma::mat& H) - { - if (!isStart) - ++(*it); - else isStart = false; - - if (*it == V.end()) - { - delete it; - it = new arma::sp_mat::const_iterator(V.begin()); - } - - size_t currentUserIndex = it->col(); - size_t currentItemIndex = it->row(); - - arma::mat deltaW(1, W.n_cols); - deltaW.zeros(); - - deltaW += (**it - arma::dot(W.row(currentItemIndex), - H.col(currentUserIndex))) * arma::trans(H.col(currentUserIndex)); - if (kw != 0) deltaW -= kw * W.row(currentItemIndex); - - W.row(currentItemIndex) += u*deltaW; - } - - /** - * The update rule for the encoding matrix H. - * The function takes in all the matrices and only changes the - * value of the H matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix. - * @param H Encoding matrix to be updated. - */ - inline void HUpdate(const arma::sp_mat& /* V */, - const arma::mat& W, - arma::mat& H) - { - arma::mat deltaH(H.n_rows, 1); - deltaH.zeros(); - - size_t currentUserIndex = it->col(); - size_t currentItemIndex = it->row(); - - deltaH += (**it - arma::dot(W.row(currentItemIndex), - H.col(currentUserIndex))) * arma::trans(W.row(currentItemIndex)); - if (kh != 0) deltaH -= kh * H.col(currentUserIndex); - - H.col(currentUserIndex) += u * deltaH; - } - - private: - double u; - double kw; - double kh; - - size_t n; - size_t m; - - arma::sp_mat dummy; - arma::sp_mat::const_iterator* it; - - bool isStart; -}; // class SVDCompleteIncrementalLearning - -} // namespace amf -} // namespace mlpack - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_incomplete_incremental_learning.hpp b/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_incomplete_incremental_learning.hpp deleted file mode 100644 index 95467c4b1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/amf/update_rules/svd_incomplete_incremental_learning.hpp +++ /dev/null @@ -1,211 +0,0 @@ -/** - * @file svd_incomplete_incremental_learning.hpp - * @author Sumedh Ghaisas - * - * SVD factorizer used in AMF (Alternating Matrix Factorization). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AMF_SVD_INCOMPLETE_INCREMENTAL_LEARNING_HPP -#define MLPACK_METHODS_AMF_SVD_INCOMPLETE_INCREMENTAL_LEARNING_HPP - -namespace mlpack -{ -namespace amf -{ - -/** - * This class computes SVD using incomplete incremental batch learning, as - * described in the following paper: - * - * @code - * @techreport{ma2008guide, - * title={A Guide to Singular Value Decomposition for Collaborative - * Filtering}, - * author={Ma, Chih-Chao}, - * year={2008}, - * institution={Department of Computer Science, National Taiwan University} - * } - * @endcode - * - * This class implements 'Algorithm 2' as given in the paper. Incremental - * learning modifies only some feature values in W and H after scanning part of - * the input matrix (V). This differs from batch learning, which considers - * every element in V for each update of W and H. The regularization technique - * is also different: in incomplete incremental learning, regularization takes - * into account the number of elements in a given column of V. - * - * @see SVDBatchLearning - */ -class SVDIncompleteIncrementalLearning -{ - public: - /** - * Initialize the parameters of SVDIncompleteIncrementalLearning. - * - * @param u Step value used in batch learning. - * @param kw Regularization constant for W matrix. - * @param kh Regularization constant for H matrix. - */ - SVDIncompleteIncrementalLearning(double u = 0.001, - double kw = 0, - double kh = 0) - : u(u), kw(kw), kh(kh) - { - // Nothing to do. - } - - /** - * Initialize parameters before factorization. This function must be called - * before a new factorization. This simply sets the column being considered - * to 0, so the input matrix and rank are not used. - * - * @param dataset Input matrix to be factorized. - * @param rank rank of factorization - */ - template - void Initialize(const MatType& /* dataset */, const size_t /* rank */) - { - // Set the current user to 0. - currentUserIndex = 0; - } - - /** - * The update rule for the basis matrix W. - * The function takes in all the matrices and only changes the - * value of the W matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix to be updated. - * @param H Encoding matrix. - */ - template - inline void WUpdate(const MatType& V, - arma::mat& W, - const arma::mat& H) - { - arma::mat deltaW; - deltaW.zeros(V.n_rows, W.n_cols); - - // Iterate through all the rating by this user to update corresponding item - // feature feature vector. - for (size_t i = 0; i < V.n_rows; ++i) - { - const double val = V(i, currentUserIndex); - // Update only if the rating is non-zero. - if (val != 0) - { - deltaW.row(i) += (val - arma::dot(W.row(i), H.col(currentUserIndex))) * - H.col(currentUserIndex).t(); - } - // Add regularization. - if (kw != 0) - deltaW.row(i) -= kw * W.row(i); - } - - W += u * deltaW; - } - - /** - * The update rule for the encoding matrix H. The function takes in all the - * matrices and only changes the value of the H matrix. - * - * @param V Input matrix to be factorized. - * @param W Basis matrix. - * @param H Encoding matrix to be updated. - */ - template - inline void HUpdate(const MatType& V, - const arma::mat& W, - arma::mat& H) - { - arma::vec deltaH; - deltaH.zeros(H.n_rows); - - // Iterate through all the rating by this user to update corresponding item - // feature feature vector. - for (size_t i = 0; i < V.n_rows; ++i) - { - const double val = V(i, currentUserIndex); - // Update only if the rating is non-zero. - if (val != 0) - { - deltaH += (val - arma::dot(W.row(i), H.col(currentUserIndex))) * - W.row(i).t(); - } - } - // Add regularization. - if (kh != 0) - deltaH -= kh * H.col(currentUserIndex); - - // Update H matrix and move on to the next user. - H.col(currentUserIndex++) += u * deltaH; - currentUserIndex = currentUserIndex % V.n_cols; - } - - private: - //! Step size of batch learning. - double u; - //! Regularization parameter for W matrix. - double kw; - //! Regularization parameter for H matrix. - double kh; - - //! Current user under consideration. - size_t currentUserIndex; -}; - -//! TODO : Merge this template specialized function for sparse matrix using -//! common row_col_iterator - -//! template specialiazed functions for sparse matrices -template<> -inline void SVDIncompleteIncrementalLearning::WUpdate( - const arma::sp_mat& V, arma::mat& W, const arma::mat& H) -{ - arma::mat deltaW(V.n_rows, W.n_cols); - deltaW.zeros(); - for (arma::sp_mat::const_iterator it = V.begin_col(currentUserIndex); - it != V.end_col(currentUserIndex); ++it) - { - double val = *it; - size_t i = it.row(); - deltaW.row(i) += (val - arma::dot(W.row(i), H.col(currentUserIndex))) * - arma::trans(H.col(currentUserIndex)); - if (kw != 0) deltaW.row(i) -= kw * W.row(i); - } - - W += u*deltaW; -} - -template<> -inline void SVDIncompleteIncrementalLearning::HUpdate( - const arma::sp_mat& V, const arma::mat& W, arma::mat& H) -{ - arma::mat deltaH(H.n_rows, 1); - deltaH.zeros(); - - for (arma::sp_mat::const_iterator it = V.begin_col(currentUserIndex); - it != V.end_col(currentUserIndex); ++it) - { - double val = *it; - size_t i = it.row(); - if ((val = V(i, currentUserIndex)) != 0) - { - deltaH += (val - arma::dot(W.row(i), H.col(currentUserIndex))) * - arma::trans(W.row(i)); - } - } - if (kh != 0) deltaH -= kh * H.col(currentUserIndex); - - H.col(currentUserIndex++) += u * deltaH; - currentUserIndex = currentUserIndex % V.n_cols; -} - -} // namespace amf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/identity_function.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/identity_function.hpp deleted file mode 100644 index b98905a45..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/identity_function.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file identity_function.hpp - * @author Marcus Edel - * - * Definition and implementation of the identity function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_IDENTITY_FUNCTION_HPP -#define MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_IDENTITY_FUNCTION_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The identity function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& x \\ - * f'(x) &=& 1 - * @f} - */ -class IdentityFunction -{ - public: - /** - * Computes the identity function. - * - * @param x Input data. - * @return f(x). - */ - static double Fn(const double x) - { - return x; - } - - /** - * Computes the identity function. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const InputVecType& x, OutputVecType& y) - { - y = x; - } - - /** - * Computes the first derivative of the identity function. - * - * @param x Input data. - * @return f'(x) - */ - static double Deriv(const double /* unused */) - { - return 1.0; - } - - /** - * Computes the first derivatives of the identity function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - template - static void Deriv(const InputVecType& y, OutputVecType& x) - { - x.ones(arma::size(y)); - } - - /** - * Computes the first derivatives of the identity function using a 3rd order - * tensor as input. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - template - static void Deriv(const arma::Cube& y, arma::Cube& x) - { - x.ones(y.n_rows, y.n_cols, y.n_slices); - } -}; // class IdentityFunction - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/logistic_function.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/logistic_function.hpp deleted file mode 100644 index 20e162227..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/logistic_function.hpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @file logistic_function.hpp - * @author Marcus Edel - * - * Definition and implementation of the logistic function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_LOGISTIC_FUNCTION_HPP -#define MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_LOGISTIC_FUNCTION_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The logistic function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \frac{1}{1 + e^{-x}} \\ - * f'(x) &=& f(x) * (1 - f(x)) \\ - * f^{-1}(y) &=& ln(\frac{y}{1-y}) - * @f} - */ -class LogisticFunction -{ - public: - /** - * Computes the logistic function. - * - * @param x Input data. - * @return f(x). - */ - template - static double Fn(const eT x) - { - if (x < arma::Datum::log_max) - { - if (x > -arma::Datum::log_max) - return 1.0 / (1.0 + std::exp(-x)); - - return 0.0; - } - - return 1.0; - } - - /** - * Computes the logistic function. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const InputVecType& x, OutputVecType& y) - { - y = (1.0 / (1 + arma::exp(-x))); - } - - /** - * Computes the first derivative of the logistic function. - * - * @param x Input data. - * @return f'(x) - */ - static double Deriv(const double y) - { - return y * (1.0 - y); - } - - /** - * Computes the first derivatives of the logistic function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - template - static void Deriv(const InputVecType& y, OutputVecType& x) - { - x = y % (1.0 - y); - } - - /** - * Computes the inverse of the logistic function. - * - * @param y Input data. - * @return f^{-1}(y) - */ - static double Inv(const double y) - { - return arma::trunc_log(y / (1 - y)); - } - - /** - * Computes the inverse of the logistic function. - * - * @param y Input data. - * @return x The resulting inverse of the input data. - */ - template - static void Inv(const InputVecType& y, OutputVecType& x) - { - x = arma::trunc_log(y / (1 - y)); - } -}; // class LogisticFunction - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/rectifier_function.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/rectifier_function.hpp deleted file mode 100644 index e1a3b6d1c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/rectifier_function.hpp +++ /dev/null @@ -1,115 +0,0 @@ -/** - * @file rectifier_function.hpp - * @author Marcus Edel - * - * Definition and implementation of the rectifier function as described by - * V. Nair and G. E. Hinton. - * - * For more information, see the following paper. - * - * @code - * @misc{NairHinton2010, - * author = {Vinod Nair, Geoffrey E. Hinton}, - * title = {Rectified Linear Units Improve Restricted Boltzmann Machines}, - * year = {2010} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_RECTIFIER_FUNCTION_HPP -#define MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_RECTIFIER_FUNCTION_HPP - -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The rectifier function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \max(0, x) \\ - * f'(x) &=& \left\{ - * \begin{array}{lr} - * 1 & : x > 0 \\ - * 0 & : x \le 0 - * \end{array} - * \right. - * @f} - */ -class RectifierFunction -{ - public: - /** - * Computes the rectifier function. - * - * @param x Input data. - * @return f(x). - */ - static double Fn(const double x) - { - return std::max(0.0, x); - } - - /** - * Computes the rectifier function using a dense matrix as input. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const arma::Mat& x, arma::Mat& y) - { - y = arma::max(arma::zeros >(x.n_rows, x.n_cols), x); - } - - /** - * Computes the rectifier function using a 3rd-order tensor as input. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const arma::Cube& x, arma::Cube& y) - { - y = x; - for (size_t s = 0; s < x.n_slices; s++) - Fn(x.slice(s), y.slice(s)); - } - - /** - * Computes the first derivative of the rectifier function. - * - * @param x Input data. - * @return f'(x) - */ - static double Deriv(const double y) - { - return y > 0; - } - - /** - * Computes the first derivatives of the rectifier function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - template - static void Deriv(const InputType& y, OutputType& x) - { - x = y; - - for (size_t i = 0; i < y.n_elem; i++) - x(i) = Deriv(y(i)); - } -}; // class RectifierFunction - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/softplus_function.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/softplus_function.hpp deleted file mode 100644 index 395e99db9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/softplus_function.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @file softplus_function.hpp - * @author Vivek Pal - * - * Definition and implementation of the softplus function as described by - * Charles Dugas, Yoshua Bengio, Franc¸ois Belisle, Claude Nadeau & Rene Garcia. - * - * For more information, please see the following paper: - * - * @code - * @inproceedings{Dugas2001, - * author = {Dugas, Charles and Bengio, Yoshua and Belisle, Francois and - * Nadeau, Claude and Garcia, Rene}, - * title = {Incorporating Second-Order Functional Knowledge for Better - * Option Pricing}, - * booktitle = {Advances in Neural Information Processing Systems}, - * year = {2001} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_SOFTPLUS_FUNCTION_HPP -#define MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_SOFTPLUS_FUNCTION_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The softplus function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \ln(1 + e^{x}) \\ - * f'(x) &=& \frac{1}{1 + e^{-x}} \\ - * f^{-1}(y) &=& \ln(e^{y} - 1) - * @f} - */ -class SoftplusFunction -{ - public: - /** - * Computes the softplus function. - * - * @param x Input data. - * @return f(x). - */ - static double Fn(const double x) - { - if (x < DBL_MAX) - return x > -DBL_MAX ? std::log(1 + std::exp(x)) : 0; - return 1.0; - } - - /** - * Computes the softplus function. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const InputType& x, OutputType& y) - { - y = x; - y.transform([](double val) {return (Fn(val));} ); - } - - /** - * Computes the first derivative of the softplus function. - * - * @param y Input data. - * @return f'(x) - */ - static double Deriv(const double y) - { - return 1.0 / (1 + std::exp(-y)); - } - - /** - * Computes the first derivatives of the softplus function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - template - static void Deriv(const InputType& y, OutputType& x) - { - x = 1.0 / (1 + arma::exp(-y)); - } - - /** - * Computes the inverse of the softplus function. - * - * @param y Input data. - * @return f^{-1}(y) - */ - static double Inv(const double y) - { - return y > 0 ? arma::trunc_log(arma::trunc_exp(y) - 1) : 0; - } - - /** - * Computes the inverse of the softplus function. - * - * @param y Input data. - * @param x The resulting inverse of the input data. - */ - template - static void Inv(const InputType& y, OutputType& x) - { - x = y; - x.transform([](double val) {return (Inv(val));} ); - } -}; // class SoftplusFunction - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/softsign_function.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/softsign_function.hpp deleted file mode 100644 index eb9db79b6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/softsign_function.hpp +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @file softsign_function.hpp - * @author Marcus Edel - * - * Definition and implementation of the softsign function as described by - * X. Glorot and Y. Bengio. - * - * For more information, see the following paper. - * - * @code - * @inproceedings{GlorotAISTATS2010, - * title={title={Understanding the difficulty of training deep feedforward - * neural networks}, - * author={Glorot, Xavier and Bengio, Yoshua}, - * booktitle={Proceedings of AISTATS 2010}, - * year={2010} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_SOFTSIGN_FUNCTION_HPP -#define MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_SOFTSIGN_FUNCTION_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The softsign function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \frac{x}{1 + |x|} \\ - * f'(x) &=& (1 - |x|)^2 \\ - * f(x) &=& \left\{ - * \begin{array}{lr} - * -\frac{y}{y-1} & : x > 0 \\ - * \frac{x}{1 + x} & : x \le 0 - * \end{array} - * \right. - * @f} - */ -class SoftsignFunction -{ - public: - /** - * Computes the softsign function. - * - * @param x Input data. - * @return f(x). - */ - static double Fn(const double x) - { - if (x < DBL_MAX) - return x > -DBL_MAX ? x / (1.0 + std::abs(x)) : -1.0; - return 1.0; - } - - /** - * Computes the softsign function. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const InputVecType& x, OutputVecType& y) - { - y = x; - - for (size_t i = 0; i < x.n_elem; i++) - y(i) = Fn(x(i)); - } - - /** - * Computes the first derivative of the softsign function. - * - * @param y Input data. - * @return f'(x) - */ - static double Deriv(const double y) - { - return std::pow(1.0 - std::abs(y), 2); - } - - /** - * Computes the first derivatives of the softsign function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - template - static void Deriv(const InputVecType& y, OutputVecType& x) - { - x = arma::pow(1.0 - arma::abs(y), 2); - } - - /** - * Computes the inverse of the softsign function. - * - * @param y Input data. - * @return f^{-1}(y) - */ - static double Inv(const double y) - { - if (y > 0) - return y < 1 ? -y / (y - 1) : DBL_MAX; - else - return y > -1 ? y / (1 + y) : -DBL_MAX; - } - - /** - * Computes the inverse of the softsign function. - * - * @param y Input data. - * @param x The resulting inverse of the input data. - */ - template - static void Inv(const InputVecType& y, OutputVecType& x) - { - x = y; - - for (size_t i = 0; i < y.n_elem; i++) - x(i) = Inv(y(i)); - } -}; // class SoftsignFunction - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/swish_function.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/swish_function.hpp deleted file mode 100644 index 68b831643..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/swish_function.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @file swish_function.hpp - * @author Vivek Pal - * - * Definition and implementation of the Swish function as described by - * Prajit Ramachandran, Barret Zoph & Quoc V. Le - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_SWISH_FUNCTION_HPP -#define MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_SWISH_FUNCTION_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The swish function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& x \cdot \sigma(x) \\ - * f'(x) &=& f(x) + \sigma(x) (1 - f(x)) \\ - * \sigma(x) &=& frac{1}{1 + e^{-x}} - * @f} - */ -class SwishFunction -{ - public: - /** - * Computes the swish function. - * - * @param x Input data. - * @return f(x). - */ - static double Fn(const double x) - { - return x / (1.0 + std::exp(-x)); - } - - /** - * Computes the swish function using a matrix as input. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const arma::Mat& x, arma::Mat& y) - { - y = x / (1.0 + arma::exp(-x)); - } - - /** - * Computes the swish function. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const InputVecType& x, OutputVecType& y) - { - y = x; - - for (size_t i = 0; i < x.n_elem; i++) - y(i) = Fn(x(i)); - } - - /** - * Computes the first derivative of the swish function. - * - * @param y Input data. - * @return f'(x) - */ - static double Deriv(const double y) - { - return y / (1 + std::exp(-y)) + (1 - y / (1 + std::exp(-y))) / - (1 + std::exp(-y)); - } - - /** - * Computes the first derivatives of the swish function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - template - static void Deriv(const InputVecType& y, OutputVecType& x) - { - x = y / (1 + arma::exp(-y)) + (1 - y / (1 + arma::exp(-y))) / - (1 + arma::exp(-y)); - } -}; // class SwishFunction - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/tanh_function.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/tanh_function.hpp deleted file mode 100644 index 63abf0f1e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/activation_functions/tanh_function.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file tanh_function.hpp - * @author Marcus Edel - * - * Definition and implementation of the Tangens Hyperbolic function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_TANH_FUNCTION_HPP -#define MLPACK_METHODS_ANN_ACTIVATION_FUNCTIONS_TANH_FUNCTION_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The tanh function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \frac{e^x - e^{-x}}{e^x + e^{-x}} \\ - * f'(x) &=& 1 - \tanh^2(x) \\ - * f^{-1}(x) &=& \arctan(x) - * @f} - */ -class TanhFunction -{ - public: - /** - * Computes the tanh function. - * - * @param x Input data. - * @return f(x). - */ - static double Fn(const double x) - { - return std::tanh(x); - } - - /** - * Computes the tanh function. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - static void Fn(const InputVecType& x, OutputVecType& y) - { - y = arma::tanh(x); - } - - /** - * Computes the first derivative of the tanh function. - * - * @param y Input data. - * @return f'(x) - */ - static double Deriv(const double y) - { - return 1 - std::pow(y, 2); - } - - /** - * Computes the first derivatives of the tanh function. - * - * @param y Input data. - * @param x The resulting derivatives. - */ - template - static void Deriv(const InputVecType& y, OutputVecType& x) - { - x = 1 - arma::pow(y, 2); - } - - /** - * Computes the inverse of the tanh function. - * - * @param y Input data. - * @return f^{-1}(x) - */ - static double Inv(const double y) - { - return std::atanh(y); - } - - /** - * Computes the inverse of the tanh function. - * - * @param y Input data. - * @param x The resulting inverse of the input data. - */ - template - static void Inv(const InputVecType& y, OutputVecType& x) - { - x = arma::atanh(y); - } -}; // class TanhFunction - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/add.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/add.hpp deleted file mode 100644 index fba73c124..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/add.hpp +++ /dev/null @@ -1,102 +0,0 @@ -/** - * @file add.hpp - * @author Konstantin Sidorov - * - * Definition of the AddTask class, which implements a generator of - * instances of binary addition task. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_AUGMENTED_TASKS_ADD_HPP -#define MLPACK_METHODS_AUGMENTED_TASKS_ADD_HPP - -#include -#include - -namespace mlpack { -namespace ann /* Artificial Neural Network */ { -namespace augmented /* Augmented neural network */ { -namespace tasks /* Task utilities for augmented */ { - -/** - * Generator of instances of the binary addition task. - * The parameters are: - * - macimum binary length; - * - * Every element of sequence is encoded as 1-dimensional vector - * (possible vector elements are {0, 1, 0.5} - - * the latter corresponds to '+' sign'). - * Generated datasets are compliant with mlpack format - - * every dataset element is shaped as a vector of - * length 3 * (sequence length), - * - * Example of generated dataset (binary length = 2): - * - Input sequence: [0,1,0,0,0,1,0,1,0,1,0,0] - * - Output sequences: [0,1,0,0,1,0] - * - */ -class AddTask -{ - public: - /** - * Creates an instance of the binary addition task. - * - * @param bitLen Maximum binary length of added numbers. - */ - AddTask(const size_t bitLen); - - /** - * Generate dataset of a given size. - * - * @param input The variable to store input sequences. - * @param labels The variable to store output sequences. - * @param batchSize The dataset size. - * @param fixedLength Flag that indicates whether - * the method should return sequences of even length. - */ - void Generate(arma::field& input, - arma::field& labels, - const size_t batchSize, - const bool fixedLength = false) const; - - /** - * Generate dataset of a given size and store it in - * arma::mat object. - * - * @param input The variable to store input sequences. - * @param labels The variable to store output sequences. - * @param batchSize The dataset size. - */ - void Generate(arma::mat& input, - arma::mat& labels, - const size_t batchSize) const; - - private: - // Maximum binary length of numbers. - size_t bitLen; - - /** - * Function for converting intermediate sequence representation - * to one-hot representation produced - * on the final stage of Generate function. - * - * @param input Reference parameter with intermediate representations, - * in which 0 and 1 corrrespond to the corresponding number bits, - * and 2 corresponds to `+` sign, which acts as a separator. - * @param output Reference parameter for storing final representations. - */ - void Binarize(const arma::field& input, - arma::field& output) const; -}; - -} // namespace tasks -} // namespace augmented -} // namespace ann -} // namespace mlpack - -#include "add_impl.hpp" -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/add_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/add_impl.hpp deleted file mode 100644 index d1284087b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/add_impl.hpp +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @file add_impl.hpp - * @author Konstantin Sidorov - * - * Implementation of AddTask class - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_AUGMENTED_TASKS_ADD_IMPL_HPP -#define MLPACK_METHODS_AUGMENTED_TASKS_ADD_IMPL_HPP - -#include "add.hpp" - -namespace mlpack { -namespace ann /* Artificial Neural Network */ { -namespace augmented /* Augmented neural network */ { -namespace tasks /* Task utilities for augmented */ { - -AddTask::AddTask(const size_t bitLen) : bitLen(bitLen) -{ - if (bitLen <= 0) - { - std::ostringstream oss; - oss << "AddTask::AddTask(): binary length (" << bitLen << ") " - << "is not positive!" - << std::endl; - throw std::invalid_argument(oss.str()); - } -} - -void AddTask::Generate(arma::field& input, - arma::field& labels, - const size_t batchSize, - bool fixedLength) const -{ - arma::field vecInput = arma::field(batchSize); - arma::field vecLabels = arma::field(batchSize); - size_t sizeA = bitLen, sizeB = bitLen; - for (size_t i = 0; i < batchSize; ++i) - { - if (!fixedLength) - { - arma::vec weights(bitLen - 1); - weights = arma::exp2(arma::linspace(1, bitLen - 1, bitLen - 1)); - - mlpack::distribution::DiscreteDistribution d(1); - // We have two binary numbers with exactly two digits (10 and 11). - // Increasing length by 1 double the number of valid numbers. - d.Probabilities(0) = arma::exp2( - arma::linspace(1, bitLen - 1, bitLen - 1)); - - sizeA = 2 + d.Random()(0); - sizeB = 2 + d.Random()(0); - } - // Construct sequence of the form - // (binary number with sizeA bits) + '+' + (binary number with sizeB bits). - vecInput(i) = arma::randi( - sizeA + sizeB + 1, arma::distr_param(0, 1)); - // Insert special value for '+' delimiter. - vecInput(i).at(sizeA) = 2; - - int valA = 0; - for (size_t k = 0; k < sizeA; ++k) - { - valA += static_cast(vecInput(i).at(k)) << k; - } - - int valB = 0; - for (size_t k = sizeA + 1; k < sizeA + 1 + sizeB; ++k) - { - valB += static_cast(vecInput(i).at(k)) << (k - sizeA - 1); - } - - int tot = valA + valB; - std::vector binarySeq; - while (tot > 0) - { - binarySeq.push_back(tot & 1); - tot >>= 1; - } - if (binarySeq.empty()) - { - if (valA + valB != 0) - { - std::ostringstream oss; - oss << "AddTask::Generate(): output sequence is empty " - << "but the target sum is not 0 (=" << valA + valB << ")" - << std::endl; - throw std::domain_error(oss.str()); - } - binarySeq.push_back(0); - } - vecLabels(i) = arma::colvec(binarySeq.size()); - for (size_t j = 0; j < binarySeq.size(); ++j) - { - vecLabels(i).at(j) = binarySeq[j]; - } - } - Binarize(vecInput, input); - Binarize(vecLabels, labels); - if (input.n_rows != labels.n_rows) - { - std::ostringstream oss; - oss << "AddTask::Generate(): sequences after application of " - << "Binarize() are not aligned (" - << input.n_rows << " and " << labels.n_rows << ")" - << std::endl; - throw std::logic_error(oss.str()); - } - for (size_t i = 0; i < input.n_rows; ++i) - { - labels.at(i).reshape(input.at(i).n_elem, 1); - } -} - -void AddTask::Generate(arma::mat& input, - arma::mat& labels, - const size_t batchSize) const -{ - arma::field fieldInput, fieldLabels; - Generate(fieldInput, fieldLabels, batchSize, true); - input.set_size(fieldInput(0).n_rows, batchSize); - labels.set_size(fieldLabels(0).n_rows, batchSize); - for (size_t i = 0; i < batchSize; ++i) - { - input.col(i) = fieldInput.at(i); - labels.col(i) = fieldLabels.at(i); - } -} - -void AddTask::Binarize(const arma::field& input, - arma::field& output) const -{ - output = arma::field(input.n_elem); - for (size_t i = 0; i < input.n_elem; ++i) - { - output.at(i) = arma::zeros(3, input.at(i).n_elem); - for (size_t j = 0; j < input.at(i).n_elem; ++j) - { - size_t val = input.at(i).at(j); - output.at(i).at(val, j) = 1; - } - output.at(i).reshape(output.at(i).n_elem, 1); - } -} - - -} // namespace tasks -} // namespace augmented -} // namespace ann -} // namespace mlpack -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/copy.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/copy.hpp deleted file mode 100644 index 05efdbbfd..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/copy.hpp +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @file copy.hpp - * @author Konstantin Sidorov - * - * Definition of the CopyTask class, which implements a generator of - * instances of sequence copy task. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_AUGMENTED_TASKS_COPY_HPP -#define MLPACK_METHODS_AUGMENTED_TASKS_COPY_HPP - -#include -#include - -namespace mlpack { -namespace ann /* Artificial Neural Network */ { -namespace augmented /* Augmented neural network */ { -namespace tasks /* Task utilities for augmented */ { - -/** - * Generator of instances of the binary sequence copy task. - * The parameters are: - * - maximum sequence length; - * - number of sequence repetitions. - * - * Input/output sequences are aligned to have the same length: - * input sequence is padded with zeros from the right end, - * output sequence is padded with zeros from the left end. - * The sequences are formed of 2-dimensional vectors - * of the format [sequence element, input flag], - * where input flag = 0 iff first vector element is a sequence element. - * - * Generated datasets are compliant with mlpack format - - * every dataset element is shaped as a vector of - * length (elem-length) * (input sequence length + target sequence length), - * where elem-lemgth is 2 for input sequences and 1 for output sequences. - * - * Example of generated dataset (sequence length = 3, repetition count = 2): - * - Input sequence: [1,0,0,0,1,0,0,1,0,1,0,1,0,1,0,1,0,1] - * - Output sequences: [0,0,0,1,0,1,1,0,1] - * - */ -class CopyTask -{ - public: - /** - * Creates an instance of the sequence copy task. - * - * @param maxLength Maximum length of sequence - * that has to be repeated by model. - * @param nRepeats Number of repeates required to solve the task. - * @param addSeparator Flag indicating whether generator - * should emit separating symbol after input sequence. - */ - CopyTask(const size_t maxLength, - const size_t nRepeats, - const bool addSeparator = false); - /** - * Generate dataset of a given size. - * - * @param input The variable to store input sequences. - * @param labels The variable to store output sequences. - * @param batchSize The dataset size. - */ - void Generate(arma::field& input, - arma::field& labels, - const size_t batchSize, - bool fixedLength = false) const; - - /** - * Generate dataset of a given size and store it in - * arma::mat object. - * - * @param input The variable to store input sequences. - * @param labels The variable to store output sequences. - * @param batchSize The dataset size. - */ - void Generate(arma::mat& input, - arma::mat& labels, - const size_t batchSize) const; - - private: - // Maximum length of a sequence. - size_t maxLength; - // Number of repeats the model has to perform to complete the task. - size_t nRepeats; - // Flag indicating whether generator should produce - // separator as part of the sequence - bool addSeparator; -}; - -} // namespace tasks -} // namespace augmented -} // namespace ann -} // namespace mlpack - -#include "copy_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/copy_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/copy_impl.hpp deleted file mode 100644 index f427388a6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/copy_impl.hpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @file copy_impl.hpp - * @author Konstantin Sidorov - * - * Implementation of CopyTask class - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AUGMENTED_TASKS_COPY_IMPL_HPP -#define MLPACK_METHODS_AUGMENTED_TASKS_COPY_IMPL_HPP - -// In case it hasn't been included yet. -#include "copy.hpp" - -namespace mlpack { -namespace ann /* Artificial Neural Network */ { -namespace augmented /* Augmented neural network */ { -namespace tasks /* Task utilities for augmented */ { - -CopyTask::CopyTask(const size_t maxLength, - const size_t nRepeats, - const bool addSeparator) : - maxLength(maxLength), - nRepeats(nRepeats), - addSeparator(addSeparator) -{ - if (maxLength <= 1) - { - std::ostringstream oss; - oss << "CopyTask::CopyTask(): maximum sequence length (" - << maxLength << ") " - << "should be at least 2!" - << std::endl; - throw std::invalid_argument(oss.str()); - } - if (nRepeats <= 0) - { - std::ostringstream oss; - oss << "CopyTask::CopyTask(): repetition count (" << nRepeats << ") " - << "is not positive!" - << std::endl; - throw std::invalid_argument(oss.str()); - } - // Just storing task-specific parameters. -} - -void CopyTask::Generate(arma::field& input, - arma::field& labels, - const size_t batchSize, - bool fixedLength) const -{ - input = arma::field(batchSize); - labels = arma::field(batchSize); - size_t size = maxLength; - for (size_t i = 0; i < batchSize; ++i) - { - if (!fixedLength) - { - arma::vec weights(maxLength - 1); - - mlpack::distribution::DiscreteDistribution d(1); - // We have two binary numbers with exactly two digits (10 and 11). - // Increasing length by 1 double the number of valid numbers. - d.Probabilities(0) = - arma::exp2(arma::linspace(1, maxLength - 1, maxLength - 1)); - - size = 2 + d.Random()(0); - } - arma::colvec vecInput = arma::randi( - size, arma::distr_param(0, 1)); - arma::colvec vecLabel = arma::conv_to::from( - arma::repmat(vecInput, nRepeats, 1)); - size_t totSize = vecInput.n_elem + addSeparator + vecLabel.n_elem; - input(i) = arma::zeros(totSize, 2); - input(i).col(0).rows(0, vecInput.n_elem - 1) = - vecInput; - if (addSeparator) - input(i).at(vecInput.n_elem, 0) = 0.5; - input(i).col(1).rows(addSeparator + vecInput.n_elem, totSize - 1) = - arma::ones(totSize-vecInput.n_elem - addSeparator); - input(i) = input(i).t(); - input(i).reshape(input(i).n_elem, 1); - labels(i) = arma::zeros(totSize, 1); - labels(i).col(0).rows(addSeparator + vecInput.n_elem, totSize - 1) = - vecLabel; - } -} - -void CopyTask::Generate(arma::mat& input, - arma::mat& labels, - const size_t batchSize) const -{ - arma::field fieldInput, fieldLabels; - Generate(fieldInput, fieldLabels, batchSize, true); - size_t cols = batchSize; - input = arma::zeros(fieldInput(0).n_rows, cols); - labels = arma::zeros(fieldLabels(0).n_rows, cols); - for (size_t i = 0; i < cols; ++i) - { - input.col(i) = fieldInput.at(i); - labels.col(i) = fieldLabels.at(i); - } -} - - -} // namespace tasks -} // namespace augmented -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/score.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/score.hpp deleted file mode 100644 index 7138b0ed3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/score.hpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @file score.hpp - * @author Konstantin Sidorov - * - * Definition of scoring functions for sequence prediction problems. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_AUGMENTED_TASKS_SCORE_HPP -#define MLPACK_METHODS_AUGMENTED_TASKS_SCORE_HPP - -#include - -namespace mlpack { -namespace ann /* Artificial Neural Network */ { -namespace augmented /* Augmented neural network */ { -namespace scorers /* Scoring utilities for augmented */ { - -/** -* Function that computes the sequences precision -* (number of correct sequences / number of sequences) -* of model's answer against ground truth answer. -* -* @param trueOutputs Ground truth sequences. -* @param predOutputs Sequences predicted by model. -* @param tol Minimum absolute difference value -* which is considered as a model failure. -*/ -template -double SequencePrecision(arma::field trueOutputs, - arma::field predOutputs, - double tol = 1e-4); - -} // namespace scorers -} // namespace augmented -} // namespace ann -} // namespace mlpack - -#include "score_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/score_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/score_impl.hpp deleted file mode 100644 index 528194a0b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/score_impl.hpp +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @file score_impl.hpp - * @author Konstantin Sidorov - * - * Implementation of scoring functions - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AUGMENTED_TASKS_SCORE_IMPL_HPP -#define MLPACK_METHODS_AUGMENTED_TASKS_SCORE_IMPL_HPP - -// In case it hasn't been included yet. -#include "score.hpp" - -namespace mlpack { -namespace ann /* Artificial Neural Network */ { -namespace augmented /* Augmented neural network */ { -namespace scorers /* Scoring utilities for augmented */ { - -template -double SequencePrecision(arma::field trueOutputs, - arma::field predOutputs, - double tol) -{ - double score = 0; - size_t testSize = trueOutputs.n_elem; - if (trueOutputs.n_elem != predOutputs.n_elem) - { - std::ostringstream oss; - oss << "SequencePrecision(): number of predicted sequences (" - << predOutputs.n_elem << ") should be equal to the number " - << "of ground-truth sequences (" - << trueOutputs.n_elem << ")" - << std::endl; - throw std::invalid_argument(oss.str()); - } - - for (size_t i = 0; i < testSize; i++) - { - arma::vec delta = arma::vectorise(arma::abs( - trueOutputs.at(i) - predOutputs.at(i))); - double maxDelta = arma::max(delta); - if (maxDelta < tol) - { - score++; - } - } - score /= testSize; - return score; -} - -} // namespace scorers -} // namespace augmented -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/sort.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/sort.hpp deleted file mode 100644 index 0345444a9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/sort.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @file sort.hpp - * @author Konstantin Sidorov - * - * Definition of the SortTask class, which implements a generator of - * instances of sequence sort task. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_AUGMENTED_TASKS_SORT_HPP -#define MLPACK_METHODS_AUGMENTED_TASKS_SORT_HPP - -#include - -namespace mlpack { -namespace ann /* Artificial Neural Network */ { -namespace augmented /* Augmented neural network */ { -namespace tasks /* Task utilities for augmented */ { - -/** - * Generator of instances of the sequence sort task. - * The parameters are: - * - maximum sequence length; - * - binary length of sequence elements. - * - * Generated datasets are compliant with mlpack format - - * every dataset element is shaped as a vector of - * length (binary length) * (sequence length). - * - * Example of generated dataset (sequence length = 3, binary length = 2): - * - Input sequences: [1,1,0,0,0,1] - * (three numbers in the sequence are 11, 00, and 01) - * - Output sequences: [0,0,0,1,1,1] - * (00, 01, 11 - reordering of the numbers above in the ascending order) - * - */ -class SortTask -{ - public: - /** - * Creates an instance of the sequence sort task. - * - * @param maxLength Maximum length of the number sequence. - * @param bitLen Binary length of sorted numbers. - * @param addSeparator Flag indicating whether generator - * should emit separating symbol after input sequence. - */ - SortTask(const size_t maxLength, - const size_t bitLen, - bool addSeparator = false); - - /** - * Generate dataset of a given size. - * - * @param input The variable to store input sequences. - * @param labels The variable to store output sequences. - * @param batchSize The dataset size. - * @param fixedLength Flag indicating whether generator - * should emit sequences of pairwise equal length. - */ - void Generate(arma::field& input, - arma::field& labels, - const size_t batchSize, - bool fixedLength = false) const; - /** - * Generate dataset of a given size and store it in - * arma::mat object. - * - * @param input The variable to store input sequences. - * @param labels The variable to store output sequences. - * @param batchSize The dataset size. - */ - void Generate(arma::mat& input, - arma::mat& labels, - const size_t batchSize) const; - - private: - // Maximum length of the sequence. - size_t maxLength; - // Binary length of sorted numbers. - size_t bitLen; - // Flag indicating whether generator should produce - // separator as part of the sequence - bool addSeparator; -}; - -} // namespace tasks -} // namespace augmented -} // namespace ann -} // namespace mlpack - -#include "sort_impl.hpp" -#endif - - - diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/sort_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/sort_impl.hpp deleted file mode 100644 index df4989155..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/augmented/tasks/sort_impl.hpp +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @file sort_impl.hpp - * @author Konstantin Sidorov - * - * Implementation of SortTask class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_AUGMENTED_TASKS_SORT_IMPL_HPP -#define MLPACK_METHODS_AUGMENTED_TASKS_SORT_IMPL_HPP - -#include "sort.hpp" - -namespace mlpack { -namespace ann /* Artificial Neural Network */ { -namespace augmented /* Augmented neural network */ { -namespace tasks /* Task utilities for augmented */ { - -SortTask::SortTask(const size_t maxLength, - const size_t bitLen, - bool addSeparator) - : maxLength(maxLength), bitLen(bitLen), addSeparator(addSeparator) -{ - if (maxLength <= 1) - { - std::ostringstream oss; - oss << "SortTask::SortTask(): maximum sequence length (" - << maxLength << ") " - << "should be at least 2!" - << std::endl; - throw std::invalid_argument(oss.str()); - } - if (bitLen <= 0) - { - std::ostringstream oss; - oss << "SortTask::SortTask(): binary length (" << bitLen << ") " - << "is not positive!" - << std::endl; - throw std::invalid_argument(oss.str()); - } -} - -void SortTask::Generate(arma::field& input, - arma::field& labels, - const size_t batchSize, - bool fixedLength) const -{ - input = arma::field(batchSize); - labels = arma::field(batchSize); - size_t size = maxLength; - for (size_t i = 0; i < batchSize; ++i) - { - if (!fixedLength) - { - // Generate random uniform length from [2..maxLength]. - size = mlpack::math::RandInt(2, maxLength+1); - } - input(i) = arma::randi(bitLen, size, arma::distr_param(0, 1)); - arma::mat itemAns(bitLen, size); - arma::colvec vals(size); - for (size_t j = 0; j < size; ++j) - { - int val = 0; - for (size_t k = 0; k < bitLen; ++k) - { - val <<= 1; - val += input(i).at(k, j); - } - vals[j] = val; - } - arma::uvec indices = arma::sort_index(vals); - for (size_t j = 0; j < size; ++j) - { - itemAns.col(j) = input(i).col(indices.at(j)); - } - labels(i) = itemAns; - input(i).reshape(input(i).n_elem, 1); - if (addSeparator) - { - arma::mat sepInput = arma::zeros(input(i).n_elem + size, 1); - size_t ptr = 0, origPtr = 0; - for (size_t j = 0; j < size; ++j) - { - sepInput.rows(ptr, ptr + bitLen - 1) = - input(i).rows(origPtr, origPtr + bitLen - 1); - ptr += bitLen; - origPtr += bitLen; - sepInput.at(ptr, 0) = 0.5; - ++ptr; - } - input(i) = sepInput; - } - labels(i).reshape(labels(i).n_elem, 1); - } -} - -void SortTask::Generate(arma::mat& input, - arma::mat& labels, - const size_t batchSize) const -{ - arma::field fieldInput, fieldLabels; - Generate(fieldInput, fieldLabels, batchSize, true); - size_t inputRows = fieldInput(0).n_rows; - size_t labelRows = fieldLabels(0).n_rows; - size_t cols = batchSize; - input = arma::zeros(inputRows, cols); - labels = arma::zeros(labelRows, cols); - for (size_t i = 0; i < cols; ++i) - { - input.col(i) = fieldInput.at(i); - labels.col(i) = fieldLabels.at(i); - } -} - -} // namespace tasks -} // namespace augmented -} // namespace ann -} // namespace mlpack -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/border_modes.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/border_modes.hpp deleted file mode 100644 index b9e6b1e43..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/border_modes.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * @file border_modes.hpp - * @author Marcus Edel - * - * This file provides the border modes that can be used to compute different - * convolutions. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_CONVOLUTION_RULES_BORDER_MODES_HPP -#define MLPACK_METHODS_ANN_CONVOLUTION_RULES_BORDER_MODES_HPP - -namespace mlpack { -namespace ann { - -/* - * The FullConvolution class represents the full two-dimensional convolution. - */ -class FullConvolution { /* Nothing to do here */ }; - -/* - * The ValidConvolution represents only those parts of the convolution that are - * computed without the zero-padded edges. - */ -class ValidConvolution { /* Nothing to do here */ }; - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/fft_convolution.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/fft_convolution.hpp deleted file mode 100644 index 777fa2632..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/fft_convolution.hpp +++ /dev/null @@ -1,217 +0,0 @@ -/** - * @file fft_convolution.hpp - * @author Shangtong Zhang - * @author Marcus Edel - * - * Implementation of the convolution through fft. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_CONVOLUTION_RULES_FFT_CONVOLUTION_HPP -#define MLPACK_METHODS_ANN_CONVOLUTION_RULES_FFT_CONVOLUTION_HPP - -#include -#include "border_modes.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Computes the two-dimensional convolution through fft. This class allows - * specification of the type of the border type. The convolution can be - * computed with the valid border type or the full border type (default). - * - * FullConvolution: returns the full two-dimensional convolution. - * ValidConvolution: returns only those parts of the convolution that are - * computed without the zero-padded edges. - * - * @tparam BorderMode Type of the border mode (FullConvolution or - * ValidConvolution). - * @tparam padLastDim Pad the last dimension of the input to to turn it from - * odd to even. - */ -template -class FFTConvolution -{ - public: - /* - * Perform a convolution through fft (valid mode). This method only supports - * input which is even on the last dimension. In case of an odd input width, a - * user can manually pad the input or specify the padLastDim parameter which - * takes care of the padding. The filter instead can have any size. When using - * the valid mode the filter has to be smaller than the input. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - */ - template - static typename std::enable_if< - std::is_same::value, void>::type - Convolution(const arma::Mat& input, - const arma::Mat& filter, - arma::Mat& output) - { - arma::Mat inputPadded = input; - arma::Mat filterPadded = filter; - - if (padLastDim) - inputPadded.resize(inputPadded.n_rows, inputPadded.n_cols + 1); - - // Pad filter and input to the output shape. - filterPadded.resize(inputPadded.n_rows, inputPadded.n_cols); - - arma::Mat temp = arma::real(ifft2(arma::fft2(inputPadded) % arma::fft2( - filterPadded))); - - // Extract the region of interest. We don't need to handle the padLastDim in - // a special way we just cut it out from the output matrix. - output = temp.submat(filter.n_rows - 1, filter.n_cols - 1, - input.n_rows - 1, input.n_cols - 1); - } - - /* - * Perform a convolution through fft (full mode). This method only supports - * input which is even on the last dimension. In case of an odd input width, a - * user can manually pad the input or specify the padLastDim parameter which - * takes care of the padding. The filter instead can have any size. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - */ - template - static typename std::enable_if< - std::is_same::value, void>::type - Convolution(const arma::Mat& input, - const arma::Mat& filter, - arma::Mat& output) - { - // In case of the full convolution outputRows and outputCols doesn't - // represent the true output size when the padLastDim parameter is set, - // instead it's the working size. - const size_t outputRows = input.n_rows + 2 * (filter.n_rows - 1); - size_t outputCols = input.n_cols + 2 * (filter.n_cols - 1); - - if (padLastDim) - outputCols++; - - // Pad filter and input to the working output shape. - arma::Mat inputPadded = arma::zeros >(outputRows, - outputCols); - inputPadded.submat(filter.n_rows - 1, filter.n_cols - 1, - filter.n_rows - 1 + input.n_rows - 1, - filter.n_cols - 1 + input.n_cols - 1) = input; - - arma::Mat filterPadded = filter; - filterPadded.resize(outputRows, outputCols); - - // Perform FFT and IFFT - arma::Mat temp = arma::real(ifft2(arma::fft2(inputPadded) % arma::fft2( - filterPadded))); - - // Extract the region of interest. We don't need to handle the padLastDim - // parameter in a special way we just cut it out from the output matrix. - output = temp.submat(filter.n_rows - 1, filter.n_cols - 1, - 2 * (filter.n_rows - 1) + input.n_rows - 1, - 2 * (filter.n_cols - 1) + input.n_cols - 1); - } - - /* - * Perform a convolution through fft using 3rd order tensors. This method only - * supports input which is even on the last dimension. In case of an odd input - * width, a user can manually pad the input or specify the padLastDim - * parameter which takes care of the padding. The filter instead can have any - * size. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - */ - template - static void Convolution(const arma::Cube& input, - const arma::Cube& filter, - arma::Cube& output) - { - arma::Mat convOutput; - FFTConvolution::Convolution(input.slice(0), filter.slice(0), - convOutput); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - input.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < input.n_slices; i++) - { - FFTConvolution::Convolution(input.slice(i), filter.slice(i), - output.slice(i)); - } - } - - /* - * Perform a convolution through fft using dense matrix as input and a 3rd - * order tensors as filter and output. This method only supports input which - * is even on the last dimension. In case of an odd input width, a user can - * manually pad the input or specify the padLastDim parameter which takes care - * of the padding. The filter instead can have any size. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - */ - template - static void Convolution(const arma::Mat& input, - const arma::Cube& filter, - arma::Cube& output) - { - arma::Mat convOutput; - FFTConvolution::Convolution(input, filter.slice(0), - convOutput); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - filter.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < filter.n_slices; i++) - { - FFTConvolution::Convolution(input, filter.slice(i), - output.slice(i)); - } - } - - /* - * Perform a convolution using a 3rd order tensors as input and output and a - * dense matrix as filter. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - */ - template - static void Convolution(const arma::Cube& input, - const arma::Mat& filter, - arma::Cube& output) - { - arma::Mat convOutput; - FFTConvolution::Convolution(input.slice(0), filter, - convOutput); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - input.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < input.n_slices; i++) - { - FFTConvolution::Convolution(input.slice(i), filter, - output.slice(i)); - } - } -}; // class FFTConvolution - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/naive_convolution.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/naive_convolution.hpp deleted file mode 100644 index 1352883c8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/naive_convolution.hpp +++ /dev/null @@ -1,250 +0,0 @@ -/** - * @file naive_convolution.hpp - * @author Shangtong Zhang - * @author Marcus Edel - * - * Implementation of the convolution. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_CONVOLUTION_RULES_NAIVE_CONVOLUTION_HPP -#define MLPACK_METHODS_ANN_CONVOLUTION_RULES_NAIVE_CONVOLUTION_HPP - -#include -#include "border_modes.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Computes the two-dimensional convolution. This class allows specification of - * the type of the border type. The convolution can be compute with the valid - * border type of the full border type (default). - * - * FullConvolution: returns the full two-dimensional convolution. - * ValidConvolution: returns only those parts of the convolution that are - * computed without the zero-padded edges. - * - * @tparam BorderMode Type of the border mode (FullConvolution or - * ValidConvolution). - */ -template -class NaiveConvolution -{ - public: - /* - * Perform a convolution (valid mode). - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - * @param dilationW The dilation factor in x direction. - * @param dilationH The dilation factor in y direction. - */ - template - static typename std::enable_if< - std::is_same::value, void>::type - Convolution(const arma::Mat& input, - const arma::Mat& filter, - arma::Mat& output, - const size_t dW = 1, - const size_t dH = 1, - const size_t dilationW = 1, - const size_t dilationH = 1) - { - output = arma::zeros >( - (input.n_rows - (filter.n_rows - 1) * dilationW - 1) / dW + 1, - (input.n_cols - (filter.n_cols - 1) * dilationH - 1) / dH + 1); - - // It seems to be about 3.5 times faster to use pointers instead of - // filter(ki, kj) * input(leftInput + ki, topInput + kj) and output(i, j). - eT* outputPtr = output.memptr(); - - for (size_t j = 0; j < output.n_cols; ++j) - { - for (size_t i = 0; i < output.n_rows; ++i, outputPtr++) - { - const eT* kernelPtr = filter.memptr(); - for (size_t kj = 0; kj < filter.n_cols; ++kj) - { - const eT* inputPtr = input.colptr(kj * dilationW + j * dW) + i * dH; - for (size_t ki = 0; ki < filter.n_rows; ++ki, ++kernelPtr, - inputPtr += dilationH) - *outputPtr += *kernelPtr * (*inputPtr); - } - } - } - } - - /* - * Perform a convolution (full mode). - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - * @param dilationW The dilation factor in x direction. - * @param dilationH The dilation factor in y direction. - */ - template - static typename std::enable_if< - std::is_same::value, void>::type - Convolution(const arma::Mat& input, - const arma::Mat& filter, - arma::Mat& output, - const size_t dW = 1, - const size_t dH = 1, - const size_t dilationW = 1, - const size_t dilationH = 1) - { - size_t outputRows = (input.n_rows - 1) * dW + 2 * (filter.n_rows - 1) - * dilationW + 1; - size_t outputCols = (input.n_cols - 1) * dH + 2 * (filter.n_cols - 1) - * dilationH + 1; - - for (size_t i = 0; i < dW; i++) - { - if (((((i + outputRows - 2 * (filter.n_rows - 1) * dilationW - 1) % dW) - + dW) % dW) == i){ - outputRows += i; - break; - } - } - for (size_t i = 0; i < dH; i++) - { - if (((((i + outputCols - 2 * (filter.n_cols - 1) * dilationH - 1) % dH) - + dH) % dH) == i){ - outputCols += i; - break; - } - } - - // Pad filter and input to the working output shape. - arma::Mat inputPadded = arma::zeros >(outputRows, - outputCols); - inputPadded.submat((filter.n_rows - 1) * dilationW, (filter.n_cols - 1) - * dilationH, (filter.n_rows - 1) * dilationW + input.n_rows - 1, - (filter.n_cols - 1) * dilationH + input.n_cols - 1) = input; - - NaiveConvolution::Convolution(inputPadded, filter, - output, 1, 1, dilationW, dilationH); - } - - /* - * Perform a convolution using 3rd order tensors. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - * @param dilationW The dilation factor in x direction. - * @param dilationH The dilation factor in y direction. - */ - template - static void Convolution(const arma::Cube& input, - const arma::Cube& filter, - arma::Cube& output, - const size_t dW = 1, - const size_t dH = 1, - const size_t dilationW = 1, - const size_t dilationH = 1) - { - arma::Mat convOutput; - NaiveConvolution::Convolution(input.slice(0), filter.slice(0), - convOutput, dW, dH, dilationW, dilationH); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - input.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < input.n_slices; i++) - { - NaiveConvolution::Convolution(input.slice(i), filter.slice(i), - output.slice(i), dW, dH, dilationW, dilationH); - } - } - - /* - * Perform a convolution using dense matrix as input and a 3rd order tensors - * as filter and output. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - * @param dilationW The dilation factor in x direction. - * @param dilationH The dilation factor in y direction. - */ - template - static void Convolution(const arma::Mat& input, - const arma::Cube& filter, - arma::Cube& output, - const size_t dW = 1, - const size_t dH = 1, - const size_t dilationW = 1, - const size_t dilationH = 1) - { - arma::Mat convOutput; - NaiveConvolution::Convolution(input, filter.slice(0), - convOutput, dW, dH, dilationW, dilationH); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - filter.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < filter.n_slices; i++) - { - NaiveConvolution::Convolution(input, filter.slice(i), - output.slice(i), dW, dH, dilationW, dilationH); - } - } - - /* - * Perform a convolution using a 3rd order tensors as input and output and a - * dense matrix as filter. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the convolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - * @param dilationW The dilation factor in x direction. - * @param dilationH The dilation factor in y direction. - */ - template - static void Convolution(const arma::Cube& input, - const arma::Mat& filter, - arma::Cube& output, - const size_t dW = 1, - const size_t dH = 1, - const size_t dilationW = 1, - const size_t dilationH = 1) - { - arma::Mat convOutput; - NaiveConvolution::Convolution(input.slice(0), filter, - convOutput, dW, dH, dilationW, dilationH); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - input.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < input.n_slices; i++) - { - NaiveConvolution::Convolution(input.slice(i), filter, - output.slice(i), dW, dH, dilationW, dilationH); - } - } -}; // class NaiveConvolution - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/svd_convolution.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/svd_convolution.hpp deleted file mode 100644 index 8ed0a9c41..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/convolution_rules/svd_convolution.hpp +++ /dev/null @@ -1,203 +0,0 @@ -/** - * @file svd_convolution.hpp - * @author Marcus Edel - * - * Implementation of the convolution using the singular value decomposition to - * speed up the computation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_CONVOLUTION_RULES_SVD_CONVOLUTION_HPP -#define MLPACK_METHODS_ANN_CONVOLUTION_RULES_SVD_CONVOLUTION_HPP - -#include -#include "border_modes.hpp" -#include "fft_convolution.hpp" -#include "naive_convolution.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Computes the two-dimensional convolution using singular value decomposition. - * This class allows specification of the type of the border type. The - * convolution can be computed with the valid border type of the full border - * type (default). - * - * FullConvolution: returns the full two-dimensional convolution. - * ValidConvolution: returns only those parts of the convolution that are - * computed without the zero-padded edges. - * - * @tparam BorderMode Type of the border mode (FullConvolution or - * ValidConvolution). - */ -template -class SVDConvolution -{ - public: - /* - * Perform a convolution (valid or full mode) using singular value - * decomposition. By using singular value decomposition of the filter matrix - * the convolution can be expressed as a sum of outer products. Each product - * can be computed efficiently as convolution with a row and a column vector. - * The individual convolutions are computed with the naive implementation - * which is fast if the filter is low-dimensional. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the conolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - */ - template - static void Convolution(const arma::Mat& input, - const arma::Mat& filter, - arma::Mat& output) - { - // Use the naive convolution in case the filter isn't two dimensional or the - // filter is bigger than the input. - if (filter.n_rows > input.n_rows || filter.n_cols > input.n_cols || - filter.n_rows == 1 || filter.n_cols == 1) - { - NaiveConvolution::Convolution(input, filter, output); - } - else - { - arma::Mat U, V, subOutput; - arma::Col s; - - arma::svd_econ(U, s, V, filter); - - // Rank approximation using the singular values calculated with singular - // value decomposition of dense filter matrix. - const size_t rank = arma::sum(s > (s.n_elem * arma::max(s) * - arma::datum::eps)); - - // Test for separability based on the rank of the kernel and take - // advantage of the low rank. - if (rank * (filter.n_rows + filter.n_cols) < filter.n_elem) - { - arma::Mat subFilter = V.unsafe_col(0) * s(0); - NaiveConvolution::Convolution(input, subFilter, subOutput); - - subOutput = subOutput.t(); - NaiveConvolution::Convolution(subOutput, U.unsafe_col(0), - output); - - arma::Mat temp; - for (size_t r = 1; r < rank; r++) - { - subFilter = V.unsafe_col(r) * s(r); - NaiveConvolution::Convolution(input, subFilter, - subOutput); - - subOutput = subOutput.t(); - NaiveConvolution::Convolution(subOutput, U.unsafe_col(r), - temp); - output += temp; - } - - output = output.t(); - } - else - { - FFTConvolution::Convolution(input, filter, output); - } - } - } - - /* - * Perform a convolution using 3rd order tensors. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the conolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - */ - template - static void Convolution(const arma::Cube& input, - const arma::Cube& filter, - arma::Cube& output) - { - arma::Mat convOutput; - SVDConvolution::Convolution(input.slice(0), filter.slice(0), - convOutput); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - input.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < input.n_slices; i++) - { - SVDConvolution::Convolution(input.slice(i), filter.slice(i), - output.slice(i)); - } - } - - /* - * Perform a convolution using dense matrix as input and a 3rd order tensors - * as filter and output. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the conolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - */ - template - static void Convolution(const arma::Mat& input, - const arma::Cube& filter, - arma::Cube& output) - { - arma::Mat convOutput; - SVDConvolution::Convolution(input, filter.slice(0), convOutput); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - filter.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < filter.n_slices; i++) - { - SVDConvolution::Convolution(input, filter.slice(i), - output.slice(i)); - } - } - - /* - * Perform a convolution using a 3rd order tensors as input and output and a - * dense matrix as filter. - * - * @param input Input used to perform the convolution. - * @param filter Filter used to perform the conolution. - * @param output Output data that contains the results of the convolution. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - */ - template - static void Convolution(const arma::Cube& input, - const arma::Mat& filter, - arma::Cube& output) - { - arma::Mat convOutput; - SVDConvolution::Convolution(input.slice(0), filter, convOutput); - - output = arma::Cube(convOutput.n_rows, convOutput.n_cols, - input.n_slices); - output.slice(0) = convOutput; - - for (size_t i = 1; i < input.n_slices; i++) - { - SVDConvolution::Convolution(input.slice(i), filter, - output.slice(i)); - } - } -}; // class SVDConvolution - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/ffn.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/ffn.hpp deleted file mode 100644 index e6088a1c5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/ffn.hpp +++ /dev/null @@ -1,486 +0,0 @@ -/** - * @file ffn.hpp - * @author Marcus Edel - * @author Shangtong Zhang - * - * Definition of the FFN class, which implements feed forward neural networks. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_FFN_HPP -#define MLPACK_METHODS_ANN_FFN_HPP - -#include - -#include "visitor/delete_visitor.hpp" -#include "visitor/delta_visitor.hpp" -#include "visitor/output_height_visitor.hpp" -#include "visitor/output_parameter_visitor.hpp" -#include "visitor/output_width_visitor.hpp" -#include "visitor/reset_visitor.hpp" -#include "visitor/weight_size_visitor.hpp" -#include "visitor/copy_visitor.hpp" - -#include "init_rules/network_init.hpp" - -#include -#include -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of a standard feed forward network. - * - * @tparam OutputLayerType The output layer type used to evaluate the network. - * @tparam InitializationRuleType Rule used to initialize the weight matrix. - * @tparam CustomLayers Any set of custom layers that could be a part of the - * feed forward network. - */ -template< - typename OutputLayerType = NegativeLogLikelihood<>, - typename InitializationRuleType = RandomInitialization, - typename... CustomLayers -> -class FFN -{ - public: - //! Convenience typedef for the internal model construction. - using NetworkType = FFN; - - /** - * Create the FFN object. - * - * Optionally, specify which initialize rule and performance function should - * be used. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * @param outputLayer Output layer used to evaluate the network. - * @param initializeRule Optional instantiated InitializationRule object - * for initializing the network parameter. - */ - FFN(OutputLayerType outputLayer = OutputLayerType(), - InitializationRuleType initializeRule = InitializationRuleType()); - - //! Copy constructor. - FFN(const FFN&); - - //! Move constructor. - FFN(FFN&&); - - //! Copy/move assignment operator. - FFN& operator = (FFN); - - //! Destructor to release allocated memory. - ~FFN(); - - /** - * Train the feedforward network on the given input data using the given - * optimizer. - * - * This will use the existing model parameters as a starting point for the - * optimization. If this is not what you want, then you should access the - * parameters vector directly with Parameters() and modify it as desired. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * @tparam OptimizerType Type of optimizer to use to train the model. - * @param predictors Input training variables. - * @param responses Outputs results from input training variables. - * @param optimizer Instantiated optimizer used to train the model. - */ - template - void Train(arma::mat predictors, - arma::mat responses, - OptimizerType& optimizer); - - /** - * Train the feedforward network on the given input data. By default, the - * RMSProp optimization algorithm is used, but others can be specified - * (such as mlpack::optimization::SGD). - * - * This will use the existing model parameters as a starting point for the - * optimization. If this is not what you want, then you should access the - * parameters vector directly with Parameters() and modify it as desired. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * @tparam OptimizerType Type of optimizer to use to train the model. - * @param predictors Input training variables. - * @param responses Outputs results from input training variables. - */ - template - void Train(arma::mat predictors, arma::mat responses); - - /** - * Predict the responses to a given set of predictors. The responses will - * reflect the output of the given output layer as returned by the - * output layer function. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * @param predictors Input predictors. - * @param results Matrix to put output predictions of responses into. - */ - void Predict(arma::mat predictors, arma::mat& results); - - /** - * Evaluate the feedforward network with the given parameters. This function - * is usually called by the optimizer to train the model. - * - * @param parameters Matrix model parameters. - * @param deterministic Whether or not to train or test the model. Note some - * layer act differently in training or testing mode. - */ - double Evaluate(const arma::mat& parameters); - - /** - * Evaluate the feedforward network with the given parameters, but using only - * a number of data points. This is useful for optimizers such as SGD, which - * require a separable objective function. - * - * @param parameters Matrix model parameters. - * @param begin Index of the starting point to use for objective function - * evaluation. - * @param batchSize Number of points to be passed at a time to use for - * objective function evaluation. - * @param deterministic Whether or not to train or test the model. Note some - * layer act differently in training or testing mode. - */ - double Evaluate(const arma::mat& parameters, - const size_t begin, - const size_t batchSize, - const bool deterministic); - - /** - * Evaluate the feedforward network with the given parameters, but using only - * a number of data points. This is useful for optimizers such as SGD, which - * require a separable objective function. This just calls the overload of - * Evaluate() with deterministic = true. - * - * @param parameters Matrix model parameters. - * @param begin Index of the starting point to use for objective function - * evaluation. - * @param batchSize Number of points to be passed at a time to use for - * objective function evaluation. - */ - double Evaluate(const arma::mat& parameters, - const size_t begin, - const size_t batchSize); - - /** - * Evaluate the feedforward network with the given parameters. - * This function is usually called by the optimizer to train the model. - * - * @param parameters Matrix model parameters. - * @param gradient Matrix to output gradient into. - */ - template - double EvaluateWithGradient(const arma::mat& parameters, GradType& gradient); - - /** - * Evaluate the feedforward network with the given parameters, but using only - * a number of data points. This is useful for optimizers such as SGD, which - * require a separable objective function. - * - * @param parameters Matrix model parameters. - * @param begin Index of the starting point to use for objective function - * evaluation. - * @param gradient Matrix to output gradient into. - * @param batchSize Number of points to be passed at a time to use for - * objective function evaluation. - * @param deterministic Whether or not to train or test the model. Note some - * layer act differently in training or testing mode. - */ - template - double EvaluateWithGradient(const arma::mat& parameters, - const size_t begin, - GradType& gradient, - const size_t batchSize, - const bool deterministic); - - /** - * Evaluate the feedforward network with the given parameters, but using only - * a number of data points. This is useful for optimizers such as SGD, which - * require a separable objective function. This just calls the overload of - * Evaluate() with deterministic = true. - * - * @param parameters Matrix model parameters. - * @param begin Index of the starting point to use for objective function - * evaluation. - * @param gradient Matrix to output gradient into. - * @param batchSize Number of points to be passed at a time to use for - * objective function evaluation. - */ - template - double EvaluateWithGradient(const arma::mat& parameters, - const size_t begin, - GradType& gradient, - const size_t batchSize); - - /** - * Evaluate the gradient of the feedforward network with the given parameters, - * and with respect to only a number of points in the dataset. This is useful - * for optimizers such as SGD, which require a separable objective function. - * - * @param parameters Matrix of the model parameters to be optimized. - * @param begin Index of the starting point to use for objective function - * gradient evaluation. - * @param gradient Matrix to output gradient into. - * @param batchSize Number of points to be processed as a batch for objective - * function gradient evaluation. - */ - void Gradient(const arma::mat& parameters, - const size_t begin, - arma::mat& gradient, - const size_t batchSize); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - /* - * Add a new module to the model. - * - * @param args The layer parameter. - */ - template - void Add(Args... args) { network.push_back(new LayerType(args...)); } - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - void Add(LayerTypes layer) { network.push_back(layer); } - - //! Return the number of separable functions (the number of predictor points). - size_t NumFunctions() const { return numFunctions; } - - //! Return the initial point for the optimization. - const arma::mat& Parameters() const { return parameter; } - //! Modify the initial point for the optimization. - arma::mat& Parameters() { return parameter; } - - //! Get the matrix of responses to the input data points. - const arma::mat& Responses() const { return responses; } - //! Modify the matrix of responses to the input data points. - arma::mat& Responses() { return responses; } - - //! Get the matrix of data points (predictors). - const arma::mat& Predictors() const { return predictors; } - //! Modify the matrix of data points (predictors). - arma::mat& Predictors() { return predictors; } - - /** - * Reset the module infomration (weights/parameters). - */ - void ResetParameters(); - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - /** - * Perform the forward pass of the data in real batch mode. - * - * Forward and Backward should be used as a pair, and they are designed mainly - * for advanced users. User should try to use Predict and Train unless those - * two functions can't satisfy some special requirements. - * - * @param inputs The input data. - * @param results The predicted results. - */ - void Forward(arma::mat inputs, arma::mat& results); - - /** - * Perform a partial forward pass of the data. - * - * This function is meant for the cases when users require a forward pass only - * through certain layers and not the entire network. - * - * @param inputs The input data for the specified first layer. - * @param results The predicted results from the specified last layer. - * @param begin The index of the first layer. - * @param end The index of the last layer. - */ - void Forward(arma::mat inputs, - arma::mat& results, - const size_t begin, - const size_t end); - - /** - * Perform the backward pass of the data in real batch mode. - * - * Forward and Backward should be used as a pair, and they are designed mainly - * for advanced users. User should try to use Predict and Train unless those - * two functions can't satisfy some special requirements. - * - * @param targets The training target. - * @param gradients Computed gradients. - * @return Training error of the current pass. - */ - double Backward(arma::mat targets, arma::mat& gradients); - - private: - // Helper functions. - /** - * The Forward algorithm (part of the Forward-Backward algorithm). Computes - * forward probabilities for each module. - * - * @param input Data sequence to compute probabilities for. - */ - void Forward(arma::mat&& input); - - /** - * Prepare the network for the given data. - * This function won't actually trigger training process. - * - * @param predictors Input data variables. - * @param responses Outputs results from input data variables. - */ - void ResetData(arma::mat predictors, arma::mat responses); - - /** - * The Backward algorithm (part of the Forward-Backward algorithm). Computes - * backward pass for module. - */ - void Backward(); - - /** - * Iterate through all layer modules and update the the gradient using the - * layer defined optimizer. - */ - void Gradient(arma::mat&& input); - - /** - * Reset the module status by setting the current deterministic parameter - * for all modules that implement the Deterministic function. - */ - void ResetDeterministic(); - - /** - * Reset the gradient for all modules that implement the Gradient function. - */ - void ResetGradients(arma::mat& gradient); - - /** - * Swap the content of this network with given network. - * - * @param network Desired source network. - */ - void Swap(FFN& network); - - //! Instantiated outputlayer used to evaluate the network. - OutputLayerType outputLayer; - - //! Instantiated InitializationRule object for initializing the network - //! parameter. - InitializationRuleType initializeRule; - - //! The input width. - size_t width; - - //! The input height. - size_t height; - - //! Indicator if we already trained the model. - bool reset; - - //! Locally-stored model modules. - std::vector > network; - - //! The matrix of data points (predictors). - arma::mat predictors; - - //! The matrix of responses to the input data points. - arma::mat responses; - - //! Matrix of (trained) parameters. - arma::mat parameter; - - //! The number of separable functions (the number of predictor points). - size_t numFunctions; - - //! The current error for the backward pass. - arma::mat error; - - //! THe current input of the forward/backward pass. - arma::mat currentInput; - - //! Locally-stored delta visitor. - DeltaVisitor deltaVisitor; - - //! Locally-stored output parameter visitor. - OutputParameterVisitor outputParameterVisitor; - - //! Locally-stored weight size visitor. - WeightSizeVisitor weightSizeVisitor; - - //! Locally-stored output width visitor. - OutputWidthVisitor outputWidthVisitor; - - //! Locally-stored output height visitor. - OutputHeightVisitor outputHeightVisitor; - - //! Locally-stored reset visitor. - ResetVisitor resetVisitor; - - //! Locally-stored delete visitor. - DeleteVisitor deleteVisitor; - - //! The current evaluation mode (training or testing). - bool deterministic; - - //! Locally-stored delta object. - arma::mat delta; - - //! Locally-stored input parameter object. - arma::mat inputParameter; - - //! Locally-stored output parameter object. - arma::mat outputParameter; - - //! Locally-stored gradient parameter. - arma::mat gradient; - - //! Locally-stored copy visitor - CopyVisitor copyVisitor; -}; // class FFN - -} // namespace ann -} // namespace mlpack - -//! Set the serialization version of the FFN class. Multiple template arguments -//! makes this ugly... -namespace boost { -namespace serialization { - -template -struct version< - mlpack::ann::FFN> -{ - BOOST_STATIC_CONSTANT(int, value = 1); -}; - -} // namespace serialization -} // namespace boost - -// Include implementation. -#include "ffn_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/ffn_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/ffn_impl.hpp deleted file mode 100644 index 315dc817c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/ffn_impl.hpp +++ /dev/null @@ -1,626 +0,0 @@ -/** - * @file ffn_impl.hpp - * @author Marcus Edel - * - * Definition of the FFN class, which implements feed forward neural networks. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_FFN_IMPL_HPP -#define MLPACK_METHODS_ANN_FFN_IMPL_HPP - -// In case it hasn't been included yet. -#include "ffn.hpp" - -#include "visitor/forward_visitor.hpp" -#include "visitor/backward_visitor.hpp" -#include "visitor/deterministic_set_visitor.hpp" -#include "visitor/gradient_set_visitor.hpp" -#include "visitor/gradient_visitor.hpp" -#include "visitor/set_input_height_visitor.hpp" -#include "visitor/set_input_width_visitor.hpp" - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - - -template -FFN::FFN( - OutputLayerType outputLayer, InitializationRuleType initializeRule) : - outputLayer(std::move(outputLayer)), - initializeRule(std::move(initializeRule)), - width(0), - height(0), - reset(false), - numFunctions(0), - deterministic(true) -{ - /* Nothing to do here */ -} - -template -FFN::~FFN() -{ - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deleteVisitor)); -} - -template -void FFN::ResetData( - arma::mat predictors, arma::mat responses) -{ - numFunctions = responses.n_cols; - this->predictors = std::move(predictors); - this->responses = std::move(responses); - this->deterministic = true; - ResetDeterministic(); - - if (!reset) - ResetParameters(); -} - -template -template -void FFN::Train( - arma::mat predictors, - arma::mat responses, - OptimizerType& optimizer) -{ - ResetData(std::move(predictors), std::move(responses)); - - // Train the model. - Timer::Start("ffn_optimization"); - const double out = optimizer.Optimize(*this, parameter); - Timer::Stop("ffn_optimization"); - - Log::Info << "FFN::FFN(): final objective of trained model is " << out - << "." << std::endl; -} - -template -template -void FFN::Train( - arma::mat predictors, arma::mat responses) -{ - ResetData(std::move(predictors), std::move(responses)); - - OptimizerType optimizer; - - // Train the model. - Timer::Start("ffn_optimization"); - const double out = optimizer.Optimize(*this, parameter); - Timer::Stop("ffn_optimization"); - - Log::Info << "FFN::FFN(): final objective of trained model is " << out - << "." << std::endl; -} - -template -void FFN::Forward( - arma::mat inputs, arma::mat& results) -{ - if (parameter.is_empty()) - ResetParameters(); - - if (!deterministic) - { - deterministic = true; - ResetDeterministic(); - } - - currentInput = std::move(inputs); - Forward(std::move(currentInput)); - results = boost::apply_visitor(outputParameterVisitor, network.back()); -} - -template -void FFN::Forward( - arma::mat inputs, arma::mat& results, const size_t begin, const size_t end) -{ - boost::apply_visitor(ForwardVisitor(std::move(inputs), std::move( - boost::apply_visitor(outputParameterVisitor, network[begin]))), - network[begin]); - - for (size_t i = 1; i < end - begin + 1; ++i) - { - boost::apply_visitor(ForwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[begin + i - 1])), std::move( - boost::apply_visitor(outputParameterVisitor, network[begin + i]))), - network[begin + i]); - } - - results = boost::apply_visitor(outputParameterVisitor, network[end]); -} - -template -double FFN::Backward( - arma::mat targets, arma::mat& gradients) -{ - double res = outputLayer.Forward(std::move(boost::apply_visitor( - outputParameterVisitor, network.back())), std::move(targets)); - - outputLayer.Backward(std::move(boost::apply_visitor(outputParameterVisitor, - network.back())), std::move(targets), std::move(error)); - - gradients = arma::zeros(parameter.n_rows, parameter.n_cols); - - Backward(); - ResetGradients(gradients); - Gradient(std::move(currentInput)); - - return res; -} - -template -void FFN::Predict( - arma::mat predictors, arma::mat& results) -{ - if (parameter.is_empty()) - ResetParameters(); - - if (!deterministic) - { - deterministic = true; - ResetDeterministic(); - } - - arma::mat resultsTemp; - Forward(std::move(arma::mat(predictors.colptr(0), - predictors.n_rows, 1, false, true))); - resultsTemp = boost::apply_visitor(outputParameterVisitor, - network.back()).col(0); - - results = arma::mat(resultsTemp.n_elem, predictors.n_cols); - results.col(0) = resultsTemp.col(0); - - for (size_t i = 1; i < predictors.n_cols; i++) - { - Forward(std::move(arma::mat(predictors.colptr(i), - predictors.n_rows, 1, false, true))); - - resultsTemp = boost::apply_visitor(outputParameterVisitor, - network.back()); - results.col(i) = resultsTemp.col(0); - } -} - -template -double FFN::Evaluate( - const arma::mat& parameters) -{ - double res = 0; - for (size_t i = 0; i < predictors.n_cols; ++i) - res += Evaluate(parameters, i, true); - - return res; -} - -template -double FFN::Evaluate( - const arma::mat& /* parameters */, - const size_t begin, - const size_t batchSize, - const bool deterministic) -{ - if (parameter.is_empty()) - ResetParameters(); - - if (deterministic != this->deterministic) - { - this->deterministic = deterministic; - ResetDeterministic(); - } - - Forward(std::move(predictors.cols(begin, begin + batchSize - 1))); - double res = outputLayer.Forward( - std::move(boost::apply_visitor(outputParameterVisitor, network.back())), - std::move(responses.cols(begin, begin + batchSize - 1))); - - return res; -} - -template -double FFN::Evaluate( - const arma::mat& parameters, const size_t begin, const size_t batchSize) -{ - return Evaluate(parameters, begin, batchSize, true); -} - -template -template -double FFN:: -EvaluateWithGradient(const arma::mat& parameters, GradType& gradient) -{ - double res = 0; - for (size_t i = 0; i < predictors.n_cols; ++i) - res += EvaluateWithGradient(parameters, i, gradient, 1, false); - - return res; -} - -template -template -double FFN:: -EvaluateWithGradient(const arma::mat& /* parameters */, - const size_t begin, - GradType& gradient, - const size_t batchSize, - const bool deterministic) -{ - if (gradient.is_empty()) - { - if (parameter.is_empty()) - ResetParameters(); - - gradient = arma::zeros(parameter.n_rows, parameter.n_cols); - } - else - { - gradient.zeros(); - } - - if (deterministic != this->deterministic) - { - this->deterministic = deterministic; - ResetDeterministic(); - } - - Forward(std::move(predictors.cols(begin, begin + batchSize - 1))); - double res = outputLayer.Forward( - std::move(boost::apply_visitor(outputParameterVisitor, network.back())), - std::move(responses.cols(begin, begin + batchSize - 1))); - - outputLayer.Backward( - std::move(boost::apply_visitor(outputParameterVisitor, network.back())), - std::move(responses.cols(begin, begin + batchSize - 1)), - std::move(error)); - - Backward(); - ResetGradients(gradient); - Gradient(std::move(predictors.cols(begin, begin + batchSize - 1))); - - return res; -} - -template -template -double FFN:: -EvaluateWithGradient(const arma::mat& parameters, - const size_t begin, - GradType& gradient, - const size_t batchSize) -{ - return EvaluateWithGradient(parameters, begin, gradient, batchSize, false); -} - -template -void FFN::Gradient( - const arma::mat& parameters, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) -{ - if (gradient.is_empty()) - { - if (parameter.is_empty()) - ResetParameters(); - - gradient = arma::zeros(parameter.n_rows, parameter.n_cols); - } - else - { - gradient.zeros(); - } - - Evaluate(parameters, begin, batchSize, false); - - outputLayer.Backward( - std::move(boost::apply_visitor(outputParameterVisitor, network.back())), - std::move(responses.cols(begin, begin + batchSize - 1)), - std::move(error)); - - Backward(); - ResetGradients(gradient); - Gradient(std::move(predictors.cols(begin, begin + batchSize - 1))); -} - -template -void FFN::Shuffle() -{ - math::ShuffleData(predictors, responses, predictors, responses); -} - -template -void FFN::ResetParameters() -{ - ResetDeterministic(); - - // Reset the network parameter with the given initialization rule. - NetworkInitialization networkInit(initializeRule); - networkInit.Initialize(network, parameter); -} - -template -void FFN::ResetDeterministic() -{ - DeterministicSetVisitor deterministicSetVisitor(deterministic); - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deterministicSetVisitor)); -} - -template -void FFN::ResetGradients(arma::mat& gradient) -{ - size_t offset = 0; - for (size_t i = 0; i < network.size(); ++i) - { - offset += boost::apply_visitor(GradientSetVisitor(std::move(gradient), - offset), network[i]); - } -} - -template -void FFN::Forward(arma::mat&& input) -{ - boost::apply_visitor(ForwardVisitor(std::move(input), std::move( - boost::apply_visitor(outputParameterVisitor, network.front()))), - network.front()); - - if (!reset) - { - if (boost::apply_visitor(outputWidthVisitor, network.front()) != 0) - { - width = boost::apply_visitor(outputWidthVisitor, network.front()); - } - - if (boost::apply_visitor(outputHeightVisitor, network.front()) != 0) - { - height = boost::apply_visitor(outputHeightVisitor, network.front()); - } - } - - for (size_t i = 1; i < network.size(); ++i) - { - if (!reset) - { - // Set the input width. - boost::apply_visitor(SetInputWidthVisitor(width), network[i]); - - // Set the input height. - boost::apply_visitor(SetInputHeightVisitor(height), network[i]); - } - - boost::apply_visitor(ForwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[i - 1])), std::move( - boost::apply_visitor(outputParameterVisitor, network[i]))), network[i]); - - if (!reset) - { - // Get the output width. - if (boost::apply_visitor(outputWidthVisitor, network[i]) != 0) - { - width = boost::apply_visitor(outputWidthVisitor, network[i]); - } - - // Get the output height. - if (boost::apply_visitor(outputHeightVisitor, network[i]) != 0) - { - height = boost::apply_visitor(outputHeightVisitor, network[i]); - } - } - } - - if (!reset) - reset = true; -} - -template -void FFN::Backward() -{ - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network.back())), std::move(error), std::move( - boost::apply_visitor(deltaVisitor, network.back()))), network.back()); - - for (size_t i = 2; i < network.size(); ++i) - { - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[network.size() - i])), std::move( - boost::apply_visitor(deltaVisitor, network[network.size() - i + 1])), - std::move(boost::apply_visitor(deltaVisitor, - network[network.size() - i]))), network[network.size() - i]); - } -} - -template -void FFN::Gradient(arma::mat&& input) -{ - boost::apply_visitor(GradientVisitor(std::move(input), std::move( - boost::apply_visitor(deltaVisitor, network[1]))), network.front()); - - for (size_t i = 1; i < network.size() - 1; ++i) - { - boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[i - 1])), std::move( - boost::apply_visitor(deltaVisitor, network[i + 1]))), network[i]); - } - - boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[network.size() - 2])), std::move(error)), - network[network.size() - 1]); -} - -template -template -void FFN::serialize( - Archive& ar, const unsigned int version) -{ - ar & BOOST_SERIALIZATION_NVP(parameter); - ar & BOOST_SERIALIZATION_NVP(width); - ar & BOOST_SERIALIZATION_NVP(height); - ar & BOOST_SERIALIZATION_NVP(currentInput); - - // Earlier versions of the FFN code did not serialize whether or not the model - // was reset. - if (version > 0) - { - ar & BOOST_SERIALIZATION_NVP(reset); - } - - // Be sure to clear other layers before loading. - if (Archive::is_loading::value) - { - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deleteVisitor)); - network.clear(); - } - - ar & BOOST_SERIALIZATION_NVP(network); - - // If we are loading, we need to initialize the weights. - if (Archive::is_loading::value) - { - // The behavior in earlier versions was to always assume the weights needed - // to be reset. - if (version == 0) - reset = false; - - size_t offset = 0; - for (size_t i = 0; i < network.size(); ++i) - { - offset += boost::apply_visitor(WeightSetVisitor(std::move(parameter), - offset), network[i]); - - boost::apply_visitor(resetVisitor, network[i]); - } - - deterministic = true; - ResetDeterministic(); - } -} - -template -void FFN::Swap(FFN& network) -{ - std::swap(outputLayer, network.outputLayer); - std::swap(initializeRule, network.initializeRule); - std::swap(width, network.width); - std::swap(height, network.height); - std::swap(reset, network.reset); - std::swap(this->network, network.network); - std::swap(predictors, network.predictors); - std::swap(responses, network.responses); - std::swap(parameter, network.parameter); - std::swap(numFunctions, network.numFunctions); - std::swap(error, network.error); - std::swap(currentInput, network.currentInput); - std::swap(deterministic, network.deterministic); - std::swap(delta, network.delta); - std::swap(inputParameter, network.inputParameter); - std::swap(outputParameter, network.outputParameter); - std::swap(gradient, network.gradient); -}; - -template -FFN::FFN( - const FFN& network): - outputLayer(network.outputLayer), - initializeRule(network.initializeRule), - width(network.width), - height(network.height), - reset(network.reset), - predictors(network.predictors), - responses(network.responses), - parameter(network.parameter), - numFunctions(network.numFunctions), - error(network.error), - currentInput(network.currentInput), - deterministic(network.deterministic), - delta(network.delta), - inputParameter(network.inputParameter), - outputParameter(network.outputParameter), - gradient(network.gradient) -{ - // Build new layers according to source network - for (size_t i = 0; i < network.network.size(); ++i) - { - this->network.push_back(boost::apply_visitor(copyVisitor, - network.network[i])); - } -}; - -template -FFN::FFN( - FFN&& network): - outputLayer(std::move(network.outputLayer)), - initializeRule(std::move(network.initializeRule)), - width(network.width), - height(network.height), - reset(network.reset), - predictors(std::move(network.predictors)), - responses(std::move(network.responses)), - parameter(std::move(network.parameter)), - numFunctions(network.numFunctions), - error(std::move(network.error)), - currentInput(std::move(network.currentInput)), - deterministic(network.deterministic), - delta(std::move(network.delta)), - inputParameter(std::move(network.inputParameter)), - outputParameter(std::move(network.outputParameter)), - gradient(std::move(network.gradient)) -{ - this->network = std::move(network.network); -}; - -template -FFN& -FFN::operator = (FFN network) -{ - Swap(network); - return *this; -}; - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/const_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/const_init.hpp deleted file mode 100644 index 0b969dfa4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/const_init.hpp +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @file const_init.hpp - * @author Sumedh Ghaisas - * - * Intialization rule for the neural networks. This simple initialization is - * performed by assigning a matrix of all constant values to the weight - * matrix. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_CONST_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_CONST_INIT_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize weight matrix with constant values. - */ -class ConstInitialization -{ - public: - /** - * Create the ConstantInitialization object. - */ - ConstInitialization(const double initVal) : initVal(initVal) - { /* Nothing to do here */ } - - /** - * Initialize the elements of the specified weight matrix. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Mat& W, const size_t rows, const size_t cols) - { - W.set_size(rows, cols); - W.fill(initVal); - } - - /** - * Initialize the elements of the specified weight (3rd order tensor). - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Cube& W, - const size_t rows, - const size_t cols, - const size_t slices) - { - W.set_size(rows, cols, slices); - W.fill(initVal); - } - - //! Get the initialization value. - double const& InitValue() const { return initVal; } - //! Modify the initialization value. - double& initValue() { return initVal; } - - private: - //! Value to be initialized with - double initVal; -}; // class ConstInitialization - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/gaussian_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/gaussian_init.hpp deleted file mode 100644 index 29114ef5e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/gaussian_init.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file gaussian_init.hpp - * @author Kris Singh - * - * Intialization rule for the neural networks. This simple initialization is - * performed by assigning a gaussian matrix with a given mean and variance - * to the weight matrix. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_GAUSSIAN_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_GAUSSIAN_INIT_HPP - -#include -#include - -using namespace mlpack::math; - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize weigth matrix with a gaussian. - */ -class GaussianInitialization -{ - public: - /** - * Initialize the gaussian with the given mean and variance. - * - * @param mean Mean of the gaussian. - * @param variance Variance of the gaussian. - */ - GaussianInitialization(const double mean = 0, const double variance = 1) : - mean(mean), variance(variance) - { - // Nothing to do here. - } - - /** - * Initialize the elements weight matrix using a Gaussian Distribution. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - void Initialize(arma::mat& W, - const size_t rows, - const size_t cols) - { - if (W.is_empty()) - { - W = arma::mat(rows, cols); - } - W.imbue( [&]() { return arma::as_scalar(RandNormal(mean, variance)); } ); - } - - /** - * Initialize randomly the elements of the specified weight 3rd order tensor. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - * @param slice Numbers of slices. - */ - void Initialize(arma::cube & W, - const size_t rows, - const size_t cols, - const size_t slices) - { - W = arma::cube(rows, cols, slices); - - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); - } - - private: - //! Mean of the gaussian. - double mean; - - //! Variance of the gaussian. - double variance; -}; // class GaussianInitialization - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/glorot_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/glorot_init.hpp deleted file mode 100644 index a52a49631..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/glorot_init.hpp +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @file glorot_init.hpp - * @author Prabhat Sharma - * - * Definition and implementation of the Glorot initialization method. This - * initialization rule initialize the weights to maintain activation variances - * and back-propagated gradients variance as one moves up or down the network. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_GLOROT_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_GLOROT_INIT_HPP - -#include -#include "random_init.hpp" -#include "gaussian_init.hpp" - -using namespace mlpack::math; - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize the weight matrix with the Glorot - * Initialization method. The method is defined by - * - * @f{eqnarray*}{ - * \mathrm{Var}[w_i] &=& \frac{2}{n_i + n_{i+1}} \\ - * w_i \sim \mathrm{U}[-\frac{\sqrt{6}}{\sqrt{n_i + n_{i+1}}}, - * \frac{\sqrt{6}}{\sqrt{n_i + n_{i+1}}}] - * @f} - * - * where @f$ n_{i+1} @f$ is the number of neurons in the outgoing layer, @f$ n_i - * @f$ represents the number of neurons in the ingoing layer. Here Normal - * Distribution may also be used if needed - * - * For more information, see the following paper. - * - * @code - * @inproceedings {pmlr-v9-glorot10a, - * title = {Understanding the difficulty of training - * deep feedforward neural networks}, - * author = {Xavier Glorot and Yoshua Bengio}, - * booktitle = {Proceedings of the Thirteenth International Conference - * on Artificial Intelligence and Statistics}, - * year = {2010} - * } - * @endcode - * - */ -template -class GlorotInitializationType -{ - public: - /** - * Initialize the Glorot initialization object. - */ - GlorotInitializationType() - { - // Nothing to do here. - } - - /** - * Initialize the elements weight matrix with glorot initialization method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Mat& W, - const size_t rows, - const size_t cols); - - /** - * Initialize the elements of the specified weight 3rd order tensor with - * glorot initialization method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - * @param slice Numbers of slices. - */ - template - void Initialize(arma::Cube& W, - const size_t rows, - const size_t cols, - const size_t slices); -}; // class GlorotInitializationType - -template <> -template -inline void GlorotInitializationType::Initialize(arma::Mat& W, - const size_t rows, - const size_t cols) -{ - if (W.is_empty()) - W = arma::mat(rows, cols); - - double var = 2.0/double(rows + cols); - GaussianInitialization normalInit(0.0, var); - normalInit.Initialize(W, rows, cols); -} - -template <> -template -inline void GlorotInitializationType::Initialize(arma::Mat& W, - const size_t rows, - const size_t cols) -{ - if (W.is_empty()) - W = arma::mat(rows, cols); - - // Limit of distribution. - double a = sqrt(6) / sqrt(rows + cols); - RandomInitialization randomInit(-a, a); - randomInit.Initialize(W, rows, cols); -} - -template -template -inline void GlorotInitializationType::Initialize(arma::Cube& W, - const size_t rows, - const size_t cols, - const size_t slices) -{ - if (W.is_empty()) - { - W = arma::cube(rows, cols, slices); - } - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); -} - -// Convenience typedefs. - -/** - * XavierInitilization is the popular name for this method. - */ -using XavierInitialization = GlorotInitializationType; - -/** - * GlorotInitialization uses uniform distribution. - */ -using GlorotInitialization = GlorotInitializationType; -// Uses normal distribution -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/he_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/he_init.hpp deleted file mode 100644 index 421b499dc..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/he_init.hpp +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @file he_init.hpp - * @author Dakshit Agrawal - * @author Prabhat Sharma - * - * Intialization rule given by He et. al. for neural networks. The He - * initialization initializes weights of the neural network to better - * suit the rectified activation units. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_INIT_RULES_HE_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_HE_INIT_HPP - -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize weight matrix with the He - * initialization rule given by He et. al. for neural networks. The He - * initialization initializes weights of the neural network to better - * suit the rectified activation units. - * - * For more information, the following paper can be referred to: - * - * @code - * @article{Delving2015, - * title = {Delving Deep into Rectifiers: Surpassing Human-Level Performance - * on ImageNet Classification}, - * author = {Kaiming He and Xiangyu Zhang and Shaoqing Ren and Jian Sun}, - * journal = {2015 IEEE International Conference on Computer Vision (ICCV)}, - * year = {2015}, - * pages = {1026-1034} - * } - * @endcode - * - */ -class HeInitialization -{ - public: - /** - * Initialize the HeInitialization object. - */ - HeInitialization() - { - // Nothing to do here. - } - - /** - * Initialize the elements of the weight matrix with the He initialization - * rule. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - void Initialize(arma::mat& W, const size_t rows, const size_t cols) - { - // He initialization rule says to initialize weights with random - // values taken from a gaussian distribution with mean = 0 and - // standard deviation = sqrt(2/rows), i.e. variance = (2/rows). - const double variance = 2.0 / (double)rows; - - if (W.is_empty()) - { - W.set_size(rows, cols); - } - - // Multipling a random variable X with variance V(X) by some factor c, - // then the variance V(cX) = (c^2) * V(X). - W.imbue( [&]() { return sqrt(variance) * arma::randn(); } ); - } - - /** - * Initialize the elements of the specified weight 3rd order tensor - * with He initialization rule. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - * @param slice Numbers of slices. - */ - void Initialize(arma::cube & W, - const size_t rows, - const size_t cols, - const size_t slices) - { - if (W.is_empty()) - W.set_size(rows, cols, slices); - - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); - } -}; // class HeInitialization - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/init_rules_traits.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/init_rules_traits.hpp deleted file mode 100644 index 199e6e5a2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/init_rules_traits.hpp +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @file init_rules_traits.hpp - * @author Marcus Edel - * - * This provides the InitTraits class, a template class to get information - * about various initialization methods. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_INIT_RULES_TRAITS_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_INIT_RULES_TRAITS_HPP - -namespace mlpack { -namespace ann { - -/** - * This is a template class that can provide information about various - * initialization methods. By default, this class will provide the weakest - * possible assumptions on the initialization method, and each initialization - * method should override values as necessary. If a initialization method - * doesn't need to override a value, then there's no need to write a InitTraits - * specialization for that class. - */ -template -class InitTraits -{ - public: - /** - * This is true if the initialization method is used for a single layer. - */ - static const bool UseLayer = true; -}; - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/kathirvalavakumar_subavathi_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/kathirvalavakumar_subavathi_init.hpp deleted file mode 100644 index 1fc5f202d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/kathirvalavakumar_subavathi_init.hpp +++ /dev/null @@ -1,135 +0,0 @@ -/** - * @file kathirvalavakumar_subavathi_init.hpp - * @author Marcus Edel - * - * Definition and implementation of the initialization method by T. - * Kathirvalavakumar and S. Subavathi. This initialization rule is based on - * sensitivity analysis using cauchy’s inequality. - * - * For more information, see the following paper. - * - * @code - * @inproceedings{KathirvalavakumarJILSA2011, - * title={A New Weight Initialization Method Using Cauchy’s Inequality Based - * on Sensitivity Analysis}, - * author={T. Kathirvalavakumar and S. Subavathi}, - * booktitle={Journal of Intelligent Learning Systems and Applications, - * Vol. 3 No. 4}, - * year={2011} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_KATHIRVALAVAKUMAR_SUBAVATHI_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_KATHIRVALAVAKUMAR_SUBAVATHI_INIT_HPP - -#include - -#include "init_rules_traits.hpp" -#include "random_init.hpp" - -#include - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize the weight matrix with the method proposed - * by T. Kathirvalavakumar and S. Subavathi. The method is based on sensitivity - * analysis using using cauchy’s inequality. The method is defined by - * - * @f{eqnarray*}{ - * \overline{s} &=& f^{-1}(\overline{t}) \\ - * \Theta^{1}_{p} &\le& \overline{s} - * \sqrt{\frac{3}{I \sum_{i = 1}^{I} (x_{ip}^2)}} \\ - * \Theta^1 &=& min(\Theta_{p}^{1}); p=1,2,..,P \\ - * -\Theta^{1} \le w_{i}^{1} &\le& \Theta^{1} - * @f} - * - * where I is the number of inputs including the bias, p refers the pattern - * considered in training, f is the transfer function and \={s} is the active - * region in which the derivative of the activation function is greater than 4% - * of the maximum derivatives. - */ -class KathirvalavakumarSubavathiInitialization -{ - public: - /** - * Initialize the random initialization rule with the given values. - * - * @param data The input patterns. - * @param s Parameter that defines the active region. - */ - template - KathirvalavakumarSubavathiInitialization(const arma::Mat& data, - const double s) : s(s) - { - dataSum = arma::sum(data % data); - } - - /** - * Initialize the elements of the specified weight matrix with the - * Kathirvalavakumar-Subavathi method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Mat& W, const size_t rows, const size_t cols) - { - arma::Row b = s * arma::sqrt(3 / (rows * dataSum)); - const double theta = b.min(); - RandomInitialization randomInit(-theta, theta); - randomInit.Initialize(W, rows, cols); - } - - /** - * Initialize the elements of the specified weight 3rd order tensor with the - * Kathirvalavakumar-Subavathi method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Cube& W, - const size_t rows, - const size_t cols, - const size_t slices) - { - W = arma::Cube(rows, cols, slices); - - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); - } - - private: - //! Parameter that defines the sum of elements in each column. - arma::rowvec dataSum; - - //! Parameter that defines the active region. - double s; -}; // class KathirvalavakumarSubavathiInitialization - -//! Initialization traits of the kathirvalavakumar subavath initialization rule. -template<> -class InitTraits -{ - public: - //! The kathirvalavakumar subavath initialization rule is applied over the - //! entire network. - static const bool UseLayer = false; -}; - - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/lecun_normal_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/lecun_normal_init.hpp deleted file mode 100644 index 19bfb4617..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/lecun_normal_init.hpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @file lecun_normal_init.hpp - * @author Dakshit Agrawal - * @author Prabhat Sharma - * - * Intialization rule given by Lecun et. al. for neural networks and - * also mentioned in Self Normalizing Networks. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_INIT_RULES_LECUN_NORMAL_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_LECUN_NORMAL_INIT_HPP - -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize weight matrix with the Lecun Normalization - * initialization rule. - * - * For more information, the following papers can be referred to: - * - * @code - * @inproceedings{Klambauer2017, - * itle = {Self-Normalizing Neural Networks.}, - * author = {Klambauer, Günter and Unterthiner, Thomas - * and Mayr, Andreas and Hochreiter, Sepp}, - * pages = {972-981}, - * year = {2017} - * } - * - * @inproceedings{LeCun1998, - * title = {Efficient BackProp}, - * author = {LeCun, Yann and Bottou, L{\'e}on and Orr, Genevieve B. - * and M\"{u}ller, Klaus-Robert}, - * year = {1998}, - * pages = {9--50} - * } - * @endcode - * -*/ -class LecunNormalInitialization -{ - public: - /** - * Initialize the LecunNormalInitialization object. - */ - LecunNormalInitialization() - { - // Nothing to do here. - } - - /** - * Initialize the elements of the weight matrix with the Lecun - * Normal initialization rule. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - void Initialize(arma::mat& W, - const size_t rows, - const size_t cols) - { - // He initialization rule says to initialize weights with random - // values taken from a gaussian distribution with mean = 0 and - // standard deviation = sqrt(1 / rows), i.e. variance = (1 / rows). - const double variance = 1.0 / ((double) rows); - - if (W.is_empty()) - { - W.set_size(rows, cols); - } - - // Multipling a random variable X with variance V(X) by some factor c, - // then the variance V(cX) = (c ^ 2) * V(X). - W.imbue( [&]() { return sqrt(variance) * arma::randn(); } ); - } - - /** - * Initialize the elements of the specified weight 3rd order tensor - * with Lecun Normal initialization rule. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - * @param slice Numbers of slices. - */ - void Initialize(arma::cube & W, - const size_t rows, - const size_t cols, - const size_t slices) - { - if (W.is_empty()) - W.set_size(rows, cols, slices); - - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); - } -}; // class LecunNormalInitialization - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/network_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/network_init.hpp deleted file mode 100644 index e169506a7..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/network_init.hpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @file network_init.hpp - * @author Marcus Edel - * - * Intialization of a given network with a given initialization rule - * e.g. GaussianInitialization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_NETWORK_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_NETWORK_INIT_HPP - -#include - -#include "../visitor/reset_visitor.hpp" -#include "../visitor/weight_size_visitor.hpp" -#include "../visitor/weight_set_visitor.hpp" -#include "init_rules_traits.hpp" - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize the network with the given initialization - * rule. - */ -template -class NetworkInitialization -{ - public: - /** - * Use the given initialization rule to initialize the specified network. - * - * @param initializeRule Rule to initialize the given network. - */ - NetworkInitialization( - const InitializationRuleType& initializeRule = InitializationRuleType()) : - initializeRule(initializeRule) - { - // Nothing to do here. - } - - /** - * Initialize the specified network and store the results in the given - * parameter. - * - * @param network Network that should be initialized. - * @param parameter The network parameter. - */ - void Initialize(const std::vector >& network, - arma::mat& parameter) - { - // Determine the number of parameter/weights of the given network. - size_t weights = 0; - for (size_t i = 0; i < network.size(); ++i) - weights += boost::apply_visitor(weightSizeVisitor, network[i]); - parameter.set_size(weights, 1); - - // Initialize the network layer by layer or the complete network. - if (ann::InitTraits::UseLayer) - { - for (size_t i = 0, offset = 0; i < network.size(); ++i) - { - // Initialize the layer with the specified parameter/weight - // initialization rule. - const size_t weight = boost::apply_visitor(weightSizeVisitor, - network[i]); - arma::mat tmp = arma::mat(parameter.memptr() + offset, - weight, 1, false, false); - initializeRule.Initialize(tmp, tmp.n_elem, 1); - - // Increase the parameter/weight offset for the next layer. - offset += weight; - } - } - else - { - initializeRule.Initialize(parameter, parameter.n_elem, 1); - } - - // Note: We can't merge the for loop into the for loop above because - // WeightSetVisitor also sets the parameter/weights of the inner modules. - // Inner Modules are held by the parent module e.g. the concat module can - // hold various other modules. - for (size_t i = 0, offset = 0; i < network.size(); ++i) - { - offset += boost::apply_visitor(WeightSetVisitor(std::move(parameter), - offset), network[i]); - - boost::apply_visitor(resetVisitor, network[i]); - } - } - - private: - //! Instantiated InitializationRule object for initializing the network - //! parameter. - InitializationRuleType initializeRule; - - //! Locally-stored reset visitor. - ResetVisitor resetVisitor; - - //! Locally-stored weight size visitor. - WeightSizeVisitor weightSizeVisitor; -}; // class NetworkInitialization - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp deleted file mode 100644 index 50d62057e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @file nguyen_widrow_init.hpp - * @author Marcus Edel - * - * Definition and implementation of the Nguyen-Widrow method. This - * initialization rule initialize the weights so that the active regions of the - * neurons are approximately evenly distributed over the input space. - * - * For more information, see the following paper. - * - * @code - * @inproceedings{NguyenIJCNN1990, - * title={Improving the learning speed of 2-layer neural networks by choosing - * initial values of the adaptive weights}, - * booktitle={Neural Networks, 1990., 1990 IJCNN International Joint - * Conference on}, - * year={1990} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_NGUYEN_WIDROW_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_NGUYEN_WIDROW_INIT_HPP - -#include - -#include "init_rules_traits.hpp" -#include "random_init.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize the weight matrix with the Nguyen-Widrow - * method. The method is defined by - * - * @f{eqnarray*}{ - * \gamma &\le& w_i \le \gamma \\ - * \beta &=& 0.7H^{\frac{1}{I}} \\ - * n &=& \sqrt{\sum_{i=0}{I}w_{i}^{2}} \\ - * w_i &=& \frac{\beta w_i}{n} - * @f} - * - * Where H is the number of neurons in the outgoing layer, I represents the - * number of neurons in the ingoing layer and gamma defines the random interval - * that is used to initialize the weights with a random value in a specific - * range. - */ -class NguyenWidrowInitialization -{ - public: - /** - * Initialize the random initialization rule with the given lower bound and - * upper bound. - * - * @param lowerBound The number used as lower bound. - * @param upperBound The number used as upper bound. - */ - NguyenWidrowInitialization(const double lowerBound = -0.5, - const double upperBound = 0.5) : - lowerBound(lowerBound), upperBound(upperBound) { } - - /** - * Initialize the elements of the specified weight matrix with the - * Nguyen-Widrow method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Mat& W, const size_t rows, const size_t cols) - { - RandomInitialization randomInit(lowerBound, upperBound); - randomInit.Initialize(W, rows, cols); - - double beta = 0.7 * std::pow(cols, 1 / rows); - W *= (beta / arma::norm(W)); - } - - /** - * Initialize the elements of the specified weight 3rd order tensor with the - * Nguyen-Widrow method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - * @param slices Number of slices. - */ - template - void Initialize(arma::Cube& W, - const size_t rows, - const size_t cols, - const size_t slices) - { - W = arma::Cube(rows, cols, slices); - - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); - } - - private: - //! The number used as lower bound. - double lowerBound; - - //! The number used as upper bound. - double upperBound; -}; // class NguyenWidrowInitialization - -//! Initialization traits of the Nguyen-Widrow initialization rule. -template<> -class InitTraits -{ - public: - //! The Nguyen-Widrow initialization rule is applied over the entire network. - static const bool UseLayer = false; -}; - - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/oivs_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/oivs_init.hpp deleted file mode 100644 index df5c714f2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/oivs_init.hpp +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @file oivs_init.hpp - * @author Marcus Edel - * - * Definition and implementation of the Optimal Initial Value Setting method - * (OIVS). This initialization rule is based on geometrical considerations as - * described by H. Shimodaira. - * - * For more information, see the following paper. - * - * @code - * @inproceedings{ShimodairaICTAI1994, - * title={A weight value initialization method for improving learning - * performance of the backpropagation algorithm in neural networks}, - * author={Shimodaira, H.}, - * booktitle={Tools with Artificial Intelligence, 1994. Proceedings., - * Sixth International Conference on}, - * year={1994} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_OIVS_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_OIVS_INIT_HPP - -#include -#include - -#include "random_init.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize the weight matrix with the oivs method. The - * method is based on the equations representing the characteristics of the - * information transformation mechanism of a node. The method is defined by - * - * @f{eqnarray*}{ - * b &=& |F^{-1}(1 - \epsilon) - f^{-1}(\epsilon)| \\ - * \hat{w} &=& \frac{b}{k \cdot n} \\ - * \gamma &\le& a_i \le \gamma \\ - * w_i &=& \hat{w} \cdot \sqrt{a_i + 1} - * @f} - * - * Where f is the transfer function epsilon, k custom parameters, n the number of - * neurons in the outgoing layer and gamma a parameter that defines the random - * interval. - * - * @tparam ActivationFunction The activation function used for the oivs method. - */ -template< - class ActivationFunction = LogisticFunction -> -class OivsInitialization -{ - public: - /** - * Initialize the random initialization rule with the given values. - * - * @param epsilon Parameter to control the activation region. - * @param k Parameter to control the activation region width. - * @param gamma Parameter to define the uniform random range. - */ - OivsInitialization(const double epsilon = 0.1, - const int k = 5, - const double gamma = 0.9) : - k(k), gamma(gamma), - b(std::abs(ActivationFunction::Inv(1 - epsilon) - - ActivationFunction::Inv(epsilon))) - { - } - - /** - * Initialize the elements of the specified weight matrix with the oivs method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Mat& W, const size_t rows, const size_t cols) - { - RandomInitialization randomInit(-gamma, gamma); - randomInit.Initialize(W, rows, cols); - - W = (b / (k * rows)) * arma::sqrt(W + 1); - } - - /** - * Initialize the elements of the specified weight 3rd order tensor with the - * oivs method. - * - * @param W 3rd order tensor to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - * @param slices Number of slices. - */ - template - void Initialize(arma::Cube& W, - const size_t rows, - const size_t cols, - const size_t slices) - { - W = arma::Cube(rows, cols, slices); - - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); - } - - private: - //! Parameter to control the activation region width. - int k; - - //! Parameter to define the uniform random range. - double gamma; - - //! Parameter to control the activation region. - double b; -}; // class OivsInitialization - - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/orthogonal_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/orthogonal_init.hpp deleted file mode 100644 index 23d0245c5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/orthogonal_init.hpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file orthogonal_init.hpp - * @author Marcus Edel - * - * Definition and implementation of the orthogonal matrix initialization method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_ORTHOGONAL_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_ORTHOGONAL_INIT_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize the weight matrix with the orthogonal - * matrix initialization - */ -class OrthogonalInitialization -{ - public: - /** - * Initialize the orthogonal matrix initialization rule with the given gain. - * - * @param gain The gain value. - */ - OrthogonalInitialization(const double gain = 1.0) : gain(gain) { } - - /** - * Initialize the elements of the specified weight matrix with the orthogonal - * matrix initialization method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Mat& W, const size_t rows, const size_t cols) - { - arma::Mat V; - arma::Col s; - - arma::svd_econ(W, s, V, arma::randu >(rows, cols)); - W *= gain; - } - - /** - * Initialize the elements of the specified weight 3rd order tensor with the - * orthogonal matrix initialization method. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - * @param slices Number of slices. - */ - template - void Initialize(arma::Cube& W, - const size_t rows, - const size_t cols, - const size_t slices) - { - W = arma::Cube(rows, cols, slices); - - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); - } - - private: - //! The number used as gain. - double gain; -}; // class OrthogonalInitialization - - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/random_init.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/random_init.hpp deleted file mode 100644 index 6b79207c4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/init_rules/random_init.hpp +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @file random_init.hpp - * @author Marcus Edel - * - * Intialization rule for the neural networks. This simple initialization is - * performed by assigning a random matrix to the weight matrix. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_INIT_RULES_RANDOM_INIT_HPP -#define MLPACK_METHODS_ANN_INIT_RULES_RANDOM_INIT_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class is used to initialize randomly the weight matrix. - */ -class RandomInitialization -{ - public: - /** - * Initialize the random initialization rule with the given lower bound and - * upper bound. - * - * @param lowerBound The number used as lower bound. - * @param upperBound The number used as upper bound. - */ - RandomInitialization(const double lowerBound = -1, - const double upperBound = 1) : - lowerBound(lowerBound), upperBound(upperBound) { } - - /** - * Initialize the random initialization rule with the given bound. - * Using the negative of the bound as lower bound and the positive bound as - * upper bound. - * - * @param bound The number used as lower bound - */ - RandomInitialization(const double bound) : - lowerBound(-std::abs(bound)), upperBound(std::abs(bound)) { } - - /** - * Initialize randomly the elements of the specified weight matrix. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Mat& W, const size_t rows, const size_t cols) - { - W = lowerBound + arma::randu>(rows, cols) * - (upperBound - lowerBound); - } - - /** - * Initialize randomly the elements of the specified weight 3rd order tensor. - * - * @param W Weight matrix to initialize. - * @param rows Number of rows. - * @param cols Number of columns. - */ - template - void Initialize(arma::Cube& W, - const size_t rows, - const size_t cols, - const size_t slices) - { - W = arma::Cube(rows, cols, slices); - - for (size_t i = 0; i < slices; i++) - Initialize(W.slice(i), rows, cols); - } - - private: - //! The number used as lower bound. - double lowerBound; - - //! The number used as upper bound. - double upperBound; -}; // class RandomInitialization - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/add.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/add.hpp deleted file mode 100644 index 1db7e95a3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/add.hpp +++ /dev/null @@ -1,137 +0,0 @@ -/** - * @file add.hpp - * @author Marcus Edel - * - * Definition of the Add class that applies a bias term to the incoming data. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_ADD_HPP -#define MLPACK_METHODS_ANN_LAYER_ADD_HPP - -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Add module class. The Add module applies a bias term - * to the incoming data. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class Add -{ - public: - /** - * Create the Add object using the specified number of output units. - * - * @param outSize The number of output units. - */ - Add(const size_t outSize = 0); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - const arma::Mat&& gy, - arma::Mat&& g); - - /** - * Calculate the gradient using the output delta and the input activation. - * - * @param input The propagated input. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class Add - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "add_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_impl.hpp deleted file mode 100644 index dda53d94d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_impl.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file add_impl.hpp - * @author Marcus Edel - * - * Implementation of the Add class that applies a bias term to the incoming - * data. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_ADD_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_ADD_IMPL_HPP - -// In case it hasn't yet been included. -#include "add.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Add::Add(const size_t outSize) : - outSize(outSize) -{ - weights.set_size(outSize, 1); -} - -template -template -void Add::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - output = input; - output.each_col() += weights; -} - -template -template -void Add::Backward( - const arma::Mat&& /* input */, - const arma::Mat&& gy, - arma::Mat&& g) -{ - g = gy; -} - -template -template -void Add::Gradient( - const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient) -{ - gradient = error; -} - -template -template -void Add::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(outSize); - - if (Archive::is_loading::value) - weights.set_size(outSize, 1); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_merge.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_merge.hpp deleted file mode 100644 index 44aee7bca..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_merge.hpp +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @file add_merge.hpp - * @author Marcus Edel - * - * Definition of the AddMerge module which accumulates the output of the given - * modules. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_ADD_MERGE_HPP -#define MLPACK_METHODS_ANN_LAYER_ADD_MERGE_HPP - -#include - -#include "../visitor/delete_visitor.hpp" -#include "../visitor/delta_visitor.hpp" -#include "../visitor/output_parameter_visitor.hpp" - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the AddMerge module class. The AddMerge class accumulates - * the output of various modules. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam CustomLayers Additional custom layers that can be added. - */ -template< - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat, - typename... CustomLayers -> -class AddMerge -{ - public: - /** - * Create the AddMerge object using the specified parameters. - * - * @param model Expose all the network modules. - */ - AddMerge(const bool model = false); - - //! Destructor to release allocated memory. - ~AddMerge(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& /* input */, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - void Add(LayerTypes layer) { network.push_back(layer); } - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - template - void Add(const LayerType& layer) { network.push_back(new LayerType(layer)); } - - /* - * Add a new module to the model. - * - * @param args The layer parameter. - */ - template - void Add(Args... args) { network.push_back(new LayerType(args...)); } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Return the model modules. - std::vector >& Model() - { - if (model) - { - return network; - } - - return empty; - } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Parameter which indicates if the modules should be exposed. - bool model; - - //! We need this to know whether we should delete the layer in the destructor. - bool ownsLayer; - - //! Locally-stored network modules. - std::vector > network; - - //! Locally-stored empty list of modules. - std::vector > empty; - - //! Locally-stored delete visitor module object. - DeleteVisitor deleteVisitor; - - //! Locally-stored output parameter visitor module object. - OutputParameterVisitor outputParameterVisitor; - - //! Locally-stored delta visitor module object. - DeltaVisitor deltaVisitor; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class AddMerge - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "add_merge_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_merge_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_merge_impl.hpp deleted file mode 100644 index 1e67c3237..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/add_merge_impl.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file add_merge_impl.hpp - * @author Marcus Edel - * - * Definition of the AddMerge module which accumulates the output of the given - * modules. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_ADD_MERGE_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_ADD_MERGE_IMPL_HPP - -// In case it hasn't yet been included. -#include "add_merge.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -AddMerge::AddMerge( - const bool model) : model(model), ownsLayer(!model) -{ - // Nothing to do here. -} - -template -AddMerge::~AddMerge() -{ - if (ownsLayer) - { - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deleteVisitor)); - } -} - -template -template -void AddMerge::Forward( - const InputType&& /* input */, OutputType&& output) -{ - output = boost::apply_visitor(outputParameterVisitor, network.front()); - - for (size_t i = 1; i < network.size(); ++i) - { - output += boost::apply_visitor(outputParameterVisitor, network[i]); - } -} - -template -template -void AddMerge::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - g = gy; -} - -template -template -void AddMerge::serialize( - Archive& ar, const unsigned int /* version */) -{ - if (Archive::is_loading::value) - network.clear(); - - ar & BOOST_SERIALIZATION_NVP(network); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/alpha_dropout.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/alpha_dropout.hpp deleted file mode 100644 index 978edd861..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/alpha_dropout.hpp +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @file alpha_dropout.hpp - * @author Dakshit Agrawal - * - * Definition of the Alpha-Dropout class, which implements a regularizer that - * randomly sets units to alpha-dash to prevent them from co-adapting and - * makes an affine transformation so as to keep the mean and variance of - * outputs at their original values. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_LAYER_ALPHA_DROPOUT_HPP -#define MLPACK_METHODS_ANN_LAYER_ALPHA_DROPOUT_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The alpha - dropout layer is a regularizer that randomly with probability - * 'ratio' sets input values to alphaDash. The alpha - dropout layer is mostly - * used for SELU activation function where successive layers don't have same - * mean and variance. - * - * For more information, see the following. - * - * @code - * @article{Klambauer2017, - * author = {Gunter Klambauer and Thomas Unterthiner and - * Andreas Mayr}, - * title = {Self-Normalizing Neural Networks}, - * journal = {Advances in Neural Information Processing Systems}, - * year = {2017} - * } - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template -class AlphaDropout -{ - public: - /** - * Create the Alpha_Dropout object using the specified ratio. - * - * @param ratio The probability of setting a value to alphaDash. - * @param alphaDash The dropout scaling parameter. - */ - AlphaDropout(const double ratio = 0.5, - const double alphaDash = -alpha * lambda); - - /** - * Ordinary feed forward pass of the alpha_dropout layer. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of the alpha_dropout layer. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the detla. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! The value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - //! The probability of setting a value to alphaDash. - double Ratio() const { return ratio; } - - //! Value to be multiplied with x for affine transformation. - double A() const { return a; } - - //! Value to be added to a*x for affine transformation. - double B() const { return b; } - - //! Value of alphaDash. - double AlphaDash() const {return alphaDash; } - - //! Get the mask. - OutputDataType const& Mask() const {return mask;} - - //! Modify the probability of setting a value to alphaDash. As - //! 'a' and 'b' depend on 'ratio', modify them as well. - void Ratio(const double r) - { - ratio = r; - a = pow((1 - ratio) * (1 + ratio * pow(alphaDash, 2)), -0.5); - b = -a * alphaDash * ratio; - } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored mast object. - OutputDataType mask; - - //! The probability of setting a value to aplhaDash. - double ratio; - - //! The low variance value of SELU activation function. - double alphaDash; - - //! If true dropout and scaling is disabled, see notes above. - bool deterministic; - - //! Value of alpha for normalized inputs (taken from SELU). - static constexpr double alpha = 1.6732632423543772848170429916717; - - //! Value of lambda for normalized inputs (taken from SELU). - static constexpr double lambda = 1.0507009873554804934193349852946; - - //! Value to be multiplied with x for affine transformation. - double a; - - //! Value to be added to a*x for affine transformation. - double b; -}; // class AlphaDropout - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "alpha_dropout_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/alpha_dropout_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/alpha_dropout_impl.hpp deleted file mode 100644 index 78a779053..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/alpha_dropout_impl.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file alpha_dropout_impl.hpp - * @author Dakshit Agrawal - * - * Definition of the Alpha-Dropout class, which implements a regularizer that - * randomly sets units to alpha-dash to prevent them from co-adapting and - * makes an affine transformation so as to keep the mean and variance of - * outputs at their original values. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_LAYER_ALPHA_DROPOUT_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_ALPHA_DROPOUT_IMPL_HPP - -// In case it hasn't yet been included. -#include "alpha_dropout.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -AlphaDropout::AlphaDropout( - const double ratio, - const double alphaDash) : - ratio(ratio), - alphaDash(alphaDash), - deterministic(false) -{ - Ratio(ratio); -} - -template -template -void AlphaDropout::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - // The dropout mask will not be multiplied in the deterministic mode - // (during testing). - if (deterministic) - { - output = input; - } - else - { - // Set values to alphaDash with probability ratio. Then apply affine - // transformation so as to keep mean and variance of outputs to their - // original values. - mask = arma::randu< arma::Mat >(input.n_rows, input.n_cols); - mask.transform( [&](double val) { return (val > ratio); } ); - output = (input % mask + alphaDash * (1 - mask)) * a + b; - } -} - -template -template -void AlphaDropout::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - g = gy % mask * a; -} - -template -template -void AlphaDropout::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(ratio); - ar & BOOST_SERIALIZATION_NVP(alphaDash); - ar & BOOST_SERIALIZATION_NVP(a); - ar & BOOST_SERIALIZATION_NVP(b); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/atrous_convolution.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/atrous_convolution.hpp deleted file mode 100644 index 79bf1def2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/atrous_convolution.hpp +++ /dev/null @@ -1,360 +0,0 @@ -/** - * @file atrous_convolution.hpp - * @author Aarush Gupta - * @author Shikhar Jaiswal - * - * Definition of the Atrous Convolution class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_ATROUS_CONVOLUTION_HPP -#define MLPACK_METHODS_ANN_LAYER_ATROUS_CONVOLUTION_HPP - -#include - -#include -#include -#include -#include - -#include "layer_types.hpp" - -namespace mlpack{ -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Atrous Convolution class. The Atrous Convolution - * class represents a single layer of a neural network. Atrous (or Dilated) - * Convolutions are just simple convolutions applied to input with the defined, - * spaces included between the kernel cells, in order to capture a larger - * field of reception, without having to increase dicrete kernel sizes. - * - * @tparam ForwardConvolutionRule Atrous Convolution to perform forward process. - * @tparam BackwardConvolutionRule Atrous Convolution to perform backward process. - * @tparam GradientConvolutionRule Atrous Convolution to calculate gradient. - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename ForwardConvolutionRule = NaiveConvolution, - typename BackwardConvolutionRule = NaiveConvolution, - typename GradientConvolutionRule = NaiveConvolution, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class AtrousConvolution -{ - public: - //! Create the AtrousConvolution object. - AtrousConvolution(); - - /** - * Create the AtrousConvolution object using the specified number of - * input maps, output maps, filter size, stride, dilation and - * padding parameter. - * - * @param inSize The number of input maps. - * @param outSize The number of output maps. - * @param kW Width of the filter/kernel. - * @param kH Height of the filter/kernel. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - * @param padW Padding width of the input. - * @param padH Padding height of the input. - * @param inputWidth The widht of the input data. - * @param inputHeight The height of the input data. - * @param dilationW The space between the cells of filters in x direction. - * @param dilationH The space between the cells of filters in y direction. - */ - AtrousConvolution(const size_t inSize, - const size_t outSize, - const size_t kW, - const size_t kH, - const size_t dW = 1, - const size_t dH = 1, - const size_t padW = 0, - const size_t padH = 0, - const size_t inputWidth = 0, - const size_t inputHeight = 0, - const size_t dilationW = 1, - const size_t dilationH = 1); - - /* - * Set the weight and bias term. - */ - void Reset(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! Get the input width. - size_t const& InputWidth() const { return inputWidth; } - //! Modify input the width. - size_t& InputWidth() { return inputWidth; } - - //! Get the input height. - size_t const& InputHeight() const { return inputHeight; } - //! Modify the input height. - size_t& InputHeight() { return inputHeight; } - - //! Get the output width. - size_t const& OutputWidth() const { return outputWidth; } - //! Modify the output width. - size_t& OutputWidth() { return outputWidth; } - - //! Get the output height. - size_t const& OutputHeight() const { return outputHeight; } - //! Modify the output height. - size_t& OutputHeight() { return outputHeight; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /* - * Return the convolution output size. - * - * @param size The size of the input (row or column). - * @param k The size of the filter (width or height). - * @param s The stride size (x or y direction). - * @param p The size of the padding (width or height). - * @param d The dilation size. - * @return The convolution output size. - */ - size_t ConvOutSize(const size_t size, - const size_t k, - const size_t s, - const size_t p, - const size_t d) - { - return std::floor(size + p * 2 - d * (k - 1) - 1) / s + 1; - } - - /* - * Rotates a 3rd-order tensor counterclockwise by 180 degrees. - * - * @param input The input data to be rotated. - * @param output The rotated output. - */ - template - void Rotate180(const arma::Cube& input, arma::Cube& output) - { - output = arma::Cube(input.n_rows, input.n_cols, input.n_slices); - - // * left-right flip, up-down flip */ - for (size_t s = 0; s < output.n_slices; s++) - output.slice(s) = arma::fliplr(arma::flipud(input.slice(s))); - } - - /* - * Rotates a dense matrix counterclockwise by 180 degrees. - * - * @param input The input data to be rotated. - * @param output The rotated output. - */ - template - void Rotate180(const arma::Mat& input, arma::Mat& output) - { - // * left-right flip, up-down flip */ - output = arma::fliplr(arma::flipud(input)); - } - - /* - * Pad the given input data. - * - * @param input The input to be padded. - * @param wPad Padding width of the input. - * @param hPad Padding height of the input. - * @param output The padded output data. - */ - template - void Pad(const arma::Mat& input, - size_t wPad, - size_t hPad, - arma::Mat& output) - { - if (output.n_rows != input.n_rows + wPad * 2 || - output.n_cols != input.n_cols + hPad * 2) - { - output = arma::zeros(input.n_rows + wPad * 2, input.n_cols + hPad * 2); - } - - output.submat(wPad, hPad, wPad + input.n_rows - 1, - hPad + input.n_cols - 1) = input; - } - - /* - * Pad the given input data. - * - * @param input The input to be padded. - * @param wPad Padding width of the input. - * @param hPad Padding height of the input. - * @param output The padded output data. - */ - template - void Pad(const arma::Cube& input, - size_t wPad, - size_t hPad, - arma::Cube& output) - { - output = arma::zeros(input.n_rows + wPad * 2, - input.n_cols + hPad * 2, input.n_slices); - - for (size_t i = 0; i < input.n_slices; ++i) - { - Pad(input.slice(i), wPad, hPad, output.slice(i)); - } - } - - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored filter/kernel width. - size_t kW; - - //! Locally-stored filter/kernel height. - size_t kH; - - //! Locally-stored stride of the filter in x-direction. - size_t dW; - - //! Locally-stored stride of the filter in y-direction. - size_t dH; - - //! Locally-stored padding width. - size_t padW; - - //! Locally-stored padding height. - size_t padH; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored weight object. - arma::cube weight; - - //! Locally-stored bias term object. - arma::mat bias; - - //! Locally-stored input width. - size_t inputWidth; - - //! Locally-stored input height. - size_t inputHeight; - - //! Locally-stored output width. - size_t outputWidth; - - //! Locally-stored output height. - size_t outputHeight; - - //! Locally-stored width dilation factor. - size_t dilationW; - - //! Locally-stored height dilation factor. - size_t dilationH; - - //! Locally-stored transformed output parameter. - arma::cube outputTemp; - - //! Locally-stored transformed input parameter. - arma::cube inputTemp; - - //! Locally-stored transformed padded input parameter. - arma::cube inputPaddedTemp; - - //! Locally-stored transformed error parameter. - arma::cube gTemp; - - //! Locally-stored transformed gradient parameter. - arma::cube gradientTemp; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class AtrousConvolution - -} // namespace ann -} // namespace mlpack - -// Include implementation -#include "atrous_convolution_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/atrous_convolution_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/atrous_convolution_impl.hpp deleted file mode 100644 index 5593a96f8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/atrous_convolution_impl.hpp +++ /dev/null @@ -1,351 +0,0 @@ -/** - * @file atrous_convolution_impl.hpp - * @author Aarush Gupta - * @author Shikhar Jaiswal - * - * Implementation of the Atrous Convolution module class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_ATROUS_CONVOLUTION_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_ATROUS_CONVOLUTION_IMPL_HPP - -// In case it hasn't yet been included. -#include "atrous_convolution.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -AtrousConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::AtrousConvolution() -{ - // Nothing to do here. -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -AtrousConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::AtrousConvolution( - const size_t inSize, - const size_t outSize, - const size_t kW, - const size_t kH, - const size_t dW, - const size_t dH, - const size_t padW, - const size_t padH, - const size_t inputWidth, - const size_t inputHeight, - const size_t dilationW, - const size_t dilationH) : - inSize(inSize), - outSize(outSize), - kW(kW), - kH(kH), - dW(dW), - dH(dH), - padW(padW), - padH(padH), - inputWidth(inputWidth), - inputHeight(inputHeight), - outputWidth(0), - outputHeight(0), - dilationW(dilationW), - dilationH(dilationH) -{ - weights.set_size((outSize * inSize * kW * kH) + outSize, 1); -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -void AtrousConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Reset() -{ - weight = arma::cube(weights.memptr(), kW, kH, - outSize * inSize, false, false); - bias = arma::mat(weights.memptr() + weight.n_elem, - outSize, 1, false, false); -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void AtrousConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Forward(const arma::Mat&& input, arma::Mat&& output) -{ - inputTemp = arma::cube(input.memptr(), inputWidth, inputHeight, inSize); - - if (padW != 0 || padH != 0) - { - Pad(inputTemp, padW, padH, inputPaddedTemp); - } - - size_t wConv = ConvOutSize(inputWidth, kW, dW, padW, dilationW); - size_t hConv = ConvOutSize(inputHeight, kH, dH, padH, dilationH); - - output.set_size(wConv * hConv * outSize, 1); - outputTemp = arma::Cube(output.memptr(), wConv, hConv, outSize, - false, false); - outputTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0; inMap < inSize; inMap++, outMapIdx++) - { - arma::Mat convOutput; - if (padW != 0 || padH != 0) - { - ForwardConvolutionRule::Convolution(inputPaddedTemp.slice(inMap), - weight.slice(outMapIdx), convOutput, dW, dH, dilationW, dilationH); - } - else - { - ForwardConvolutionRule::Convolution(inputTemp.slice(inMap), - weight.slice(outMapIdx), convOutput, dW, dH, dilationW, dilationH); - } - outputTemp.slice(outMap) += convOutput; - } - - outputTemp.slice(outMap) += bias(outMap); - } - - outputWidth = outputTemp.n_rows; - outputHeight = outputTemp.n_cols; -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void AtrousConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - arma::cube mappedError(gy.memptr(), outputWidth, outputHeight, outSize, - false, false); - - g.set_size(inputTemp.n_rows * inputTemp.n_cols * inputTemp.n_slices, 1); - gTemp = arma::Cube(g.memptr(), inputTemp.n_rows, - inputTemp.n_cols, inputTemp.n_slices, false, false); - gTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0; inMap < inSize; inMap++, outMapIdx++) - { - arma::Mat output, rotatedFilter; - Rotate180(weight.slice(outMapIdx), rotatedFilter); - - BackwardConvolutionRule::Convolution(mappedError.slice(outMap), - rotatedFilter, output, dW, dH, dilationW, dilationH); - - if (padW != 0 || padH != 0) - { - gTemp.slice(inMap) += output.submat(rotatedFilter.n_rows / 2, - rotatedFilter.n_cols / 2, - rotatedFilter.n_rows / 2 + gTemp.n_rows - 1, - rotatedFilter.n_cols / 2 + gTemp.n_cols - 1); - } - else - { - gTemp.slice(inMap) += output; - } - } - } -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void AtrousConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Gradient( - const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient) -{ - arma::cube mappedError; - if (padW != 0 && padH != 0) - { - mappedError = arma::cube(error.memptr(), outputWidth / padW, - outputHeight / padH, outSize); - } - else - { - mappedError = arma::cube(error.memptr(), outputWidth, - outputHeight, outSize); - } - - gradient.set_size(weights.n_elem, 1); - gradientTemp = arma::Cube(gradient.memptr(), weight.n_rows, weight.n_cols, - weight.n_slices, false, false); - gradientTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0, s = outMap; inMap < inSize; inMap++, outMapIdx++, - s += outSize) - { - arma::Cube inputSlices; - if (padW != 0 || padH != 0) - { - inputSlices = inputPaddedTemp.slices(inMap, inMap); - } - else - { - inputSlices = inputTemp.slices(inMap, inMap); - } - - arma::Cube deltaSlices = mappedError.slices(outMap, outMap); - - arma::Cube output, reducedOutput; - GradientConvolutionRule::Convolution(inputSlices, deltaSlices, - output, dW, dH, 1, 1); - arma::Mat reducedMat; - reducedOutput = arma::zeros >(kW, kH, output.n_slices); - - for (size_t j = 0; j < output.n_slices; j++) - { - reducedMat = output.slice(j); - if (dilationH > 1) - { - for (size_t i = 1; i < reducedMat.n_cols; i++){ - reducedMat.shed_cols(i, i + dilationH - 2); - } - } - if (dilationW > 1) - { - for (size_t i = 1; i < reducedMat.n_rows; i++){ - reducedMat.shed_rows(i, i + dilationW - 2); - } - } - reducedOutput.slice(j) = reducedMat; - } - - if ((padW != 0 || padH != 0) && - (gradientTemp.n_rows < reducedOutput.n_rows && - gradientTemp.n_cols < reducedOutput.n_cols)) - { - for (size_t i = 0; i < reducedOutput.n_slices; i++) - { - gradientTemp.slice(s) += reducedOutput.slice(i).submat( - reducedOutput.n_rows / 2, reducedOutput.n_cols / 2, - reducedOutput.n_rows / 2 + gradientTemp.n_rows - 1, - reducedOutput.n_cols / 2 + gradientTemp.n_cols - 1); - } - } - else - { - for (size_t i = 0; i < reducedOutput.n_slices; i++) - gradientTemp.slice(s) += reducedOutput.slice(i); - } - } - - gradient.submat(weight.n_elem + outMap, 0, weight.n_elem + outMap, 0) = - arma::accu(mappedError.slices(outMap, outMap)); - } -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void AtrousConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); - ar & BOOST_SERIALIZATION_NVP(kW); - ar & BOOST_SERIALIZATION_NVP(kH); - ar & BOOST_SERIALIZATION_NVP(dW); - ar & BOOST_SERIALIZATION_NVP(dH); - ar & BOOST_SERIALIZATION_NVP(padW); - ar & BOOST_SERIALIZATION_NVP(padH); - ar & BOOST_SERIALIZATION_NVP(inputWidth); - ar & BOOST_SERIALIZATION_NVP(inputHeight); - ar & BOOST_SERIALIZATION_NVP(outputWidth); - ar & BOOST_SERIALIZATION_NVP(outputHeight); - ar & BOOST_SERIALIZATION_NVP(dilationW); - ar & BOOST_SERIALIZATION_NVP(dilationH); - - if (Archive::is_loading::value) - weights.set_size((outSize * inSize * kW * kH) + outSize, 1); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/base_layer.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/base_layer.hpp deleted file mode 100644 index cc1059c47..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/base_layer.hpp +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @file base_layer.hpp - * @author Marcus Edel - * - * Definition of the BaseLayer class, which attaches various functions to the - * embedding layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_BASE_LAYER_HPP -#define MLPACK_METHODS_ANN_LAYER_BASE_LAYER_HPP - -#include -#include -#include -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the base layer. The base layer works as a metaclass which - * attaches various functions to the embedding layer. - * - * A few convenience typedefs are given: - * - * - SigmoidLayer - * - IdentityLayer - * - ReLULayer - * - TanHLayer - * - * @tparam ActivationFunction Activation function used for the embedding layer. - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - class ActivationFunction = LogisticFunction, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class BaseLayer -{ - public: - /** - * Create the BaseLayer object. - */ - BaseLayer() - { - // Nothing to do here. - } - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output) - { - ActivationFunction::Fn(input, output); - } - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& input, - arma::Mat&& gy, - arma::Mat&& g) - { - arma::Mat derivative; - ActivationFunction::Deriv(input, derivative); - g = gy % derivative; - } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */) - { - /* Nothing to do here */ - } - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class BaseLayer - -// Convenience typedefs. - -/** - * Standard Sigmoid-Layer using the logistic activation function. - */ -template < - class ActivationFunction = LogisticFunction, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -using SigmoidLayer = BaseLayer< - ActivationFunction, InputDataType, OutputDataType>; - -/** - * Standard Identity-Layer using the identity activation function. - */ -template < - class ActivationFunction = IdentityFunction, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -using IdentityLayer = BaseLayer< - ActivationFunction, InputDataType, OutputDataType>; - -/** - * Standard rectified linear unit non-linearity layer. - */ -template < - class ActivationFunction = RectifierFunction, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -using ReLULayer = BaseLayer< - ActivationFunction, InputDataType, OutputDataType>; - -/** - * Standard hyperbolic tangent layer. - */ -template < - class ActivationFunction = TanhFunction, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -using TanHLayer = BaseLayer< - ActivationFunction, InputDataType, OutputDataType>; - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/batch_norm.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/batch_norm.hpp deleted file mode 100644 index 9dbf168ec..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/batch_norm.hpp +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @file batch_norm.hpp - * @author Praveen Ch - * @author Manthan-R-Sheth - * - * Definition of the Batch Normalization layer class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_BATCHNORM_HPP -#define MLPACK_METHODS_ANN_LAYER_BATCHNORM_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Declaration of the Batch Normalization layer class. The layer transforms - * the input data into zero mean and unit variance and then scales and shifts - * the data by parameters, gamma and beta respectively. These parameters are - * learnt by the network. - * - * If deterministic is false (training), the mean and variance over the batch is - * calculated and the data is normalized. If it is set to true (testing) then - * the mean and variance accrued over the training set is used. - * - * For more information, refer to the following paper, - * - * @code - * @article{Ioffe15, - * author = {Sergey Ioffe and - * Christian Szegedy}, - * title = {Batch Normalization: Accelerating Deep Network Training by - * Reducing Internal Covariate Shift}, - * journal = {CoRR}, - * volume = {abs/1502.03167}, - * year = {2015}, - * url = {http://arxiv.org/abs/1502.03167}, - * eprint = {1502.03167}, - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class BatchNorm -{ - public: - //! Create the BatchNorm object. - BatchNorm(); - - /** - * Create the BatchNorm layer object for a specified number of input units. - * - * @param size The number of input units. - * @param eps The epsilon added to variance to ensure numerical stability. - */ - BatchNorm(const size_t size, const double eps = 1e-8); - - /** - * Reset the layer parameters - */ - void Reset(); - - /** - * Forward pass of the Batch Normalization layer. Transforms the input data - * into zero mean and unit variance, scales the data by a factor gamma and - * shifts it by beta. - * - * @param input Input data for the layer - * @param output Resulting output activations. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Backward pass through the layer. - * - * @param input The input activations - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& input, - arma::Mat&& gy, - arma::Mat&& g); - - /** - * Calculate the gradient using the output delta and the input activations. - * - * @param input The input activations - * @param error The calculated error - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! Get the value of deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of deterministic parameter. - bool& Deterministic() { return deterministic; } - - //! Get the mean over the training data. - OutputDataType TrainingMean() { return runningMean; } - - //! Get the variance over the training data. - OutputDataType TrainingVariance() { return runningVariance / count; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input units. - size_t size; - - //! Locally-stored epsilon value. - double eps; - - //! Whether we are in loading or saving mode. - bool loading; - - //! Locally-stored scale parameter. - OutputDataType gamma; - - //! Locally-stored shift parameter. - OutputDataType beta; - - //! Locally-stored parameters. - OutputDataType weights; - - /** - * If true then mean and variance over the training set will be considered - * instead of being calculated over the batch. - */ - bool deterministic; - - //! Locally-stored running mean/variance counter. - size_t count; - - //! Locally-stored mean object. - OutputDataType mean; - - //! Locally-stored variance object. - OutputDataType variance; - - //! Locally-stored mean object. - OutputDataType runningMean; - - //! Locally-stored variance object. - OutputDataType runningVariance; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored normalized input. - OutputDataType normalized; -}; // class BatchNorm - -} // namespace ann -} // namespace mlpack - -// Include the implementation. -#include "batch_norm_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/batch_norm_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/batch_norm_impl.hpp deleted file mode 100644 index acf7fe229..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/batch_norm_impl.hpp +++ /dev/null @@ -1,171 +0,0 @@ -/** - * @file batch_norm_impl.hpp - * @author Praveen Ch - * @author Manthan-R-Sheth - * - * Implementation of the Batch Normalization Layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_LAYER_BATCHNORM_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_BATCHNORM_IMPL_HPP - -// In case it is not included. -#include "batch_norm.hpp" - -namespace mlpack { -namespace ann { /** Artificial Neural Network. */ - -template -BatchNorm::BatchNorm() : - eps(1e-8), - loading(false), - deterministic(false), - count(0) -{ - // Nothing to do here. -} -template -BatchNorm::BatchNorm( - const size_t size, const double eps) : - size(size), - eps(eps), - loading(false), - deterministic(false), - count(0) -{ - weights.set_size(size + size, 1); - runningMean.zeros(size, 1); - runningVariance.zeros(size, 1); -} - -template -void BatchNorm::Reset() -{ - gamma = arma::mat(weights.memptr(), size, 1, false, false); - beta = arma::mat(weights.memptr() + gamma.n_elem, size, 1, false, false); - - if (!loading) - { - gamma.fill(1.0); - beta.fill(0.0); - } - - deterministic = false; - loading = false; -} - -template -template -void BatchNorm::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - // Mean and variance over the entire training set will be used to compute - // the forward pass when deterministic is set to true. - if (deterministic) - { - // Normalize the input and scale and shift the output. - output = input.each_col() - runningMean; - output.each_col() %= gamma / arma::sqrt(runningVariance / count + eps); - output.each_col() += beta; - } - else - { - mean = arma::mean(input, 1); - variance = arma::var(input, 1, 1); - - // Normalize the input. - output = input.each_col() - mean; - output.each_col() /= arma::sqrt(variance + eps); - - // Use Welford method to compute the sample variance and mean. - for (size_t i = 0; i < input.n_cols; i++) - { - count += 1; - - OutputDataType delta = input.col(i) - runningMean; - runningMean = runningMean + delta / count; - runningVariance += delta % (input.col(i) - runningMean); - } - - // Reused in the backward and gradient step. - normalized = output; - - // Scale and shift the output. - output.each_col() %= gamma; - output.each_col() += beta; - } -} - -template -template -void BatchNorm::Backward( - const arma::Mat&& input, arma::Mat&& gy, arma::Mat&& g) -{ - const arma::mat inputMean = input.each_col() - mean; - const arma::mat stdInv = 1.0 / arma::sqrt(variance + eps); - - // Step 1: dl / dxhat - const arma::mat norm = gy.each_col() % gamma; - - // Step 2: sum dl / dxhat * (x - mu) * -0.5 * stdInv^3. - const arma::mat var = arma::sum(norm % inputMean, 1) % - arma::pow(stdInv, 3.0) * -0.5; - - // Step 4: dl / dxhat * 1 / stdInv + variance * 2 * (x - mu) / m + - // dl / dmu * 1 / m. - g = (norm.each_col() % stdInv) + (inputMean.each_col() % - var * 2 / input.n_cols); - - // Step 3: sum (dl / dxhat * -1 / stdInv) + variance * - // (sum -2 * (x - mu)) / m. - g.each_col() += (arma::sum(norm.each_col() % -stdInv, 1) + (var % - arma::mean(-2 * inputMean, 1))) / input.n_cols; -} - -template -template -void BatchNorm::Gradient( - const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient) -{ - gradient.set_size(size + size, 1); - - // Step 5: dl / dy * xhat. - gradient.submat(0, 0, gamma.n_elem - 1, 0) = arma::sum(normalized % error, 1); - - // Step 6: dl / dy. - gradient.submat(gamma.n_elem, 0, gradient.n_elem - 1, 0) = - arma::sum(error, 1); -} - -template -template -void BatchNorm::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(size); - - if (Archive::is_loading::value) - { - weights.set_size(size + size, 1); - loading = false; - } - - ar & BOOST_SERIALIZATION_NVP(eps); - ar & BOOST_SERIALIZATION_NVP(gamma); - ar & BOOST_SERIALIZATION_NVP(beta); - ar & BOOST_SERIALIZATION_NVP(count); - ar & BOOST_SERIALIZATION_NVP(runningMean); - ar & BOOST_SERIALIZATION_NVP(runningVariance); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/bilinear_interpolation.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/bilinear_interpolation.hpp deleted file mode 100644 index 11305648b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/bilinear_interpolation.hpp +++ /dev/null @@ -1,131 +0,0 @@ -/** - * @file bilinear_interpolation.hpp - * @author Kris Singh and Shikhar Jaiswal - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_BILINEAR_INTERPOLATION_HPP -#define MLPACK_METHODS_ANN_LAYER_BILINEAR_INTERPOLATION_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Definition and Implementation of the Bilinear Interpolation Layer. - * - * Bilinear Interpolation is an mathematical technique, primarily used for - * scaling purposes. It is an extension of linear interpolation, for - * interpolating functions of two variables on a rectangular grid. The key - * idea is to perform linear interpolation first in one direction (e.g., along - * x-axis), and then again in the other direction (i.e., y-axis), on four - * different known points in the grid. This way, we represent any arbitrary - * point, present within the grid, as a function of those four points. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class BilinearInterpolation -{ - public: - //! Create the Bilinear Interpolation object. - BilinearInterpolation(); - - /** - * The constructor for the Bilinear Interpolation. - * - * @param inRowSize Number of input rows. - * @param inColSize Number of input columns. - * @param outRowSize Number of output rows. - * @param outColSize Number of output columns. - * @param depth Number of input slices. - */ - BilinearInterpolation(const size_t inRowSize, - const size_t inColSize, - const size_t outRowSize, - const size_t outColSize, - const size_t depth); - - /** - * Forward pass through the layer. The layer interpolates - * the matrix using the given Bilinear Interpolation method. - * - * @param input The input matrix. - * @param output The resulting interpolated output matrix. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. Since the layer does not have any learn-able parameters, - * we just have to down-sample the gradient to make its size compatible with - * the input size. - * - * @param input The input matrix. - * @param gradient The computed backward gradient. - * @param output The resulting down-sampled output. - */ - template - void Backward(const arma::Mat&& /*input*/, - arma::Mat&& gradient, - arma::Mat&& output); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally stored row size of the input. - size_t inRowSize; - //! Locally stored column size of the input. - size_t inColSize; - //! Locally stored row size of the output. - size_t outRowSize; - //! Locally stored column size of the input. - size_t outColSize; - //! Locally stored depth of the input. - size_t depth; - //! Locally-stored delta object. - OutputDataType delta; - //! Locally-stored input parameter object. - InputDataType inputParameter; - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class BilinearInterpolation - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "bilinear_interpolation_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/bilinear_interpolation_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/bilinear_interpolation_impl.hpp deleted file mode 100644 index b9e728b5e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/bilinear_interpolation_impl.hpp +++ /dev/null @@ -1,185 +0,0 @@ -/** - * @file bilinear_interpolation_impl.hpp - * @author Kris Singh and Shikhar Jaiswal - * - * Implementation of the bilinear interpolation function as an individual layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_BILINEAR_INTERPOLATION_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_BILINEAR_INTERPOLATION_IMPL_HPP - -// In case it hasn't yet been included. -#include "bilinear_interpolation.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - - -template -BilinearInterpolation:: -BilinearInterpolation(): - inRowSize(0), - inColSize(0), - outRowSize(0), - outColSize(0), - depth(0) -{ - // Nothing to do here. -} - -template -BilinearInterpolation:: -BilinearInterpolation( - const size_t inRowSize, - const size_t inColSize, - const size_t outRowSize, - const size_t outColSize, - const size_t depth): - inRowSize(inRowSize), - inColSize(inColSize), - outRowSize(outRowSize), - outColSize(outColSize), - depth(depth) -{ - // Nothing to do here. -} - -template -template -void BilinearInterpolation::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - if (output.is_empty()) - output.set_size(outRowSize * outColSize * depth, 1); - else - { - assert(output.n_rows == outRowSize * outColSize * depth); - assert(output.n_cols == 1); - } - - assert(inRowSize >= 2); - assert(inColSize >= 2); - - arma::cube inputAsCube(input.memptr(), inRowSize, inColSize, depth); - arma::cube outputAsCube(output.memptr(), outRowSize, outColSize, depth, - false, true); - - double scaleRow = (double) inRowSize / (double) outRowSize; - double scaleCol = (double) inColSize / (double) outColSize; - - arma::mat22 coeffs; - for (size_t i = 0; i < outRowSize; i++) - { - size_t rOrigin = (size_t) std::floor(i * scaleRow); - if (rOrigin > inRowSize - 2) - rOrigin = inRowSize - 2; - - // Scaled distance of the interpolated point from the topmost row. - double deltaR = i * scaleRow - rOrigin; - if (deltaR > 1) - deltaR = 1.0; - for (size_t j = 0; j < outColSize; j++) - { - // Scaled distance of the interpolated point from the leftmost column. - size_t cOrigin = (size_t) std::floor(j * scaleCol); - if (cOrigin > inColSize - 2) - cOrigin = inColSize - 2; - - double deltaC = j * scaleCol - cOrigin; - if (deltaC > 1) - deltaC = 1.0; - coeffs[0] = (1 - deltaR) * (1 - deltaC); - coeffs[1] = deltaR * (1 - deltaC); - coeffs[2] = (1 - deltaR) * deltaC; - coeffs[3] = deltaR * deltaC; - - for (size_t k = 0; k < depth; k++) - { - outputAsCube(i, j, k) = arma::accu(inputAsCube.slice(k).submat( - rOrigin, cOrigin, rOrigin + 1, cOrigin + 1) % coeffs); - } - } - } -} - -template -template -void BilinearInterpolation::Backward( - const arma::Mat&& /*input*/, - arma::Mat&& gradient, - arma::Mat&& output) -{ - if (output.is_empty()) - output.set_size(inRowSize * inColSize * depth, 1); - else - { - assert(output.n_rows == inRowSize * inColSize * depth); - assert(output.n_cols == 1); - } - - assert(outRowSize >= 2); - assert(outColSize >= 2); - - arma::cube gradientAsCube(gradient.memptr(), outRowSize, outColSize, depth); - arma::cube outputAsCube(output.memptr(), inRowSize, inColSize, depth, false, - true); - - if (gradient.n_elem == output.n_elem) - { - outputAsCube = gradientAsCube; - } - else - { - double scaleRow = (double)(outRowSize) / inRowSize; - double scaleCol = (double)(outColSize) / inColSize; - - arma::mat22 coeffs; - for (size_t i = 0; i < inRowSize; i++) - { - size_t rOrigin = (size_t) std::floor(i * scaleRow); - if (rOrigin > outRowSize - 2) - rOrigin = outRowSize - 2; - double deltaR = i * scaleRow - rOrigin; - for (size_t j = 0; j < inColSize; j++) - { - size_t cOrigin = (size_t) std::floor(j * scaleCol); - - if (cOrigin > outColSize - 2) - cOrigin = outColSize - 2; - - double deltaC = j * scaleCol - cOrigin; - coeffs[0] = (1 - deltaR) * (1 - deltaC); - coeffs[1] = deltaR * (1 - deltaC); - coeffs[2] = (1 - deltaR) * deltaC; - coeffs[3] = deltaR * deltaC; - - for (size_t k = 0; k < depth; k++) - { - outputAsCube(i, j, k) = arma::accu(gradientAsCube.slice(k).submat( - rOrigin, cOrigin, rOrigin + 1, cOrigin + 1) % coeffs); - } - } - } - } -} - -template -template -void BilinearInterpolation::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inRowSize); - ar & BOOST_SERIALIZATION_NVP(inColSize); - ar & BOOST_SERIALIZATION_NVP(outRowSize); - ar & BOOST_SERIALIZATION_NVP(outColSize); - ar & BOOST_SERIALIZATION_NVP(depth); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat.hpp deleted file mode 100644 index 0563f9bf6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat.hpp +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @file concat.hpp - * @author Marcus Edel - * - * Definition of the Concat class, which acts as a concatenation contain. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_CONCAT_HPP -#define MLPACK_METHODS_ANN_LAYER_CONCAT_HPP - -#include - -#include "../visitor/delete_visitor.hpp" -#include "../visitor/delta_visitor.hpp" -#include "../visitor/output_parameter_visitor.hpp" - -#include - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Concat class. The Concat class works as a - * feed-forward fully connected network container which plugs various layers - * together. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam CustomLayers Additional custom layers if required. - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat, - typename... CustomLayers -> -class Concat -{ - public: - /** - * Create the Concat object using the specified parameters. - * - * @param model Expose all network modules. - * @param same Merge the error in the backward pass. - */ - Concat(const bool model = true, const bool same = true); - - /** - * Destroy the layers held by the model. - */ - ~Concat(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, using 3rd-order tensors as - * input, calculating the function f(x) by propagating x backwards through f. - * Using the results from the feed forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& /* gradient */); - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - template - void Add(const LayerType& layer) { network.push_back(new LayerType(layer)); } - - /* - * Add a new module to the model. - * - * @param args The layer parameter. - */ - template - void Add(Args... args) { network.push_back(new LayerType(args...)); } - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - void Add(LayerTypes layer) { network.push_back(layer); } - - //! Return the model modules. - std::vector >& Model() - { - if (model) - { - return network; - } - - return empty; - } - - //! Return the initial point for the optimization. - const arma::mat& Parameters() const { return parameters; } - //! Modify the initial point for the optimization. - arma::mat& Parameters() { return parameters; } - - arma::mat const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - arma::mat& InputParameter() { return inputParameter; } - - //! Get the output parameter. - arma::mat const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - arma::mat& OutputParameter() { return outputParameter; } - - //! Get the delta.e - arma::mat const& Delta() const { return delta; } - //! Modify the delta. - arma::mat& Delta() { return delta; } - - //! Get the gradient. - arma::mat const& Gradient() const { return gradient; } - //! Modify the gradient. - arma::mat& Gradient() { return gradient; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */); - - private: - //! Parameter which indicates if the modules should be exposed. - bool model; - - //! If true merge the error in the backward pass. - bool same; - - //! Locally-stored network modules. - std::vector > network; - - //! Locally-stored model parameters. - arma::mat parameters; - - //! Locally-stored delta visitor. - DeltaVisitor deltaVisitor; - - //! Locally-stored output parameter visitor. - OutputParameterVisitor outputParameterVisitor; - - //! Locally-stored delete visitor. - DeleteVisitor deleteVisitor; - - //! Locally-stored empty list of modules. - std::vector > empty; - - //! Locally-stored delta object. - arma::mat delta; - - //! Locally-stored input parameter object. - arma::mat inputParameter; - - //! Locally-stored output parameter object. - arma::mat outputParameter; - - //! Locally-stored gradient object. - arma::mat gradient; -}; // class Concat - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "concat_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_impl.hpp deleted file mode 100644 index 983440efa..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_impl.hpp +++ /dev/null @@ -1,191 +0,0 @@ -/** - * @file concat_impl.hpp - * @author Marcus Edel - * - * Implementation of the Concat class, which acts as a concatenation contain. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_CONCAT_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_CONCAT_IMPL_HPP - -// In case it hasn't yet been included. -#include "concat.hpp" - -#include "../visitor/forward_visitor.hpp" -#include "../visitor/backward_visitor.hpp" -#include "../visitor/gradient_visitor.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Concat::Concat( - const bool model, const bool same) : model(model), same(same) -{ - parameters.set_size(0, 0); -} - -template -Concat::~Concat() -{ - // Clear memory. - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deleteVisitor)); -} - -template -template -void Concat::Forward( - arma::Mat&& input, arma::Mat&& output) -{ - size_t outSize = 0; - - for (size_t i = 0; i < network.size(); ++i) - { - boost::apply_visitor(ForwardVisitor(std::move(input), std::move( - boost::apply_visitor(outputParameterVisitor, network[i]))), - network[i]); - - if (boost::apply_visitor( - outputParameterVisitor, network[i]).n_elem > outSize) - { - outSize = boost::apply_visitor(outputParameterVisitor, - network[i]).n_elem; - } - } - - output = arma::zeros(outSize, network.size()); - for (size_t i = 0; i < network.size(); ++i) - { - size_t elements = boost::apply_visitor(outputParameterVisitor, - network[i]).n_elem; - - if (elements < outSize) - { - output.submat(0, i, elements - 1, i) = arma::vectorise( - boost::apply_visitor(outputParameterVisitor, network[i])); - } - else - { - output.col(i) = arma::vectorise(boost::apply_visitor( - outputParameterVisitor, network[i])); - } - } -} - -template -template -void Concat::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - size_t outSize = 0; - size_t elements = 0; - - for (size_t i = 0, j = 0; i < network.size(); ++i, j += elements) - { - elements = boost::apply_visitor(outputParameterVisitor, - network[i]).n_elem; - - arma::mat delta; - if (gy.n_cols == 1) - { - delta = gy.submat(j, 0, j + elements - 1, 0); - } - else - { - delta = gy.submat(0, i, elements - 1, i); - } - - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[i])), std::move(delta), std::move( - boost::apply_visitor(deltaVisitor, network[i]))), network[i]); - - if (boost::apply_visitor(deltaVisitor, network[i]).n_elem > outSize) - { - outSize = boost::apply_visitor(deltaVisitor, network[i]).n_elem; - } - - if (same) - { - if (i == 0) - { - g = std::move(boost::apply_visitor(deltaVisitor, network[i])); - } - else - { - g += std::move(boost::apply_visitor(deltaVisitor, network[i])); - } - } - } - - if (!same) - { - g = arma::zeros(outSize, network.size()); - for (size_t i = 0; i < network.size(); ++i) - { - size_t elements = boost::apply_visitor(deltaVisitor, network[i]).n_elem; - if (elements < outSize) - { - g.submat(0, i, elements - 1, i) = arma::vectorise( - boost::apply_visitor(deltaVisitor, network[i])); - } - else - { - g.col(i) = arma::vectorise( - boost::apply_visitor(deltaVisitor, network[i])); - } - } - } -} - -template -template -void Concat::Gradient( - arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& /* gradient */) -{ - for (size_t i = 0; i < network.size(); ++i) - { - boost::apply_visitor(GradientVisitor(std::move(input), - std::move(error)), network[i]); - } -} - -template -template -void Concat::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(model); - ar & BOOST_SERIALIZATION_NVP(same); - - // Do we have to load or save a model? - if (model) - { - // Clear memory first, if needed. - if (Archive::is_loading::value) - { - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deleteVisitor)); - } - - ar & BOOST_SERIALIZATION_NVP(network); - } -} - -} // namespace ann -} // namespace mlpack - - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_performance.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_performance.hpp deleted file mode 100644 index 121bc2a7f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_performance.hpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @file concat_performance.hpp - * @author Marcus Edel - * - * Definition of the ConcatPerformance class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_CONCAT_PERFORMANCE_HPP -#define MLPACK_METHODS_ANN_LAYER_CONCAT_PERFORMANCE_HPP - -#include - -#include - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the concat performance class. The class works as a - * feed-forward fully connected network container which plugs performance layers - * together. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename OutputLayerType = NegativeLogLikelihood<>, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class ConcatPerformance -{ - public: - /** - * Create the ConcatPerformance object. - * - * @param inSize The number of inputs. - * @param outputLayer Output layer used to evaluate the network. - */ - ConcatPerformance(const size_t inSize = 0, - OutputLayerType&& outputLayer = OutputLayerType()); - - /* - * Computes the Negative log likelihood. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - double Forward(const arma::Mat&& input, arma::Mat&& target); - /** - * Ordinary feed backward pass of a neural network. The negative log - * likelihood layer expectes that the input contains log-probabilities for - * each class. The layer also expects a class index, in the range between 1 - * and the number of classes, as target when calling the Forward function. - * - * @param input The propagated input activation. - * @param target The target vector, that contains the class index in the range - * between 1 and the number of classes. - * @param output The calculated error. - */ - template - void Backward(const arma::Mat&& input, - const arma::Mat&& target, - arma::Mat&& output); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */); - - private: - //! Locally-stored number of inputs. - size_t inSize; - - //! Instantiated outputlayer used to evaluate the network. - OutputLayerType outputLayer; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class ConcatPerformance - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "concat_performance_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_performance_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_performance_impl.hpp deleted file mode 100644 index b4c2d6b9e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/concat_performance_impl.hpp +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @file concat_performance_impl.hpp - * @author Marcus Edel - * - * Implementation of the ConcatPerformance class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_CONCAT_PERFORMANCE_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_CONCAT_PERFORMANCE_IMPL_HPP - -// In case it hasn't yet been included. -#include "concat_performance.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template< - typename OutputLayerType, - typename InputDataType, - typename OutputDataType -> -ConcatPerformance< - OutputLayerType, - InputDataType, - OutputDataType ->::ConcatPerformance(const size_t inSize, OutputLayerType&& outputLayer) : - inSize(inSize), - outputLayer(std::move(outputLayer)) -{ - // Nothing to do here. -} - -template< - typename OutputLayerType, - typename InputDataType, - typename OutputDataType -> -template -double ConcatPerformance< - OutputLayerType, - InputDataType, - OutputDataType ->::Forward(const arma::Mat&& input, arma::Mat&& target) -{ - const size_t elements = input.n_elem / inSize; - - double output = 0; - for (size_t i = 0; i < input.n_elem; i+= elements) - { - arma::mat subInput = input.submat(i, 0, i + elements - 1, 0); - output += outputLayer.Forward(std::move(subInput), std::move(target)); - } - - return output; -} - -template< - typename OutputLayerType, - typename InputDataType, - typename OutputDataType -> -template -void ConcatPerformance< - OutputLayerType, - InputDataType, - OutputDataType ->::Backward( - const arma::Mat&& input, - const arma::Mat&& target, - arma::Mat&& output) -{ - const size_t elements = input.n_elem / inSize; - - arma::mat subInput = input.submat(0, 0, elements - 1, 0); - arma::mat subOutput; - - outputLayer.Backward(std::move(subInput), std::move(target), - std::move(subOutput)); - - output = arma::zeros(subOutput.n_elem, inSize); - output.col(0) = subOutput; - - for (size_t i = elements, j = 0; i < input.n_elem; i+= elements, j++) - { - subInput = input.submat(i, 0, i + elements - 1, 0); - outputLayer.Backward(std::move(subInput), std::move(target), - std::move(subOutput)); - - output.col(j) = subOutput; - } -} - -template< - typename OutputLayerType, - typename InputDataType, - typename OutputDataType -> -template -void ConcatPerformance< - OutputLayerType, - InputDataType, - OutputDataType ->::serialize(Archive& /* ar */, const unsigned int /* version */) -{ - // Nothing to do here. -} - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "concat_performance_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/constant.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/constant.hpp deleted file mode 100644 index 03d5a9014..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/constant.hpp +++ /dev/null @@ -1,116 +0,0 @@ -/** - * @file constant.hpp - * @author Marcus Edel - * - * Definition of the Constant class, which outputs a constant value given - * any input. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_CONSTANT_HPP -#define MLPACK_METHODS_ANN_LAYER_CONSTANT_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the constant layer. The constant layer outputs a given - * constant value given any input value. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class Constant -{ - public: - /** - * Create the Constant object that outputs a given constant scalar value - * given any input value. - * - * @param outSize The number of output units. - * @param scalar The constant value used to create the constant output. - */ - Constant(const size_t outSize = 0, const double scalar = 0.0); - - /** - * Ordinary feed forward pass of a neural network. The forward pass fills the - * output with the specified constant parameter. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network. The backward pass of the - * constant layer is returns always a zero output error matrix. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const DataType&& /* input */, - DataType&& /* gy */, - DataType&& g); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored constant output matrix. - OutputDataType constantOutput; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class ConstantLayer - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "constant_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/constant_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/constant_impl.hpp deleted file mode 100644 index 429cd4480..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/constant_impl.hpp +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file constant_impl.hpp - * @author Marcus Edel - * - * Implementation of the Constant class, which outputs a constant value given - * any input. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_CONSTANT_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_CONSTANT_IMPL_HPP - -// In case it hasn't yet been included. -#include "constant.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Constant::Constant( - const size_t outSize, - const double scalar) : - inSize(0), - outSize(outSize) -{ - constantOutput = OutputDataType(outSize, 1); - constantOutput.fill(scalar); -} - -template -template -void Constant::Forward( - const InputType&& input, OutputType&& output) -{ - if (inSize == 0) - { - inSize = input.n_elem; - } - - output = constantOutput; -} - -template -template -void Constant::Backward( - const DataType&& /* input */, DataType&& /* gy */, DataType&& g) -{ - g = arma::zeros(inSize, 1); -} - -template -template -void Constant::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(constantOutput); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/convolution.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/convolution.hpp deleted file mode 100644 index 940581c13..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/convolution.hpp +++ /dev/null @@ -1,343 +0,0 @@ -/** - * @file convolution.hpp - * @author Marcus Edel - * - * Definition of the Convolution module class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_CONVOLUTION_HPP -#define MLPACK_METHODS_ANN_LAYER_CONVOLUTION_HPP - -#include - -#include -#include -#include -#include - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Convolution class. The Convolution class represents a - * single layer of a neural network. - * - * @tparam ForwardConvolutionRule Convolution to perform forward process. - * @tparam BackwardConvolutionRule Convolution to perform backward process. - * @tparam GradientConvolutionRule Convolution to calculate gradient. - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename ForwardConvolutionRule = NaiveConvolution, - typename BackwardConvolutionRule = NaiveConvolution, - typename GradientConvolutionRule = NaiveConvolution, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class Convolution -{ - public: - //! Create the Convolution object. - Convolution(); - - /** - * Create the Convolution object using the specified number of input maps, - * output maps, filter size, stride and padding parameter. - * - * @param inSize The number of input maps. - * @param outSize The number of output maps. - * @param kW Width of the filter/kernel. - * @param kH Height of the filter/kernel. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - * @param padW Padding width of the input. - * @param padH Padding height of the input. - * @param inputWidth The width of the input data. - * @param inputHeight The height of the input data. - */ - Convolution(const size_t inSize, - const size_t outSize, - const size_t kW, - const size_t kH, - const size_t dW = 1, - const size_t dH = 1, - const size_t padW = 0, - const size_t padH = 0, - const size_t inputWidth = 0, - const size_t inputHeight = 0); - - /* - * Set the weight and bias term. - */ - void Reset(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! Get the input width. - size_t const& InputWidth() const { return inputWidth; } - //! Modify input the width. - size_t& InputWidth() { return inputWidth; } - - //! Get the input height. - size_t const& InputHeight() const { return inputHeight; } - //! Modify the input height. - size_t& InputHeight() { return inputHeight; } - - //! Get the output width. - size_t const& OutputWidth() const { return outputWidth; } - //! Modify the output width. - size_t& OutputWidth() { return outputWidth; } - - //! Get the output height. - size_t const& OutputHeight() const { return outputHeight; } - //! Modify the output height. - size_t& OutputHeight() { return outputHeight; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /* - * Return the convolution output size. - * - * @param size The size of the input (row or column). - * @param k The size of the filter (width or height). - * @param s The stride size (x or y direction). - * @param p The size of the padding (width or height). - * @return The convolution output size. - */ - size_t ConvOutSize(const size_t size, - const size_t k, - const size_t s, - const size_t p) - { - return std::floor(size + p * 2 - k) / s + 1; - } - - /* - * Rotates a 3rd-order tensor counterclockwise by 180 degrees. - * - * @param input The input data to be rotated. - * @param output The rotated output. - */ - template - void Rotate180(const arma::Cube& input, arma::Cube& output) - { - output = arma::Cube(input.n_rows, input.n_cols, input.n_slices); - - // * left-right flip, up-down flip */ - for (size_t s = 0; s < output.n_slices; s++) - output.slice(s) = arma::fliplr(arma::flipud(input.slice(s))); - } - - /* - * Rotates a dense matrix counterclockwise by 180 degrees. - * - * @param input The input data to be rotated. - * @param output The rotated output. - */ - template - void Rotate180(const arma::Mat& input, arma::Mat& output) - { - // * left-right flip, up-down flip */ - output = arma::fliplr(arma::flipud(input)); - } - - /* - * Pad the given input data. - * - * @param input The input to be padded. - * @param wPad Padding width of the input. - * @param hPad Padding height of the input. - * @param output The padded output data. - */ - template - void Pad(const arma::Mat& input, - size_t wPad, - size_t hPad, - arma::Mat& output) - { - if (output.n_rows != input.n_rows + wPad * 2 || - output.n_cols != input.n_cols + hPad * 2) - { - output = arma::zeros(input.n_rows + wPad * 2, input.n_cols + hPad * 2); - } - - output.submat(wPad, hPad, wPad + input.n_rows - 1, - hPad + input.n_cols - 1) = input; - } - - /* - * Pad the given input data. - * - * @param input The input to be padded. - * @param wPad Padding width of the input. - * @param hPad Padding height of the input. - * @param output The padded output data. - */ - template - void Pad(const arma::Cube& input, - size_t wPad, - size_t hPad, - arma::Cube& output) - { - output = arma::zeros(input.n_rows + wPad * 2, - input.n_cols + hPad * 2, input.n_slices); - - for (size_t i = 0; i < input.n_slices; ++i) - { - Pad(input.slice(i), wPad, hPad, output.slice(i)); - } - } - - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored filter/kernel width. - size_t kW; - - //! Locally-stored filter/kernel height. - size_t kH; - - //! Locally-stored stride of the filter in x-direction. - size_t dW; - - //! Locally-stored stride of the filter in y-direction. - size_t dH; - - //! Locally-stored padding width. - size_t padW; - - //! Locally-stored padding height. - size_t padH; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored weight object. - arma::cube weight; - - //! Locally-stored bias term object. - arma::mat bias; - - //! Locally-stored input width. - size_t inputWidth; - - //! Locally-stored input height. - size_t inputHeight; - - //! Locally-stored output width. - size_t outputWidth; - - //! Locally-stored output height. - size_t outputHeight; - - //! Locally-stored transformed output parameter. - arma::cube outputTemp; - - //! Locally-stored transformed input parameter. - arma::cube inputTemp; - - //! Locally-stored transformed padded input parameter. - arma::cube inputPaddedTemp; - - //! Locally-stored transformed error parameter. - arma::cube gTemp; - - //! Locally-stored transformed gradient parameter. - arma::cube gradientTemp; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class Convolution - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "convolution_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/convolution_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/convolution_impl.hpp deleted file mode 100644 index 0b2618c86..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/convolution_impl.hpp +++ /dev/null @@ -1,327 +0,0 @@ -/** - * @file convolution_impl.hpp - * @author Marcus Edel - * - * Implementation of the Convolution module class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_CONVOLUTION_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_CONVOLUTION_IMPL_HPP - -// In case it hasn't yet been included. -#include "convolution.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -Convolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Convolution() -{ - // Nothing to do here. -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -Convolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Convolution( - const size_t inSize, - const size_t outSize, - const size_t kW, - const size_t kH, - const size_t dW, - const size_t dH, - const size_t padW, - const size_t padH, - const size_t inputWidth, - const size_t inputHeight) : - inSize(inSize), - outSize(outSize), - kW(kW), - kH(kH), - dW(dW), - dH(dH), - padW(padW), - padH(padH), - inputWidth(inputWidth), - inputHeight(inputHeight), - outputWidth(0), - outputHeight(0) -{ - weights.set_size((outSize * inSize * kW * kH) + outSize, 1); -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -void Convolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Reset() -{ - weight = arma::cube(weights.memptr(), kW, kH, - outSize * inSize, false, false); - bias = arma::mat(weights.memptr() + weight.n_elem, - outSize, 1, false, false); -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void Convolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Forward(const arma::Mat&& input, arma::Mat&& output) -{ - inputTemp = arma::cube(input.memptr(), inputWidth, inputHeight, inSize); - - if (padW != 0 || padH != 0) - { - Pad(inputTemp, padW, padH, inputPaddedTemp); - } - - size_t wConv = ConvOutSize(inputWidth, kW, dW, padW); - size_t hConv = ConvOutSize(inputHeight, kH, dH, padH); - - output.set_size(wConv * hConv * outSize, 1); - outputTemp = arma::Cube(output.memptr(), wConv, hConv, outSize, - false, false); - outputTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0; inMap < inSize; inMap++, outMapIdx++) - { - arma::Mat convOutput; - - if (padW != 0 || padH != 0) - { - ForwardConvolutionRule::Convolution(inputPaddedTemp.slice(inMap), - weight.slice(outMapIdx), convOutput, dW, dH); - } - else - { - ForwardConvolutionRule::Convolution(inputTemp.slice(inMap), - weight.slice(outMapIdx), convOutput, dW, dH); - } - - outputTemp.slice(outMap) += convOutput; - } - - outputTemp.slice(outMap) += bias(outMap); - } - - outputWidth = outputTemp.n_rows; - outputHeight = outputTemp.n_cols; -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void Convolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - arma::cube mappedError(gy.memptr(), outputWidth, outputHeight, outSize, - false, false); - - g.set_size(inputTemp.n_rows * inputTemp.n_cols * inputTemp.n_slices, 1); - gTemp = arma::Cube(g.memptr(), inputTemp.n_rows, - inputTemp.n_cols, inputTemp.n_slices, false, false); - gTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0; inMap < inSize; inMap++, outMapIdx++) - { - arma::Mat rotatedFilter; - Rotate180(weight.slice(outMapIdx), rotatedFilter); - - arma::Mat output; - BackwardConvolutionRule::Convolution(mappedError.slice(outMap), - rotatedFilter, output, dW, dH); - - if (padW != 0 || padH != 0) - { - gTemp.slice(inMap) += output.submat(rotatedFilter.n_rows / 2, - rotatedFilter.n_cols / 2, - rotatedFilter.n_rows / 2 + gTemp.n_rows - 1, - rotatedFilter.n_cols / 2 + gTemp.n_cols - 1); - } - else - { - gTemp.slice(inMap) += output; - } - } - } -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void Convolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Gradient( - const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient) -{ - arma::cube mappedError; - if (padW != 0 && padH != 0) - { - mappedError = arma::cube(error.memptr(), outputWidth / padW, - outputHeight / padH, outSize); - } - else - { - mappedError = arma::cube(error.memptr(), outputWidth, - outputHeight, outSize); - } - - gradient.set_size(weights.n_elem, 1); - gradientTemp = arma::Cube(gradient.memptr(), weight.n_rows, weight.n_cols, - weight.n_slices, false, false); - gradientTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0, s = outMap; inMap < inSize; inMap++, outMapIdx++, - s += outSize) - { - arma::Cube inputSlices; - if (padW != 0 || padH != 0) - { - inputSlices = inputPaddedTemp.slices(inMap, inMap); - } - else - { - inputSlices = inputTemp.slices(inMap, inMap); - } - - arma::Cube deltaSlices = mappedError.slices(outMap, outMap); - - arma::Cube output; - GradientConvolutionRule::Convolution(inputSlices, deltaSlices, - output, dW, dH); - - if ((padW != 0 || padH != 0) && - (gradientTemp.n_rows < output.n_rows && - gradientTemp.n_cols < output.n_cols)) - { - for (size_t i = 0; i < output.n_slices; i++) - { - gradientTemp.slice(s) += output.slice(i).submat(output.n_rows / 2, - output.n_cols / 2, - output.n_rows / 2 + gradientTemp.n_rows - 1, - output.n_cols / 2 + gradientTemp.n_cols - 1); - } - } - else - { - for (size_t i = 0; i < output.n_slices; i++) - gradientTemp.slice(s) += output.slice(i); - } - } - - gradient.submat(weight.n_elem + outMap, 0, weight.n_elem + outMap, 0) = - arma::accu(mappedError.slices(outMap, outMap)); - } -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void Convolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); - ar & BOOST_SERIALIZATION_NVP(kW); - ar & BOOST_SERIALIZATION_NVP(kH); - ar & BOOST_SERIALIZATION_NVP(dW); - ar & BOOST_SERIALIZATION_NVP(dH); - ar & BOOST_SERIALIZATION_NVP(padW); - ar & BOOST_SERIALIZATION_NVP(padH); - ar & BOOST_SERIALIZATION_NVP(inputWidth); - ar & BOOST_SERIALIZATION_NVP(inputHeight); - ar & BOOST_SERIALIZATION_NVP(outputWidth); - ar & BOOST_SERIALIZATION_NVP(outputHeight); - - if (Archive::is_loading::value) - weights.set_size((outSize * inSize * kW * kH) + outSize, 1); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropconnect.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropconnect.hpp deleted file mode 100644 index 46bef506f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropconnect.hpp +++ /dev/null @@ -1,209 +0,0 @@ -/** - * @file dropconnect.hpp - * @author Palash Ahuja - * @author Marcus Edel - * - * Definition of the DropConnect class, which implements a regularizer - * that randomly sets connections to zero. Preventing units from co-adapting. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_DROPCONNECT_HPP -#define MLPACK_METHODS_ANN_LAYER_DROPCONNECT_HPP - -#include - -#include "layer_types.hpp" -#include "add_merge.hpp" -#include "linear.hpp" -#include "sequential.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The DropConnect layer is a regularizer that randomly with probability - * ratio sets the connection values to zero and scales the remaining - * elements by factor 1 /(1 - ratio). The output is scaled with 1 / (1 - p) - * when deterministic is false. In the deterministic mode(during testing), - * the layer just computes the output. The output is computed according - * to the input layer. If no input layer is given, it will take a linear layer - * as default. - * - * Note: - * During training you should set deterministic to false and during testing - * you should set deterministic to true. - * - * For more information, see the following. - * - * @code - * @inproceedings{WanICML2013, - * title={Regularization of Neural Networks using DropConnect}, - * booktitle = {Proceedings of the 30th International Conference on Machine - * Learning(ICML - 13)}, - * author = {Li Wan and Matthew Zeiler and Sixin Zhang and Yann L. Cun and - * Rob Fergus}, - * year = {2013} - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template< - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class DropConnect -{ - public: - //! Create the DropConnect object. - DropConnect(); - - /** - * Creates the DropConnect Layer as a Linear Object that takes input size, - * output size and ratio as parameter. - * - * @param inSize The number of input units. - * @param outSize The number of output units. - * @param ratio The probability of setting a value to zero. - */ - DropConnect(const size_t inSize, - const size_t outSize, - const double ratio = 0.5); - - ~DropConnect(); - - /** - * Ordinary feed forward pass of the DropConnect layer. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of the DropConnect layer. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(arma::Mat&& input, - arma::Mat&& gy, - arma::Mat&& g); - - /** - * Calculate the gradient using the output delta and the input activation. - * - * @param input The propagated input. - * @param d The calculated error. - * @param g The calculated gradient. - */ - template - void Gradient(arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& /* gradient */); - - //! Get the model modules. - std::vector >& Model() { return network; } - - //! Get the parameters. - OutputDataType const& Parameters() const { return parameters; } - //! Modify the parameters. - OutputDataType& Parameters() { return parameters; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! The value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - - //! Modify the value of the deterministic parameter. - bool &Deterministic() { return deterministic; } - - //! The probability of setting a value to zero. - double Ratio() const { return ratio; } - - //! Modify the probability of setting a value to zero. - void Ratio(const double r) - { - ratio = r; - scale = 1.0 / (1.0 - ratio); - } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! The probability of setting a value to zero. - double ratio; - - //! The scale fraction. - double scale; - - //! Locally-stored weight object. - OutputDataType parameters; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored mask object. - OutputDataType mask; - - //! If true dropout and scaling is disabled, see notes above. - bool deterministic; - - //! Denoise mask for the weights. - OutputDataType denoise; - - //! Locally-stored layer module. - LayerTypes<> baseLayer; - - //! Locally-stored network modules. - std::vector > network; -}; // class DropConnect. - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "dropconnect_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropconnect_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropconnect_impl.hpp deleted file mode 100644 index 7a3713ac3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropconnect_impl.hpp +++ /dev/null @@ -1,141 +0,0 @@ -/** - * @file dropconnect_impl.hpp - * @author Palash Ahuja - * @author Marcus Edel - * - * Implementation of the DropConnect class, which implements a regularizer - * that randomly sets connections to zero. Preventing units from co-adapting. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_DROPCONNECT_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_DROPCONNECT_IMPL_HPP - -// In case it hasn't yet been included. -#include "dropconnect.hpp" - -#include "../visitor/delete_visitor.hpp" -#include "../visitor/forward_visitor.hpp" -#include "../visitor/backward_visitor.hpp" -#include "../visitor/gradient_visitor.hpp" -#include "../visitor/parameters_set_visitor.hpp" -#include "../visitor/parameters_visitor.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -DropConnect::DropConnect() : - ratio(0.5), - scale(2.0), - deterministic(true) -{ - // Nothing to do here. -} - -template -DropConnect::DropConnect( - const size_t inSize, - const size_t outSize, - const double ratio) : - ratio(ratio), - scale(1.0 / (1 - ratio)), - baseLayer(new Linear(inSize, outSize)) -{ - network.push_back(baseLayer); -} - -template -DropConnect::~DropConnect() -{ - boost::apply_visitor(DeleteVisitor(), baseLayer); -} - -template -template -void DropConnect::Forward( - arma::Mat&& input, - arma::Mat&& output) -{ - // The DropConnect mask will not be multiplied in the deterministic mode - // (during testing). - if (deterministic) - { - boost::apply_visitor(ForwardVisitor(std::move(input), std::move(output)), - baseLayer); - } - else - { - // Save weights for denoising. - boost::apply_visitor(ParametersVisitor(std::move(denoise)), baseLayer); - - // Scale with input / (1 - ratio) and set values to zero with - // probability ratio. - mask = arma::randu >(denoise.n_rows, denoise.n_cols); - mask.transform([&](double val) { return (val > ratio); }); - - boost::apply_visitor(ParametersSetVisitor(std::move(denoise % mask)), - baseLayer); - - boost::apply_visitor(ForwardVisitor(std::move(input), std::move(output)), - baseLayer); - - output = output * scale; - } -} - -template -template -void DropConnect::Backward( - arma::Mat&& input, - arma::Mat&& gy, - arma::Mat&& g) -{ - boost::apply_visitor(BackwardVisitor(std::move(input), std::move(gy), - std::move(g)), baseLayer); -} - -template -template -void DropConnect::Gradient( - arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& /* gradient */) -{ - boost::apply_visitor(GradientVisitor(std::move(input), std::move(error)), - baseLayer); - - // Denoise the weights. - boost::apply_visitor(ParametersSetVisitor(std::move(denoise)), baseLayer); -} - -template -template -void DropConnect::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // Delete the old network first, if needed. - if (Archive::is_loading::value) - { - boost::apply_visitor(DeleteVisitor(), baseLayer); - } - - ar & BOOST_SERIALIZATION_NVP(ratio); - ar & BOOST_SERIALIZATION_NVP(scale); - ar & BOOST_SERIALIZATION_NVP(baseLayer); - - if (Archive::is_loading::value) - { - network.clear(); - network.push_back(baseLayer); - } -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropout.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropout.hpp deleted file mode 100644 index a388820c7..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropout.hpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @file dropout.hpp - * @author Marcus Edel - * - * Definition of the Dropout class, which implements a regularizer that - * randomly sets units to zero preventing units from co-adapting. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_DROPOUT_HPP -#define MLPACK_METHODS_ANN_LAYER_DROPOUT_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - - -/** - * The dropout layer is a regularizer that randomly with probability 'ratio' - * sets input values to zero and scales the remaining elements by factor 1 / - * (1 - ratio) rather than during test time so as to keep the expected sum same. - * In the deterministic mode (during testing), there is no change in the input. - * - * Note: During training you should set deterministic to false and during - * testing you should set deterministic to true. - * - * For more information, see the following. - * - * @code - * @article{Hinton2012, - * author = {Geoffrey E. Hinton, Nitish Srivastava, Alex Krizhevsky, - * Ilya Sutskever, Ruslan Salakhutdinov}, - * title = {Improving neural networks by preventing co-adaptation of feature - * detectors}, - * journal = {CoRR}, - * volume = {abs/1207.0580}, - * year = {2012}, - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template -class Dropout -{ - public: - /** - * Create the Dropout object using the specified ratio parameter. - * - * @param ratio The probability of setting a value to zero. - */ - Dropout(const double ratio = 0.5); - - /** - * Ordinary feed forward pass of the dropout layer. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of the dropout layer. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the detla. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! The value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - //! The probability of setting a value to zero. - double Ratio() const { return ratio; } - - //! Modify the probability of setting a value to zero. - void Ratio(const double r) - { - ratio = r; - scale = 1.0 / (1.0 - ratio); - } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored mast object. - OutputDataType mask; - - //! The probability of setting a value to zero. - double ratio; - - //! The scale fraction. - double scale; - - //! If true dropout and scaling is disabled, see notes above. - bool deterministic; -}; // class Dropout - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "dropout_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropout_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropout_impl.hpp deleted file mode 100644 index ccac9588f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/dropout_impl.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file dropout_impl.hpp - * @author Marcus Edel - * - * Implementation of the Dropout class, which implements a regularizer that - * randomly sets units to zero. Preventing units from co-adapting. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_DROPOUT_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_DROPOUT_IMPL_HPP - -// In case it hasn't yet been included. -#include "dropout.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Dropout::Dropout( - const double ratio) : - ratio(ratio), - scale(1.0 / (1.0 - ratio)), - deterministic(false) -{ - // Nothing to do here. -} - -template -template -void Dropout::Forward( - const arma::Mat&& input, - arma::Mat&& output) -{ - // The dropout mask will not be multiplied in the deterministic mode - // (during testing). - if (deterministic) - { - output = input; - } - else - { - // Scale with input / (1 - ratio) and set values to zero with probability - // 'ratio'. - mask = arma::randu >(input.n_rows, input.n_cols); - mask.transform([&](double val) { return (val > ratio); }); - output = input % mask * scale; - } -} - -template -template -void Dropout::Backward( - const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g) -{ - g = gy % mask * scale; -} - -template -template -void Dropout::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(ratio); - - // Reset scale. - scale = 1.0 / (1.0 - ratio); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/elu.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/elu.hpp deleted file mode 100644 index 46ddf476d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/elu.hpp +++ /dev/null @@ -1,267 +0,0 @@ -/** - * @file elu.hpp - * @author Vivek Pal - * @author Dakshit Agrawal - * - * Definition of the ELU activation function as descibed by Djork-Arne Clevert, - * Thomas Unterthiner and Sepp Hochreiter. - * - * Definition of the SELU function as introduced by - * Klambauer et. al. in Self Neural Networks. The SELU activation - * function keeps the mean and variance of the input invariant. - * - * In short, SELU = lambda * ELU, with 'alpha' and 'lambda' fixed for - * normalized inputs. - * - * Hence both ELU and SELU are implemented in the same file, with - * lambda = 1 for ELU function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_ELU_HPP -#define MLPACK_METHODS_ANN_LAYER_ELU_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The ELU activation function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \left\{ - * \begin{array}{lr} - * x & : x > 0 \\ - * \alpha(e^x - 1) & : x \le 0 - * \end{array} - * \right. \\ - * f'(x) &=& \left\{ - * \begin{array}{lr} - * 1 & : x > 0 \\ - * y + \alpha & : x \le 0 - * \end{array} - * \right. - * @f} - * - * For more information, read the following paper: - * - * @code - * @article{Clevert2015, - * author = {Djork{-}Arn{\'{e}} Clevert and Thomas Unterthiner and - * Sepp Hochreiter}, - * title = {Fast and Accurate Deep Network Learning by Exponential Linear - * Units (ELUs)}, - * journal = {CoRR}, - * year = {2015} - * } - * @endcode - * - * - * The SELU activation function is defined by - * - * @f{eqnarray*}{ - * f(x) &=& \left\{ - * \begin{array}{lr} - * \lambda * x & : x > 0 \\ - * \lambda * \alpha(e^x - 1) & : x \le 0 - * \end{array} - * \right. \\ - * f'(x) &=& \left\{ - * \begin{array}{lr} - * \lambda & : x > 0 \\ - * \lambda * (y + \alpha) & : x \le 0 - * \end{array} - * \right. - * @f} - * - * For more information, read the following paper: - * - * @code - * @article{Klambauer2017, - * author = {Gunter Klambauer and Thomas Unterthiner and - * Andreas Mayr}, - * title = {Self-Normalizing Neural Networks}, - * journal = {Advances in Neural Information Processing Systems}, - * year = {2017} - * } - * @endcode - * - * @note Make sure to use SELU activation function with normalized inputs and - * weights initialized with Lecun Normal Initialization. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class ELU -{ - public: - /** - * Create the ELU object. - * - * NOTE: Use this constructor for SELU activation function. - */ - ELU(); - - /** - * Create the ELU object using the specified parameter. The non zero - * gradient for negative inputs can be adjusted by specifying the ELU - * hyperparameter alpha (alpha > 0). - * - * @note Use this constructor for ELU activation function. - * @param alpha Scale parameter for the negative factor. - */ - ELU(const double alpha); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const DataType&& input, DataType&& gy, DataType&& g); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the non zero gradient. - double const& Alpha() const { return alpha; } - //! Modify the non zero gradient. - double& Alpha() { return alpha; } - - //! Get the lambda parameter. - double const& Lambda() const { return lambda; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /** - * Computes the value of activation function. - * - * @param x Input data. - * @return f(x). - */ - double Fn(const double x) - { - if (x < DBL_MAX) - { - return (x > 0) ? lambda * x : lambda * alpha * (std::exp(x) - 1); - } - - return 1.0; - } - - /** - * Computes the value of activation function using a dense matrix as input. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - void Fn(const arma::Mat& x, arma::Mat& y) - { - y.set_size(arma::size(x)); - - for (size_t i = 0; i < x.n_elem; i++) - { - y(i) = Fn(x(i)); - } - } - - /** - * Computes the first derivative of the activation function. - * - * @param x Input data. - * @return f'(x) - */ - double Deriv(const double y) - { - return (y > 0) ? lambda : lambda * (y + alpha); - } - - /** - * Computes the first derivative of the activation function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - template - void Deriv(const InputType& x, OutputType& y) - { - y = x; - - for (size_t i = 0; i < x.n_elem; i++) - { - y(i) = Deriv(x(i)); - } - } - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! ELU Hyperparameter (0 < alpha) - //! SELU parameter fixed to 1.6732632423543774 for normalized inputs. - double alpha; - - //! Lambda Parameter used for multiplication of ELU function. - //! For ELU activation function, lambda = 1. - //! For SELU activation function, lambda = 1.0507009873554802 for normalized - //! inputs. - double lambda; -}; // class ELU - -// Template alias for SELU using ELU class. -using SELU = ELU; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "elu_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/elu_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/elu_impl.hpp deleted file mode 100644 index 5c23dee08..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/elu_impl.hpp +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @file elu_impl.hpp - * @author Vivek Pal - * @author Dakshit Agrawal - * - * Implementation of the ELU activation function as descibed by Djork-Arne - * Clevert, Thomas Unterthiner and Sepp Hochreiter. - * - * Implementation of the SELU function as introduced by Klambauer et. al. in - * Self Neural Networks. The SELU activation function keeps the mean and - * variance of the input invariant. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_ELU_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_ELU_IMPL_HPP - -// In case it hasn't yet been included. -#include "elu.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -// This constructor is called for SELU activation function. The values of -// alpha and lambda are constant for normalized inputs. -template -ELU::ELU() : - alpha(1.6732632423543774), - lambda(1.0507009873554802) -{ - // Nothing to do here. -} - -// This constructor is called for ELU activation function. The value of lambda -// is fixed and equal to 1. 'alpha' is a hyperparameter. -template -ELU::ELU(const double alpha) : - alpha(alpha), lambda(1) -{ - // Nothing to do here. -} - -template -template -void ELU::Forward( - const InputType&& input, OutputType&& output) -{ - Fn(input, output); -} - -template -template -void ELU::Backward( - const DataType&& input, DataType&& gy, DataType&& g) -{ - DataType derivative; - Deriv(input, derivative); - g = gy % derivative; -} - -template -template -void ELU::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(alpha); - ar & BOOST_SERIALIZATION_NVP(lambda); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/fast_lstm.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/fast_lstm.hpp deleted file mode 100644 index e853bb16d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/fast_lstm.hpp +++ /dev/null @@ -1,309 +0,0 @@ -/** - * @file fast_lstm.hpp - * @author Marcus Edel - * - * Definition of the Fast LSTM class, which implements a Fast LSTM network - * layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_FAST_LSTM_HPP -#define MLPACK_METHODS_ANN_LAYER_FAST_LSTM_HPP - -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * An implementation of a faster version of the Fast LSTM network layer. - * Basically by combining the calculation of the input, forget, output gates - * and hidden state in a single step. The standard formula changes as follows: - * - * @f{eqnarray}{ - * i &=& sigmoid(W \cdot x + W \cdot h + b) \\ - * f &=& sigmoid(W \cdot x + W \cdot h + b) \\ - * z &=& tanh(W \cdot x + W \cdot h + b) \\ - * c &=& f \cdot c + i \cdot z \\ - * o &=& sigmoid(W \cdot x + W \cdot h + b) \\ - * h &=& o \cdot tanh(c) - * @f} - * - * Note that FastLSTM network layer does not use peephole connections between - * the cell and gates. - * - * For more information, see the following. - * - * @code - * @article{Hochreiter1997, - * author = {Hochreiter, Sepp and Schmidhuber, J\"{u}rgen}, - * title = {Long Short-term Memory}, - * journal = {Neural Comput.}, - * year = {1997} - * } - * @endcode - * - * \see LSTM for a standard implementation of the LSTM layer. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class FastLSTM -{ - public: - // Convenience typedefs. - typedef typename InputDataType::elem_type InputElemType; - typedef typename OutputDataType::elem_type ElemType; - - //! Create the Fast LSTM object. - FastLSTM(); - - /** - * Create the Fast LSTM layer object using the specified parameters. - * - * @param inSize The number of input units. - * @param outSize The number of output units. - * @param rho Maximum number of steps to backpropagate through time (BPTT). - */ - FastLSTM(const size_t inSize, - const size_t outSize, - const size_t rho = std::numeric_limits::max()); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const InputType&& input, - ErrorType&& gy, - GradientType&& g); - - /* - * Reset the layer parameter. - */ - void Reset(); - - /* - * Resets the cell to accept a new input. This breaks the BPTT chain starts a - * new one. - * - * @param size The current maximum number of steps through time. - */ - void ResetCell(const size_t size); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(InputType&& input, - ErrorType&& error, - GradientType&& gradient); - - //! Get the maximum number of steps to backpropagate through time (BPTT). - size_t Rho() const { return rho; } - //! Modify the maximum number of steps to backpropagate through time (BPTT). - size_t& Rho() { return rho; } - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return grad; } - //! Modify the gradient. - OutputDataType& Gradient() { return grad; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /** - * This speeds up the sigmoid operation by using an approximation. - * - * @param input The input data. - * @param sigmoid The matrix to store the sigmoid approximation into. - */ - template - void FastSigmoid(InputType&& input, OutputType&& sigmoids) - { - for (size_t i = 0; i < input.n_elem; ++i) - sigmoids(i) = FastSigmoid(input(i)); - } - - /** - * Sigmoid approximation for the given sample. - * - * @param data The given data sample for the sigmoid approximation. - * @tparam The sigmoid approximation. - */ - ElemType FastSigmoid(const InputElemType data) - { - ElemType x = 0.5 * data; - ElemType z; - if (x >= 0) - { - if (x < 1.7) - z = (1.5 * x / (1 + x)); - else if (x < 3) - z = (0.935409070603099 + 0.0458812946797165 * (x - 1.7)); - else - z = 0.99505475368673; - } - else - { - ElemType xx = -x; - if (xx < 1.7) - z = -(1.5 * xx / (1 + xx)); - else if (xx < 3) - z = -(0.935409070603099 + 0.0458812946797165 * (xx - 1.7)); - else - z = -0.99505475368673; - } - - return 0.5 * (z + 1.0); - } - - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Number of steps to backpropagate through time (BPTT). - size_t rho; - - //! Locally-stored number of forward steps. - size_t forwardStep; - - //! Locally-stored number of backward steps. - size_t backwardStep; - - //! Locally-stored number of gradient steps. - size_t gradientStep; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored previous output. - OutputDataType prevOutput; - - //! Locally-stored batch size. - size_t batchSize; - - //! Current batch step, alias for batchSize - 1. - size_t batchStep; - - //! Current gradient step to keep track of the backpropagate through time - //! step. - size_t gradientStepIdx; - - //! Locally-stored cell activation error. - OutputDataType cellActivationError; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType grad; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Weights between the output and gate. - OutputDataType output2GateWeight; - - //! Weights between the input and gate. - OutputDataType input2GateWeight; - - //! Bias between the input and gate. - OutputDataType input2GateBias; - - //! Locally-stored gate parameter. - OutputDataType gate; - - //! Locally-stored gate activation. - OutputDataType gateActivation; - - //! Locally-stored state activation. - OutputDataType stateActivation; - - //! Locally-stored cell parameter. - OutputDataType cell; - - //! Locally-stored cell activation error. - OutputDataType cellActivation; - - //! Locally-stored foget gate error. - OutputDataType forgetGateError; - - //! Locally-stored previous error. - OutputDataType prevError; - - //! Locally-stored output parameters. - OutputDataType outParameter; - - //! Locally-stored current rho size. - size_t rhoSize; - - //! Current backpropagate through time steps. - size_t bpttSteps; -}; // class FastLSTM - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "fast_lstm_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/fast_lstm_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/fast_lstm_impl.hpp deleted file mode 100644 index 36d92c2a0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/fast_lstm_impl.hpp +++ /dev/null @@ -1,300 +0,0 @@ -/** - * @file fast_lstm_impl.hpp - * @author Marcus Edel - * - * Implementation of the Fast LSTM class, which implements a fast lstm network - * layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_FAST_LSTM_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_FAST_LSTM_IMPL_HPP - -// In case it hasn't yet been included. -#include "fast_lstm.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -FastLSTM::FastLSTM() -{ - // Nothing to do here. -} - -template -FastLSTM::FastLSTM( - const size_t inSize, const size_t outSize, const size_t rho) : - inSize(inSize), - outSize(outSize), - rho(rho), - forwardStep(0), - backwardStep(0), - gradientStep(0), - batchSize(0), - batchStep(0), - gradientStepIdx(0), - rhoSize(rho), - bpttSteps(0) -{ - // Weights for: input to gate layer (4 * outsize * inSize + 4 * outsize) - // and output to gate (4 * outSize). - weights.set_size( - 4 * outSize * inSize + 4 * outSize + 4 * outSize * outSize, 1); -} - -template -void FastLSTM::Reset() -{ - // Set the weight parameter for the input to gate layer (linear layer) using - // the overall layer parameter matrix. - input2GateWeight = OutputDataType(weights.memptr(), - 4 * outSize, inSize, false, false); - input2GateBias = OutputDataType(weights.memptr() + input2GateWeight.n_elem, - 4 * outSize, 1, false, false); - - // Set the weight parameter for the output to gate layer - // (linear no bias layer) using the overall layer parameter matrix. - output2GateWeight = OutputDataType(weights.memptr() + input2GateWeight.n_elem - + input2GateBias.n_elem, 4 * outSize, outSize, false, false); -} - -template -void FastLSTM::ResetCell(const size_t size) -{ - if (size == std::numeric_limits::max()) - return; - - rhoSize = size; - - if (batchSize == 0) - return; - - bpttSteps = std::min(rho, rhoSize); - forwardStep = 0; - gradientStepIdx = 0; - backwardStep = batchSize * size - 1; - gradientStep = batchSize * size - 1; - - const size_t rhoBatchSize = size * batchSize; - if (gate.is_empty() || gate.n_cols != rhoBatchSize) - { - gate.set_size(4 * outSize, rhoBatchSize); - gateActivation.set_size(outSize * 3, rhoBatchSize); - stateActivation.set_size(outSize, rhoBatchSize); - cellActivation.set_size(outSize, rhoBatchSize); - prevError.set_size(4 * outSize, batchSize); - - if (prevOutput.is_empty()) - { - prevOutput = arma::zeros(outSize, batchSize); - cell = arma::zeros(outSize, size * batchSize); - cellActivationError = arma::zeros(outSize, batchSize); - outParameter = arma::zeros( - outSize, (size + 1) * batchSize); - } - else - { - // To preserve the leading zeros, recreate the object according to given - // size specifications, while preserving the elements as well as the - // layout of the elements. - prevOutput.resize(outSize, batchSize); - cell.resize(outSize, size * batchSize); - cellActivationError.resize(outSize, batchSize); - outParameter.resize(outSize, (size + 1) * batchSize); - } - } -} - -template -template -void FastLSTM::Forward( - InputType&& input, OutputType&& output) -{ - // Check if the batch size changed, the number of cols is defines the input - // batch size. - if (input.n_cols != batchSize) - { - batchSize = input.n_cols; - batchStep = batchSize - 1; - ResetCell(rhoSize); - } - - gate.cols(forwardStep, forwardStep + batchStep) = input2GateWeight * input + - output2GateWeight * outParameter.cols( - forwardStep, forwardStep + batchStep); - gate.cols(forwardStep, forwardStep + batchStep).each_col() += input2GateBias; - - FastSigmoid(std::move( - gate.submat(0, forwardStep, 3 * outSize - 1, forwardStep + batchStep)), - std::move(gateActivation.cols(forwardStep, forwardStep + batchStep))); - - stateActivation.cols(forwardStep, forwardStep + batchStep) = arma::tanh( - gate.submat(3 * outSize, forwardStep, 4 * outSize - 1, - forwardStep + batchStep)); - - // Update the cell: cmul1 + cmul2 - // where cmul1 is input gate * hidden state and - // cmul2 is forget gate * cell (prevCell). - if (forwardStep == 0) - { - cell.cols(forwardStep, forwardStep + batchStep) = - gateActivation.submat(0, forwardStep, outSize - 1, - forwardStep + batchStep) % - stateActivation.cols(forwardStep, forwardStep + batchStep); - } - else - { - cell.cols(forwardStep, forwardStep + batchStep) = - gateActivation.submat(0, forwardStep, outSize - 1, - forwardStep + batchStep) % - stateActivation.cols(forwardStep, forwardStep + batchStep) + - gateActivation.submat(2 * outSize, forwardStep, 3 * outSize - 1, - forwardStep + batchStep) % - cell.cols(forwardStep - batchSize, forwardStep - batchSize + batchStep); - } - - cellActivation.cols(forwardStep, forwardStep + batchStep) = - arma::tanh(cell.cols(forwardStep, forwardStep + batchStep)); - - outParameter.cols(forwardStep + batchSize, - forwardStep + batchSize + batchStep) = cellActivation.cols( - forwardStep, forwardStep + batchStep) % gateActivation.submat( - outSize, forwardStep, 2 * outSize - 1, forwardStep + batchStep); - - output = OutputType(outParameter.memptr() + - (forwardStep + batchSize) * outSize, outSize, batchSize, false, false); - - forwardStep += batchSize; - if ((forwardStep / batchSize) == bpttSteps) - { - forwardStep = 0; - } -} - -template -template -void FastLSTM::Backward( - const InputType&& /* input */, ErrorType&& gy, GradientType&& g) -{ - if (gradientStepIdx > 0) - { - gy += output2GateWeight.t() * prevError; - } - - cellActivationError = gy % gateActivation.submat(outSize, - backwardStep - batchStep, 2 * outSize - 1, backwardStep) % - (1 - arma::pow(cellActivation.cols(backwardStep - batchStep, - backwardStep), 2)); - - if (gradientStepIdx > 0) - cellActivationError += forgetGateError; - - forgetGateError = gateActivation.submat(2 * outSize, - backwardStep - batchStep, 3 * outSize - 1, backwardStep) % - cellActivationError; - - if (backwardStep > batchStep) - { - prevError.submat(2 * outSize, 0, 3 * outSize - 1, batchStep) = - cell.cols((backwardStep - batchSize) - batchStep, - (backwardStep - batchSize)) % cellActivationError % - gateActivation.submat(2 * outSize, backwardStep - batchStep, - 3 * outSize - 1, backwardStep) % (1.0 - gateActivation.submat( - 2 * outSize, backwardStep - batchStep, 3 * outSize - 1, backwardStep)); - } - else - { - prevError.submat(2 * outSize, 0, 3 * outSize - 1, batchStep).zeros(); - } - - prevError.submat(0, 0, outSize - 1, batchStep) = - stateActivation.cols(backwardStep - batchStep, - backwardStep) % cellActivationError % gateActivation.submat( - 0, backwardStep - batchStep, outSize - 1, backwardStep) % - (1.0 - gateActivation.submat( - 0, backwardStep - batchStep, outSize - 1, backwardStep)); - - prevError.submat(3 * outSize, 0, 4 * outSize - 1, batchStep) = - gateActivation.submat(0, backwardStep - batchStep, - outSize - 1, backwardStep) % cellActivationError % (1 - arma::pow( - stateActivation.cols(backwardStep - batchStep, backwardStep), 2)); - - prevError.submat(outSize, 0, 2 * outSize - 1, batchStep) = - cellActivation.cols(backwardStep - batchStep, - backwardStep) % gy % gateActivation.submat( - outSize, backwardStep - batchStep, 2 * outSize - 1, backwardStep) % - (1.0 - gateActivation.submat( - outSize, backwardStep - batchStep, 2 * outSize - 1, backwardStep)); - - g = input2GateWeight.t() * prevError; - - backwardStep -= batchSize; - gradientStepIdx++; - if (gradientStepIdx == bpttSteps) - { - backwardStep = bpttSteps - 1; - gradientStepIdx = 0; - } -} - -template -template -void FastLSTM::Gradient( - InputType&& input, ErrorType&& /* error */, GradientType&& gradient) -{ - // Gradient of the input to gate layer. - gradient.submat(0, 0, input2GateWeight.n_elem - 1, 0) = - arma::vectorise(prevError * input.t()); - - gradient.submat(input2GateWeight.n_elem, 0, input2GateWeight.n_elem + - input2GateBias.n_elem - 1, 0) = arma::sum(prevError, 1); - - // Gradient of the output to gate layer. - gradient.submat(input2GateWeight.n_elem + input2GateBias.n_elem, 0, - gradient.n_elem - 1, 0) = arma::vectorise(prevError * - outParameter.cols(gradientStep - batchStep, gradientStep).t()); - - if (gradientStep > batchStep) - { - gradientStep -= batchSize; - } - else - { - gradientStep = batchSize * bpttSteps - 1; - } -} - -template -template -void FastLSTM::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(weights); - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); - ar & BOOST_SERIALIZATION_NVP(rho); - ar & BOOST_SERIALIZATION_NVP(bpttSteps); - ar & BOOST_SERIALIZATION_NVP(batchSize); - ar & BOOST_SERIALIZATION_NVP(batchStep); - ar & BOOST_SERIALIZATION_NVP(forwardStep); - ar & BOOST_SERIALIZATION_NVP(backwardStep); - ar & BOOST_SERIALIZATION_NVP(gradientStep); - ar & BOOST_SERIALIZATION_NVP(gradientStepIdx); - ar & BOOST_SERIALIZATION_NVP(cell); - ar & BOOST_SERIALIZATION_NVP(stateActivation); - ar & BOOST_SERIALIZATION_NVP(gateActivation); - ar & BOOST_SERIALIZATION_NVP(gate); - ar & BOOST_SERIALIZATION_NVP(cellActivation); - ar & BOOST_SERIALIZATION_NVP(forgetGateError); - ar & BOOST_SERIALIZATION_NVP(prevError); - ar & BOOST_SERIALIZATION_NVP(outParameter); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/flexible_relu.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/flexible_relu.hpp deleted file mode 100644 index 3117d7dc3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/flexible_relu.hpp +++ /dev/null @@ -1,175 +0,0 @@ -/** - * @file flexible_relu.hpp - * @author Aarush Gupta - * @author Manthan-R-Sheth - * - * Definition of FlexibleReLU layer as described by - * Suo Qiu, Xiangmin Xu and Bolun Cai in - * "FReLU: Flexible Rectified Linear Units for Improving Convolutional - * Neural Networks", 2018 - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_FLEXIBLERELU_HPP -#define MLPACK_METHODS_ANN_LAYER_FLEXIBLERELU_HPP - -#include - -namespace mlpack { -namespace ann /**Artificial Neural Network*/ { - -/** - * The FlexibleReLU activation function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \max(0,x)+alpha \\ - * f'(x) &=& \left\{ - * \begin{array}{lr} - * 1 & : x > 0 \\ - * 0 & : x \le 0 - * \end{array} - * \right. - * @f} - * - * For more information, read the following paper: - * - * @code - * @article{Qiu2018, - * author = {Suo Qiu, Xiangmin Xu and Bolun Cai}, - * title = {FReLU: Flexible Rectified Linear Units for Improving - * Convolutional Neural Networks} - * journal = {arxiv preprint}, - * URL = {https://arxiv.org/abs/1706.08098}, - * year = {2018} - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mar, - * arma::sp_mat or arma::cube) - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube) - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class FlexibleReLU -{ - public: - /** - * - * Create the FlexibleReLU object using the specified parameters. - * The non zero parameter can be adjusted by specifying the parameter - * alpha which controls the range of the relu function. (Default alpha = 0) - * This parameter is trainable. - * - * @param alpha Parameter for adjusting the range of the relu function. - * - */ - FlexibleReLU(const double alpha = 0); - - /** - * Reset the layer parameter. - */ - void Reset(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const DataType&& input, DataType&& gy, DataType&& g); - - /** - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return alpha; } - //! Modify the parameters. - OutputDataType& Parameters() { return alpha; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta;} - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! Get the parameter controlling the range of the relu function. - double const& Alpha() const { return alpha; } - //! Modify the parameter controlling the range of the relu function. - double& Alpha() { return alpha; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version*/); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Parameter object. - OutputDataType alpha; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Parameter controlling the range of the rectifier function - double userAlpha; -}; // class FlexibleReLU - -} // namespace ann -} // namespace mlpack - -// Include implementation -#include "flexible_relu_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/flexible_relu_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/flexible_relu_impl.hpp deleted file mode 100644 index 52ab56f49..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/flexible_relu_impl.hpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file flexible_relu_impl.hpp - * @author Aarush Gupta - * @author Manthan-R-Sheth - * - * Implementation of FlexibleReLU layer as described by - * Suo Qiu, Xiangmin Xu and Bolun Cai in - * "FReLU: Flexible Rectified Linear Units for Improving Convolutional - * Neural Networks", 2018 - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_LAYER_FLEXIBLERELU_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_FLEXIBLERELU_IMPL_HPP - -#include "flexible_relu.hpp" -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -FlexibleReLU::FlexibleReLU( - const double alpha) : userAlpha(alpha) -{ - this->alpha.set_size(1, 1); - this->alpha(0) = userAlpha; -} - -template -void FlexibleReLU::Reset() -{ - //! Set value of alpha to the one given by user. - alpha(0) = userAlpha; -} - -template -template -void FlexibleReLU::Forward( - const InputType&& input, OutputType&& output) -{ - output = arma::clamp(input, 0.0, DBL_MAX) + alpha(0); -} - -template -template -void FlexibleReLU::Backward( - const DataType&& input, DataType&& gy, DataType&& g) -{ - //! Compute the first derivative of FlexibleReLU function. - g = gy % arma::clamp(arma::sign(input), 0.0, 1.0); -} - -template -template -void FlexibleReLU::Gradient( - const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient) -{ - if (gradient.n_elem == 0) - { - gradient.set_size(1, 1); - } - - gradient(0) = arma::accu(error) / input.n_cols; -} - - -template -template -void FlexibleReLU::serialize( - Archive& ar, - const unsigned int /* version*/) -{ - ar & BOOST_SERIALIZATION_NVP(alpha); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/glimpse.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/glimpse.hpp deleted file mode 100644 index 92eaad47e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/glimpse.hpp +++ /dev/null @@ -1,433 +0,0 @@ -/** - * @file glimpse.hpp - * @author Marcus Edel - * - * Definition of the GlimpseLayer class, which takes an input image and a - * location to extract a retina-like representation of the input image at - * different increasing scales. - * - * For more information, see the following. - * - * @code - * @article{CoRR2014, - * author = {Volodymyr Mnih, Nicolas Heess, Alex Graves, Koray Kavukcuoglu}, - * title = {Recurrent Models of Visual Attention}, - * journal = {CoRR}, - * volume = {abs/1406.6247}, - * year = {2014}, - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_GLIMPSE_HPP -#define MLPACK_METHODS_ANN_LAYER_GLIMPSE_HPP - -#include - -#include "layer_types.hpp" -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - - -/* - * The mean pooling rule for convolution neural networks. Average all values - * within the receptive block. - */ -class MeanPoolingRule -{ - public: - /* - * Return the average value within the receptive block. - * - * @param input Input used to perform the pooling operation. - */ - template - double Pooling(const MatType& input) - { - return arma::mean(arma::mean(input)); - } - - /* - * Set the average value within the receptive block. - * - * @param input Input used to perform the pooling operation. - * @param value The unpooled value. - * @param output The unpooled output data. - */ - template - void Unpooling(const MatType& input, const double value, MatType& output) - { - output = arma::zeros(input.n_rows, input.n_cols); - const double mean = arma::mean(arma::mean(input)); - - output.elem(arma::find(mean == input, 1)).fill(value); - } -}; - -/** - * The glimpse layer returns a retina-like representation - * (down-scaled cropped images) of increasing scale around a given location in a - * given image. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class Glimpse -{ - public: - /** - * Create the GlimpseLayer object using the specified ratio and rescale - * parameter. - * - * @param inSize The size of the input units. - * @param size The used glimpse size (height = width). - * @param depth The number of patches to crop per glimpse. - * @param scale The scaling factor used to create the increasing retina-like - * representation. - * @param inputWidth The input width of the given input data. - * @param inputHeight The input height of the given input data. - */ - Glimpse(const size_t inSize = 0, - const size_t size = 0, - const size_t depth = 3, - const size_t scale = 2, - const size_t inputWidth = 0, - const size_t inputHeight = 0); - - /** - * Ordinary feed forward pass of the glimpse layer. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of the glimpse layer. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - //! Get the input parameter. - InputDataType& InputParameter() const {return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const {return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the detla. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Set the locationthe x and y coordinate of the center of the output - //! glimpse. - void Location(const arma::mat& location) - { - this->location = location; - } - - //! Get the input width. - size_t const& InputWidth() const { return inputWidth; } - //! Modify input the width. - size_t& InputWidth() { return inputWidth; } - - //! Get the input height. - size_t const& InputHeight() const { return inputHeight; } - //! Modify the input height. - size_t& InputHeight() { return inputHeight; } - - //! Get the output width. - size_t const& OutputWidth() const { return outputWidth; } - //! Modify the output width. - size_t& OutputWidth() { return outputWidth; } - - //! Get the output height. - size_t const& OutputHeight() const { return outputHeight; } - //! Modify the output height. - size_t& OutputHeight() { return outputHeight; } - - //! Get the value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /* - * Transform the given input by changing rows to columns. - * - * @param w The input matrix used to perform the transformation. - */ - void Transform(arma::mat& w) - { - arma::mat t = w; - - for (size_t i = 0, k = 0; i < w.n_elem; k++) - { - for (size_t j = 0; j < w.n_cols; j++, i++) - { - w(k, j) = t(i); - } - } - } - - /* - * Transform the given input by changing rows to columns. - * - * @param w The input matrix used to perform the transformation. - */ - void Transform(arma::cube& w) - { - for (size_t i = 0; i < w.n_slices; i++) - { - arma::mat t = w.slice(i); - Transform(t); - w.slice(i) = t; - } - } - - /** - * Apply pooling to the input and store the results to the output parameter. - * - * @param kSize the kernel size used to perform the pooling operation. - * @param input The input to be apply the pooling rule. - * @param output The pooled result. - */ - template - void Pooling(const size_t kSize, - const arma::Mat& input, - arma::Mat& output) - { - const size_t rStep = kSize; - const size_t cStep = kSize; - - for (size_t j = 0; j < input.n_cols; j += cStep) - { - for (size_t i = 0; i < input.n_rows; i += rStep) - { - output(i / rStep, j / cStep) += pooling.Pooling( - input(arma::span(i, i + rStep - 1), arma::span(j, j + cStep - 1))); - } - } - } - - /** - * Apply unpooling to the input and store the results. - * - * @param input The input to be apply the unpooling rule. - * @param error The error used to perform the unpooling operation. - * @param output The pooled result. - */ - template - void Unpooling(const arma::Mat& input, - const arma::Mat& error, - arma::Mat& output) - { - const size_t rStep = input.n_rows / error.n_rows; - const size_t cStep = input.n_cols / error.n_cols; - - arma::Mat unpooledError; - for (size_t j = 0; j < input.n_cols; j += cStep) - { - for (size_t i = 0; i < input.n_rows; i += rStep) - { - const arma::Mat& inputArea = input(arma::span(i, i + rStep - 1), - arma::span(j, j + cStep - 1)); - - pooling.Unpooling(inputArea, error(i / rStep, j / cStep), - unpooledError); - - output(arma::span(i, i + rStep - 1), - arma::span(j, j + cStep - 1)) += unpooledError; - } - } - } - - /** - * Apply ReSampling to the input and store the results in the output - * parameter. - * - * @param input The input to be apply the ReSampling rule. - * @param output The pooled result. - */ - template - void ReSampling(const arma::Mat& input, arma::Mat& output) - { - double wRatio = (double) (input.n_rows - 1) / (size - 1); - double hRatio = (double) (input.n_cols - 1) / (size - 1); - - double iWidth = input.n_rows - 1; - double iHeight = input.n_cols - 1; - - for (size_t y = 0; y < size; y++) - { - for (size_t x = 0; x < size; x++) - { - double ix = wRatio * x; - double iy = hRatio * y; - - // Get the 4 nearest neighbors. - double ixNw = std::floor(ix); - double iyNw = std::floor(iy); - double ixNe = ixNw + 1; - double iySw = iyNw + 1; - - // Get surfaces to each neighbor. - double se = (ix - ixNw) * (iy - iyNw); - double sw = (ixNe - ix) * (iy - iyNw); - double ne = (ix - ixNw) * (iySw - iy); - double nw = (ixNe - ix) * (iySw - iy); - - // Calculate the weighted sum. - output(y, x) = input(iyNw, ixNw) * nw + - input(iyNw, std::min(ixNe, iWidth)) * ne + - input(std::min(iySw, iHeight), ixNw) * sw + - input(std::min(iySw, iHeight), std::min(ixNe, iWidth)) * se; - } - } - } - - /** - * Apply DownwardReSampling to the input and store the results into the output - * parameter. - * - * @param input The input to be apply the DownwardReSampling rule. - * @param error The error used to perform the DownwardReSampling operation. - * @param output The DownwardReSampled result. - */ - template - void DownwardReSampling(const arma::Mat& input, - const arma::Mat& error, - arma::Mat& output) - { - double iWidth = input.n_rows - 1; - double iHeight = input.n_cols - 1; - - double wRatio = iWidth / (size - 1); - double hRatio = iHeight / (size - 1); - - for (size_t y = 0; y < size; y++) - { - for (size_t x = 0; x < size; x++) - { - double ix = wRatio * x; - double iy = hRatio * y; - - // Get the 4 nearest neighbors. - double ixNw = std::floor(ix); - double iyNw = std::floor(iy); - double ixNe = ixNw + 1; - double iySw = iyNw + 1; - - // Get surfaces to each neighbor. - double se = (ix - ixNw) * (iy - iyNw); - double sw = (ixNe - ix) * (iy - iyNw); - double ne = (ix - ixNw) * (iySw - iy); - double nw = (ixNe - ix) * (iySw - iy); - - double ograd = error(y, x); - - output(iyNw, ixNw) = output(iyNw, ixNw) + nw * ograd; - output(iyNw, std::min(ixNe, iWidth)) = output(iyNw, - std::min(ixNe, iWidth)) + ne * ograd; - output(std::min(iySw, iHeight), ixNw) = output(std::min(iySw, iHeight), - ixNw) + sw * ograd; - output(std::min(iySw, iHeight), std::min(ixNe, iWidth)) = output( - std::min(iySw, iHeight), std::min(ixNe, iWidth)) + se * ograd; - } - } - } - - //! The size of the input units. - size_t inSize; - - //! The used glimpse size (height = width). - size_t size; - - //! The number of patches to crop per glimpse. - size_t depth; - - //! The scale fraction. - size_t scale; - - //! Locally-stored input width. - size_t inputWidth; - - //! Locally-stored input height. - size_t inputHeight; - - //! Locally-stored output width. - size_t outputWidth; - - //! Locally-stored output height. - size_t outputHeight; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored depth of the input. - size_t inputDepth; - - //! Locally-stored transformed input parameter. - arma::cube inputTemp; - - //! Locally-stored transformed output parameter. - arma::cube outputTemp; - - //! The x and y coordinate of the center of the output glimpse. - arma::mat location; - - //! Locally-stored object to perform the mean pooling operation. - MeanPoolingRule pooling; - - //! Location-stored module location parameter. - std::vector locationParameter; - - //! Location-stored transformed gradient paramter. - arma::cube gTemp; - - //! If true use maximum a posteriori during the forward pass. - bool deterministic; -}; // class GlimpseLayer - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "glimpse_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/glimpse_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/glimpse_impl.hpp deleted file mode 100644 index 774cede8a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/glimpse_impl.hpp +++ /dev/null @@ -1,233 +0,0 @@ -/** - * @file glimpse_impl.hpp - * @author Marcus Edel - * - * Implementation of the GlimpseLayer class, which takes an input image and a - * location to extract a retina-like representation of the input image at - * different increasing scales. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_GLIMPSE_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_GLIMPSE_IMPL_HPP - -// In case it hasn't yet been included. -#include "glimpse.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Glimpse::Glimpse( - const size_t inSize, - const size_t size, - const size_t depth, - const size_t scale, - const size_t inputWidth, - const size_t inputHeight) : - inSize(inSize), - size(size), - depth(depth), - scale(scale), - inputWidth(inputWidth), - inputHeight(inputHeight), - outputWidth(size), - outputHeight(size), - inputDepth(0), - deterministic(true) -{ - // Nothing to do here. -} - -template -template -void Glimpse::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - inputTemp = arma::cube(input.colptr(0), inputWidth, inputHeight, inSize); - outputTemp = arma::Cube(size, size, depth * inputTemp.n_slices); - - location = input.submat(0, 1, 1, 1); - - if (!deterministic) - { - locationParameter.push_back(location); - } - - inputDepth = inputTemp.n_slices / inSize; - - for (size_t inputIdx = 0; inputIdx < inSize; inputIdx++) - { - for (size_t depthIdx = 0, glimpseSize = size; - depthIdx < depth; depthIdx++, glimpseSize *= scale) - { - size_t padSize = std::floor((glimpseSize - 1) / 2); - - arma::Cube inputPadded = arma::zeros >( - inputTemp.n_rows + padSize * 2, inputTemp.n_cols + padSize * 2, - inputTemp.n_slices / inSize); - - inputPadded.tube(padSize, padSize, padSize + inputTemp.n_rows - 1, - padSize + inputTemp.n_cols - 1) = inputTemp.subcube(0, 0, - inputIdx * inputDepth, inputTemp.n_rows - 1, inputTemp.n_cols - 1, - (inputIdx + 1) * inputDepth - 1); - - size_t h = inputPadded.n_rows - glimpseSize; - size_t w = inputPadded.n_cols - glimpseSize; - - size_t x = std::min(h, (size_t) std::max(0.0, - (location(0, inputIdx) + 1) / 2.0 * h)); - size_t y = std::min(w, (size_t) std::max(0.0, - (location(1, inputIdx) + 1) / 2.0 * w)); - - if (depthIdx == 0) - { - for (size_t j = (inputIdx + depthIdx), paddedSlice = 0; - j < outputTemp.n_slices; j += (inSize * depth), paddedSlice++) - { - outputTemp.slice(j) = inputPadded.subcube(x, y, - paddedSlice, x + glimpseSize - 1, y + glimpseSize - 1, - paddedSlice); - } - } - else - { - for (size_t j = (inputIdx + depthIdx * (depth - 1)), paddedSlice = 0; - j < outputTemp.n_slices; j += (inSize * depth), paddedSlice++) - { - arma::Mat poolingInput = inputPadded.subcube(x, y, - paddedSlice, x + glimpseSize - 1, y + glimpseSize - 1, - paddedSlice); - - if (scale == 2) - { - Pooling(glimpseSize / size, poolingInput, outputTemp.slice(j)); - } - else - { - ReSampling(poolingInput, outputTemp.slice(j)); - } - } - } - } - } - - for (size_t i = 0; i < outputTemp.n_slices; ++i) - { - outputTemp.slice(i) = arma::trans(outputTemp.slice(i)); - } - - output = arma::Mat(outputTemp.memptr(), outputTemp.n_elem, 1); - - outputWidth = outputTemp.n_rows; - outputHeight = outputTemp.n_cols; -} - -template -template -void Glimpse::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - // Generate a cube using the backpropagated error matrix. - arma::Cube mappedError = arma::zeros(outputWidth, - outputHeight, 1); - - location = locationParameter.back(); - locationParameter.pop_back(); - - for (size_t s = 0, j = 0; s < mappedError.n_slices; s+= gy.n_cols, j++) - { - for (size_t i = 0; i < gy.n_cols; i++) - { - mappedError.slice(s + i) = arma::Mat(gy.memptr(), - outputWidth, outputHeight); - } - } - - gTemp = arma::zeros(inputTemp.n_rows, inputTemp.n_cols, - inputTemp.n_slices); - - for (size_t inputIdx = 0; inputIdx < inSize; inputIdx++) - { - for (size_t depthIdx = 0, glimpseSize = size; - depthIdx < depth; depthIdx++, glimpseSize *= scale) - { - size_t padSize = std::floor((glimpseSize - 1) / 2); - - arma::Cube inputPadded = arma::zeros >( - inputTemp.n_rows + padSize * 2, inputTemp.n_cols + - padSize * 2, inputTemp.n_slices / inSize); - - size_t h = inputPadded.n_rows - glimpseSize; - size_t w = inputPadded.n_cols - glimpseSize; - - size_t x = std::min(h, (size_t) std::max(0.0, - (location(0, inputIdx) + 1) / 2.0 * h)); - size_t y = std::min(w, (size_t) std::max(0.0, - (location(1, inputIdx) + 1) / 2.0 * w)); - - if (depthIdx == 0) - { - for (size_t j = (inputIdx + depthIdx), paddedSlice = 0; - j < mappedError.n_slices; j += (inSize * depth), paddedSlice++) - { - inputPadded.subcube(x, y, - paddedSlice, x + glimpseSize - 1, y + glimpseSize - 1, - paddedSlice) = mappedError.slice(j); - } - } - else - { - for (size_t j = (inputIdx + depthIdx * (depth - 1)), paddedSlice = 0; - j < mappedError.n_slices; j += (inSize * depth), paddedSlice++) - { - arma::Mat poolingOutput = inputPadded.subcube(x, y, - paddedSlice, x + glimpseSize - 1, y + glimpseSize - 1, - paddedSlice); - - if (scale == 2) - { - Unpooling(inputTemp.slice(paddedSlice), mappedError.slice(j), - poolingOutput); - } - else - { - DownwardReSampling(inputTemp.slice(paddedSlice), - mappedError.slice(j), poolingOutput); - } - - inputPadded.subcube(x, y, - paddedSlice, x + glimpseSize - 1, y + glimpseSize - 1, - paddedSlice) = poolingOutput; - } - } - - gTemp += inputPadded.tube(padSize, padSize, padSize + - inputTemp.n_rows - 1, padSize + inputTemp.n_cols - 1); - } - } - - Transform(gTemp); - g = arma::mat(gTemp.memptr(), gTemp.n_elem, 1); -} - -template -template -void Glimpse::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(size); - ar & BOOST_SERIALIZATION_NVP(depth); - ar & BOOST_SERIALIZATION_NVP(scale); - ar & BOOST_SERIALIZATION_NVP(inputWidth); - ar & BOOST_SERIALIZATION_NVP(location); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/gru.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/gru.hpp deleted file mode 100644 index ed2e96fbc..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/gru.hpp +++ /dev/null @@ -1,262 +0,0 @@ -/** - * @file gru.hpp - * @author Sumedh Ghaisas - * - * Definition of the GRU layer. - * - * For more information, read the following paper: - * - * @code - * @inproceedings{chung2015gated, - * title = {Gated Feedback Recurrent Neural Networks.}, - * author = {Chung, Junyoung and G{\"u}l{\c{c}}ehre, Caglar and Cho, - Kyunghyun and Bengio, Yoshua}, - * booktitle = {ICML}, - * pages = {2067--2075}, - * year = {2015} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_GRU_HPP -#define MLPACK_METHODS_ANN_LAYER_GRU_HPP - -#include -#include - -#include - -#include "../visitor/delta_visitor.hpp" -#include "../visitor/output_parameter_visitor.hpp" - -#include "layer_types.hpp" -#include "add_merge.hpp" -#include "sequential.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * An implementation of a gru network layer. - * - * This cell can be used in RNN networks. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class GRU -{ - public: - //! Create the GRU object. - GRU(); - - /** - * Create the GRU layer object using the specified parameters. - * - * @param inSize The number of input units. - * @param outSize The number of output units. - * @param rho Maximum number of steps to backpropagate through time (BPTT). - */ - GRU(const size_t inSize, - const size_t outSize, - const size_t rho = std::numeric_limits::max()); - - /** - * Delete the GRU and the layers it holds. - */ - ~GRU(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(arma::Mat&& input, - arma::Mat&& /* error */, - arma::Mat&& /* gradient */); - - /* - * Resets the cell to accept a new input. This breaks the BPTT chain starts a - * new one. - * - * @param size The current maximum number of steps through time. - */ - void ResetCell(const size_t size); - - //! The value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - //! Get the maximum number of steps to backpropagate through time (BPTT). - size_t Rho() const { return rho; } - //! Modify the maximum number of steps to backpropagate through time (BPTT). - size_t& Rho() { return rho; } - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! Get the model modules. - std::vector >& Model() { return network; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Number of steps to backpropagate through time (BPTT). - size_t rho; - - //! Current batch size. - size_t batchSize; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored input 2 gate module. - LayerTypes<> input2GateModule; - - //! Locally-stored output 2 gate module. - LayerTypes<> output2GateModule; - - //! Locally-stored output hidden state 2 gate module. - LayerTypes<> outputHidden2GateModule; - - //! Locally-stored input gate module. - LayerTypes<> inputGateModule; - - //! Locally-stored hidden state module. - LayerTypes<> hiddenStateModule; - - //! Locally-stored forget gate module. - LayerTypes<> forgetGateModule; - - //! Locally-stored output parameter visitor. - OutputParameterVisitor outputParameterVisitor; - - //! Locally-stored delta visitor. - DeltaVisitor deltaVisitor; - - //! Locally-stored delete visitor. - DeleteVisitor deleteVisitor; - - //! Locally-stored list of network modules. - std::vector > network; - - //! Locally-stored number of forward steps. - size_t forwardStep; - - //! Locally-stored number of backward steps. - size_t backwardStep; - - //! Locally-stored number of gradient steps. - size_t gradientStep; - - //! Locally-stored output parameters. - std::list outParameter; - - //! Matrix of all zeroes to initialize the output - arma::mat allZeros; - - //! Iterator pointed to the last output produced by the cell - std::list::iterator prevOutput; - - //! Iterator pointed to the last output processed by backward - std::list::iterator backIterator; - - //! Iterator pointed to the last output processed by gradient - std::list::iterator gradIterator; - - //! Locally-stored previous error. - arma::mat prevError; - - //! If true dropout and scaling is disabled, see notes above. - bool deterministic; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class GRU - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "gru_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/gru_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/gru_impl.hpp deleted file mode 100644 index 86c6b8541..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/gru_impl.hpp +++ /dev/null @@ -1,415 +0,0 @@ -/** - * @file gru_impl.hpp - * @author Sumedh Ghaisas - * - * Implementation of the GRU class, which implements a gru network - * layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_GRU_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_GRU_IMPL_HPP - -// In case it hasn't yet been included. -#include "gru.hpp" - -#include "../visitor/forward_visitor.hpp" -#include "../visitor/backward_visitor.hpp" -#include "../visitor/gradient_visitor.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -GRU::GRU() -{ - // Nothing to do here. -} - -template -GRU::GRU( - const size_t inSize, - const size_t outSize, - const size_t rho) : - inSize(inSize), - outSize(outSize), - rho(rho), - batchSize(1), - forwardStep(0), - backwardStep(0), - gradientStep(0), - deterministic(false) -{ - // Input specific linear layers(for zt, rt, ot). - input2GateModule = new Linear<>(inSize, 3 * outSize); - - // Previous output gates (for zt and rt). - output2GateModule = new LinearNoBias<>(outSize, 2 * outSize); - - // Previous output gate for ot. - outputHidden2GateModule = new LinearNoBias<>(outSize, outSize); - - network.push_back(input2GateModule); - network.push_back(output2GateModule); - network.push_back(outputHidden2GateModule); - - inputGateModule = new SigmoidLayer<>(); - forgetGateModule = new SigmoidLayer<>(); - hiddenStateModule = new TanHLayer<>(); - - network.push_back(inputGateModule); - network.push_back(hiddenStateModule); - network.push_back(forgetGateModule); - - prevError = arma::zeros(3 * outSize, batchSize); - - allZeros = arma::zeros(outSize, batchSize); - - outParameter.push_back(std::move(arma::mat(allZeros.memptr(), - allZeros.n_rows, allZeros.n_cols, false, true))); - - prevOutput = outParameter.begin(); - backIterator = outParameter.end(); - gradIterator = outParameter.end(); -} - -template -GRU::~GRU() -{ - boost::apply_visitor(deleteVisitor, input2GateModule); - boost::apply_visitor(deleteVisitor, output2GateModule); - boost::apply_visitor(deleteVisitor, outputHidden2GateModule); - boost::apply_visitor(deleteVisitor, inputGateModule); - boost::apply_visitor(deleteVisitor, forgetGateModule); - boost::apply_visitor(deleteVisitor, hiddenStateModule); -} - -template -template -void GRU::Forward( - arma::Mat&& input, arma::Mat&& output) -{ - if (input.n_cols != batchSize) - { - batchSize = input.n_cols; - prevError.resize(3 * outSize, batchSize); - allZeros.zeros(outSize, batchSize); - // Batch size better not change during an iteration... - if (outParameter.size() > 1) - { - Log::Fatal << "GRU<>::Forward(): batch size cannot change during a " - << "forward pass!" << std::endl; - } - - outParameter.clear(); - outParameter.push_back(std::move(arma::mat(allZeros.memptr(), - allZeros.n_rows, allZeros.n_cols, false, true))); - - prevOutput = outParameter.begin(); - backIterator = outParameter.end(); - gradIterator = outParameter.end(); - } - - // Process the input linearly(zt, rt, ot). - boost::apply_visitor(ForwardVisitor(std::move(input), std::move( - boost::apply_visitor(outputParameterVisitor, input2GateModule))), - input2GateModule); - - // Process the output(zt, rt) linearly. - boost::apply_visitor(ForwardVisitor(std::move(*prevOutput), std::move( - boost::apply_visitor(outputParameterVisitor, output2GateModule))), - output2GateModule); - - // Merge the outputs(zt and rt). - output = (boost::apply_visitor(outputParameterVisitor, - input2GateModule).submat(0, 0, 2 * outSize - 1, batchSize - 1) + - boost::apply_visitor(outputParameterVisitor, output2GateModule)); - - // Pass the first outSize through inputGate(it). - boost::apply_visitor(ForwardVisitor(std::move(output.submat( - 0, 0, 1 * outSize - 1, batchSize - 1)), std::move(boost::apply_visitor( - outputParameterVisitor, inputGateModule))), inputGateModule); - - // Pass the second through forgetGate. - boost::apply_visitor(ForwardVisitor(std::move(output.submat( - 1 * outSize, 0, 2 * outSize - 1, batchSize - 1)), std::move( - boost::apply_visitor(outputParameterVisitor, forgetGateModule))), - forgetGateModule); - - arma::mat modInput = (boost::apply_visitor(outputParameterVisitor, - forgetGateModule) % *prevOutput); - - // Pass that through the outputHidden2GateModule. - boost::apply_visitor(ForwardVisitor(std::move(modInput), std::move( - boost::apply_visitor(outputParameterVisitor, outputHidden2GateModule))), - outputHidden2GateModule); - - // Merge for ot. - arma::mat outputH = boost::apply_visitor(outputParameterVisitor, - input2GateModule).submat(2 * outSize, 0, 3 * outSize - 1, batchSize - 1) + - boost::apply_visitor(outputParameterVisitor, outputHidden2GateModule); - - // Pass it through hiddenGate. - boost::apply_visitor(ForwardVisitor(std::move(outputH), std::move( - boost::apply_visitor(outputParameterVisitor, hiddenStateModule))), - hiddenStateModule); - - // Update the output (nextOutput): cmul1 + cmul2 - // Where cmul1 is input gate * prevOutput and - // cmul2 is (1 - input gate) * hidden gate. - output = (boost::apply_visitor(outputParameterVisitor, inputGateModule) - % (*prevOutput - boost::apply_visitor(outputParameterVisitor, - hiddenStateModule))) + boost::apply_visitor(outputParameterVisitor, - hiddenStateModule); - - forwardStep++; - if (forwardStep == rho) - { - forwardStep = 0; - if (!deterministic) - { - outParameter.push_back(std::move(arma::mat(allZeros.memptr(), - allZeros.n_rows, allZeros.n_cols, false, true))); - prevOutput = --outParameter.end(); - } - else - { - *prevOutput = std::move(arma::mat(allZeros.memptr(), - allZeros.n_rows, allZeros.n_cols, false, true)); - } - } - else if (!deterministic) - { - outParameter.push_back(output); - prevOutput = --outParameter.end(); - } - else - { - if (forwardStep == 1) - { - outParameter.clear(); - outParameter.push_back(output); - - prevOutput = outParameter.begin(); - } - else - { - *prevOutput = output; - } - } -} - -template -template -void GRU::Backward( - const arma::Mat&& input, arma::Mat&& gy, arma::Mat&& g) -{ - if (input.n_cols != batchSize) - { - batchSize = input.n_cols; - prevError.resize(3 * outSize, batchSize); - allZeros.zeros(outSize, batchSize); - // Batch size better not change during an iteration... - if (outParameter.size() > 1) - { - Log::Fatal << "GRU<>::Forward(): batch size cannot change during a " - << "forward pass!" << std::endl; - } - - outParameter.clear(); - outParameter.push_back(std::move(arma::mat(allZeros.memptr(), - allZeros.n_rows, allZeros.n_cols, false, true))); - - prevOutput = outParameter.begin(); - backIterator = outParameter.end(); - gradIterator = outParameter.end(); - } - - if ((outParameter.size() - backwardStep - 1) % rho != 0 && backwardStep != 0) - { - gy += boost::apply_visitor(deltaVisitor, output2GateModule); - } - - if (backIterator == outParameter.end()) - { - backIterator = --(--outParameter.end()); - } - - // Delta zt. - arma::mat dZt = gy % (*backIterator - - boost::apply_visitor(outputParameterVisitor, - hiddenStateModule)); - - // Delta ot. - arma::mat dOt = gy % (arma::ones(outSize, batchSize) - - boost::apply_visitor(outputParameterVisitor, inputGateModule)); - - // Delta of input gate. - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, inputGateModule)), std::move(dZt), - std::move(boost::apply_visitor(deltaVisitor, inputGateModule))), - inputGateModule); - - // Delta of hidden gate. - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, hiddenStateModule)), std::move(dOt), - std::move(boost::apply_visitor(deltaVisitor, hiddenStateModule))), - hiddenStateModule); - - // Delta of outputHidden2GateModule. - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, outputHidden2GateModule)), - std::move(boost::apply_visitor(deltaVisitor, hiddenStateModule)), - std::move(boost::apply_visitor(deltaVisitor, outputHidden2GateModule))), - outputHidden2GateModule); - - // Delta rt. - arma::mat dRt = boost::apply_visitor(deltaVisitor, outputHidden2GateModule) % - *backIterator; - - // Delta of forget gate. - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, forgetGateModule)), std::move(dRt), - std::move(boost::apply_visitor(deltaVisitor, forgetGateModule))), - forgetGateModule); - - // Put delta zt. - prevError.submat(0, 0, 1 * outSize - 1, batchSize - 1) = boost::apply_visitor( - deltaVisitor, inputGateModule); - - // Put delta rt. - prevError.submat(1 * outSize, 0, 2 * outSize - 1, batchSize - 1) = - boost::apply_visitor(deltaVisitor, forgetGateModule); - - // Put delta ot. - prevError.submat(2 * outSize, 0, 3 * outSize - 1, batchSize - 1) = - boost::apply_visitor(deltaVisitor, hiddenStateModule); - - // Get delta ht - 1 for input gate and forget gate. - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, input2GateModule)), - std::move(prevError.submat(0, 0, 2 * outSize - 1, batchSize - 1)), - std::move(boost::apply_visitor(deltaVisitor, output2GateModule))), - output2GateModule); - - // Add delta ht - 1 from hidden state. - boost::apply_visitor(deltaVisitor, output2GateModule) += - boost::apply_visitor(deltaVisitor, outputHidden2GateModule) % - boost::apply_visitor(outputParameterVisitor, forgetGateModule); - - // Add delta ht - 1 from ht. - boost::apply_visitor(deltaVisitor, output2GateModule) += gy % - boost::apply_visitor(outputParameterVisitor, inputGateModule); - - // Get delta input. - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, input2GateModule)), std::move(prevError), - std::move(boost::apply_visitor(deltaVisitor, input2GateModule))), - input2GateModule); - - backwardStep++; - backIterator--; - - g = boost::apply_visitor(deltaVisitor, input2GateModule); -} - -template -template -void GRU::Gradient( - arma::Mat&& input, - arma::Mat&& /* error */, - arma::Mat&& /* gradient */) -{ - if (input.n_cols != batchSize) - { - batchSize = input.n_cols; - prevError.resize(3 * outSize, batchSize); - allZeros.zeros(outSize, batchSize); - // Batch size better not change during an iteration... - if (outParameter.size() > 1) - { - Log::Fatal << "GRU<>::Forward(): batch size cannot change during a " - << "forward pass!" << std::endl; - } - - outParameter.clear(); - outParameter.push_back(std::move(arma::mat(allZeros.memptr(), - allZeros.n_rows, allZeros.n_cols, false, true))); - - prevOutput = outParameter.begin(); - backIterator = outParameter.end(); - gradIterator = outParameter.end(); - } - - if (gradIterator == outParameter.end()) - { - gradIterator = --(--outParameter.end()); - } - - boost::apply_visitor(GradientVisitor(std::move(input), std::move(prevError)), - input2GateModule); - - boost::apply_visitor(GradientVisitor( - std::move(*gradIterator), - std::move(prevError.submat(0, 0, 2 * outSize - 1, batchSize - 1))), - output2GateModule); - - boost::apply_visitor(GradientVisitor( - *gradIterator % boost::apply_visitor(outputParameterVisitor, - forgetGateModule), - std::move(prevError.submat(2 * outSize, 0, 3 * outSize - 1, - batchSize - 1))), outputHidden2GateModule); - - gradIterator--; -} - -template -void GRU::ResetCell(const size_t /* size */) -{ - outParameter.clear(); - outParameter.push_back(std::move(arma::mat(allZeros.memptr(), - allZeros.n_rows, allZeros.n_cols, false, true))); - - prevOutput = outParameter.begin(); - backIterator = outParameter.end(); - gradIterator = outParameter.end(); - - forwardStep = 0; - backwardStep = 0; -} - -template -template -void GRU::serialize( - Archive& ar, const unsigned int /* version */) -{ - // If necessary, clean memory from the old model. - if (Archive::is_loading::value) - { - boost::apply_visitor(deleteVisitor, input2GateModule); - boost::apply_visitor(deleteVisitor, output2GateModule); - boost::apply_visitor(deleteVisitor, outputHidden2GateModule); - boost::apply_visitor(deleteVisitor, inputGateModule); - boost::apply_visitor(deleteVisitor, forgetGateModule); - boost::apply_visitor(deleteVisitor, hiddenStateModule); - } - - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); - ar & BOOST_SERIALIZATION_NVP(rho); - - ar & BOOST_SERIALIZATION_NVP(input2GateModule); - ar & BOOST_SERIALIZATION_NVP(output2GateModule); - ar & BOOST_SERIALIZATION_NVP(outputHidden2GateModule); - ar & BOOST_SERIALIZATION_NVP(inputGateModule); - ar & BOOST_SERIALIZATION_NVP(forgetGateModule); - ar & BOOST_SERIALIZATION_NVP(hiddenStateModule); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/hard_tanh.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/hard_tanh.hpp deleted file mode 100644 index 7de2158d6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/hard_tanh.hpp +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @file hard_tanh.hpp - * @author Dhawal Arora - * - * Definition and implementation of the HardTanH layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_HARD_TANH_HPP -#define MLPACK_METHODS_ANN_LAYER_HARD_TANH_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The Hard Tanh activation function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \left\{ - * \begin{array}{lr} - * max & : x > maxValue \\ - * min & : x \le minValue \\ - * x & : otherwise - * \end{array} - * \right. \\ - * f'(x) &=& \left\{ - * \begin{array}{lr} - * 0 & : x > maxValue \\ - * 0 & : x \le minValue \\ - * 1 & : otherwise - * \end{array} - * \right. - * @f} - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class HardTanH -{ - public: - /** - * Create the HardTanH object using the specified parameters. The range - * of the linear region can be adjusted by specifying the maxValue and - * minValue. Default (maxValue = 1, minValue = -1). - * - * @param maxValue Range of the linear region maximum value. - * @param minValue Range of the linear region minimum value. - */ - HardTanH(const double maxValue = 1, const double minValue = -1); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const DataType&& input, - DataType&& gy, - DataType&& g); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the maximum value. - double const& MaxValue() const { return maxValue; } - //! Modify the maximum value. - double& MaxValue() { return maxValue; } - - //! Get the minimum value. - double const& MinValue() const { return minValue; } - //! Modify the minimum value. - double& MinValue() { return minValue; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Maximum value for the HardTanH function. - double maxValue; - - //! Minimum value for the HardTanH function. - double minValue; -}; // class HardTanH - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "hard_tanh_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/hard_tanh_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/hard_tanh_impl.hpp deleted file mode 100644 index 1332b89d8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/hard_tanh_impl.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file hard_tanh_impl.hpp - * @author Dhawal Arora - * - * Implementation and implementation of the HardTanH layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_HARD_TANH_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_HARD_TANH_IMPL_HPP - -// In case it hasn't yet been included. -#include "hard_tanh.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -HardTanH::HardTanH( - const double maxValue, - const double minValue) : - maxValue(maxValue), - minValue(minValue) -{ - // Nothing to do here. -} - -template -template -void HardTanH::Forward( - const InputType&& input, OutputType&& output) -{ - output = input; - for (size_t i = 0; i < input.n_elem; i++) - { - output(i) = (output(i) > maxValue ? maxValue : - (output(i) < minValue ? minValue : output(i))); - } -} - -template -template -void HardTanH::Backward( - const DataType&& input, DataType&& gy, DataType&& g) -{ - g = gy; - for (size_t i = 0; i < input.n_elem; i++) - { - if (input(i) < minValue || input(i) > maxValue) - { - g(i) = 0; - } - } -} - -template -template -void HardTanH::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(maxValue); - ar & BOOST_SERIALIZATION_NVP(minValue); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/join.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/join.hpp deleted file mode 100644 index b55c4bca9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/join.hpp +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file join.hpp - * @author Marcus Edel - * - * Definition of the Join module. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_JOIN_HPP -#define MLPACK_METHODS_ANN_LAYER_JOIN_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Join module class. The Join class accumulates - * the output of various modules. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template< - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class Join -{ - public: - //! Create the Join object. - Join(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input rows. - size_t inSizeRows; - - //! Locally-stored number of input cols. - size_t inSizeCols; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class Join - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "join_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/join_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/join_impl.hpp deleted file mode 100644 index 6ceee0c13..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/join_impl.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file join_impl.hpp - * @author Marcus Edel - * - * Implementation of the Join module. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_JOIN_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_JOIN_IMPL_HPP - -// In case it hasn't yet been included. -#include "join.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Join::Join() : - inSizeRows(0), - inSizeCols(0) -{ - // Nothing to do here. -} - -template -template -void Join::Forward( - const InputType&& input, OutputType&& output) -{ - inSizeRows = input.n_rows; - inSizeCols = input.n_cols; - output = arma::vectorise(input); -} - -template -template -void Join::Backward( - const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g) -{ - g = arma::mat(gy.memptr(), inSizeRows, inSizeCols, false, false); -} - -template -template -void Join::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inSizeRows); - ar & BOOST_SERIALIZATION_NVP(inSizeCols); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer.hpp deleted file mode 100644 index b4764d975..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer.hpp +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @file layer.hpp - * @author Marcus Edel - * - * This includes various layers to construct a model. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LAYER_HPP -#define MLPACK_METHODS_ANN_LAYER_LAYER_HPP - -#include "add_merge.hpp" -#include "atrous_convolution.hpp" -#include "batch_norm.hpp" -#include "concat_performance.hpp" -#include "convolution.hpp" -#include "dropconnect.hpp" -#include "glimpse.hpp" -#include "layer_norm.hpp" -#include "layer_types.hpp" -#include "linear.hpp" -#include "linear_no_bias.hpp" -#include "lstm.hpp" -#include "multiply_merge.hpp" -#include "gru.hpp" -#include "fast_lstm.hpp" -#include "recurrent.hpp" -#include "recurrent_attention.hpp" -#include "sequential.hpp" -#include "concat.hpp" -#include "vr_class_reward.hpp" -#include "transposed_convolution.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_norm.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_norm.hpp deleted file mode 100644 index bda3d0956..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_norm.hpp +++ /dev/null @@ -1,203 +0,0 @@ -/** - * @file layer_norm.hpp - * @author Shikhar Jaiswal - * - * Definition of the Layer Normalization class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LAYERNORM_HPP -#define MLPACK_METHODS_ANN_LAYER_LAYERNORM_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Declaration of the Layer Normalization class. The layer transforms - * the input data into zero mean and unit variance and then scales and shifts - * the data by parameters, gamma and beta respectively over a single training - * data. These parameters are learnt by the network. Layer Normalization is - * different from Batch Normalization in the way that normalization is done - * for individual training cases, and the mean and standard deviations are - * computed across the layer dimensions, as opposed to across the batch. - * - * For more information, refer to the following papers, - * - * @code - * @article{Ba16, - * author = {Jimmy Lei Ba, Jamie Ryan Kiros and Geoffrey E. Hinton}, - * title = {Layer Normalization}, - * volume = {abs/1607.06450}, - * year = {2016}, - * url = {http://arxiv.org/abs/1607.06450}, - * eprint = {1607.06450}, - * } - * @endcode - * - * @code - * @article{Ioffe15, - * author = {Sergey Ioffe and - * Christian Szegedy}, - * title = {Batch Normalization: Accelerating Deep Network Training by - * Reducing Internal Covariate Shift}, - * journal = {CoRR}, - * volume = {abs/1502.03167}, - * year = {2015}, - * url = {http://arxiv.org/abs/1502.03167}, - * eprint = {1502.03167}, - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class LayerNorm -{ - public: - //! Create the LayerNorm object. - LayerNorm(); - - /** - * Create the LayerNorm object for a specified number of input units. - * - * @param size The number of input units. - * @param eps The epsilon added to variance to ensure numerical stability. - */ - LayerNorm(const size_t size, const double eps = 1e-8); - - /** - * Reset the layer parameters. - */ - void Reset(); - - /** - * Forward pass of Layer Normalization. Transforms the input data - * into zero mean and unit variance, scales the data by a factor gamma and - * shifts it by beta. - * - * @param input Input data for the layer. - * @param output Resulting output activations. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Backward pass through the layer. - * - * @param input The input activations. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& input, - arma::Mat&& gy, - arma::Mat&& g); - - /** - * Calculate the gradient using the output delta and the input activations. - * - * @param input The input activations. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! Get the mean across single training data. - OutputDataType Mean() { return mean; } - - //! Get the variance across single training data. - OutputDataType Variance() { return variance; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input units. - size_t size; - - //! Locally-stored epsilon value. - double eps; - - //! Whether we are in loading or saving mode. - bool loading; - - //! Locally-stored scale parameter. - OutputDataType gamma; - - //! Locally-stored shift parameter. - OutputDataType beta; - - //! Locally-stored parameters. - OutputDataType weights; - - //! Locally-stored mean object. - OutputDataType mean; - - //! Locally-stored variance object. - OutputDataType variance; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored normalized input. - OutputDataType normalized; -}; // class LayerNorm - -} // namespace ann -} // namespace mlpack - -// Include the implementation. -#include "layer_norm_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_norm_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_norm_impl.hpp deleted file mode 100644 index 1152c089c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_norm_impl.hpp +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @file layer_norm_impl.hpp - * @author Shikhar Jaiswal - * - * Implementation of the Layer Normalization class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_LAYER_LAYERNORM_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_LAYERNORM_IMPL_HPP - -// In case it is not included. -#include "layer_norm.hpp" - -namespace mlpack { -namespace ann { /** Artificial Neural Network. */ - - -template -LayerNorm::LayerNorm() : - eps(1e-8), - loading(false) -{ - // Nothing to do here. -} - -template -LayerNorm::LayerNorm( - const size_t size, const double eps) : - size(size), - eps(eps), - loading(false) -{ - weights.set_size(size + size, 1); -} - -template -void LayerNorm::Reset() -{ - gamma = arma::mat(weights.memptr(), 1, size, false, false); - beta = arma::mat(weights.memptr() + gamma.n_elem, 1, size, false, false); - - if (!loading) - { - gamma.fill(1.0); - beta.fill(0.0); - } - - loading = false; -} - -template -template -void LayerNorm::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - mean = arma::mean(input, 0); - variance = arma::var(input, 1, 0); - - // Normalize the input. - output = input.each_row() - mean; - - output.each_row() /= arma::sqrt(variance + eps); - - // Reused in the backward and gradient step. - normalized = output; - - // Scale and shift the output. - output.each_row() %= gamma; - output.each_row() += beta; -} - -template -template -void LayerNorm::Backward( - const arma::Mat&& input, arma::Mat&& gy, arma::Mat&& g) -{ - const arma::mat inputMean = input.each_row() - mean; - const arma::mat stdInv = 1.0 / arma::sqrt(variance + eps); - - // dl / dxhat - const arma::mat norm = gy.each_row() % gamma; - - // sum dl / dxhat * (x - mu) * -0.5 * stdInv^3. - const arma::mat var = arma::sum(norm % inputMean, 0) % - arma::pow(stdInv, 3.0) * -0.5; - - // dl / dxhat * 1 / stdInv + variance * 2 * (x - mu) / m + - // dl / dmu * 1 / m. - g = (norm.each_row() % stdInv) + (inputMean.each_row() % - var * 2 / input.n_rows); - - // sum (dl / dxhat * -1 / stdInv) + variance * - // (sum -2 * (x - mu)) / m. - g.each_row() += (arma::sum(norm.each_row() % -stdInv, 0) + (var % - arma::mean(-2 * inputMean, 0))) / input.n_rows; -} - -template -template -void LayerNorm::Gradient( - const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient) -{ - gradient.set_size(size + size, 1); - - // Step 5: dl / dy * xhat. - gradient.submat(0, 0, gamma.n_elem - 1, 0) = arma::reshape(arma::sum( - normalized % error, 0), normalized.n_cols, 1); - - // Step 6: dl / dy. - gradient.submat(gamma.n_elem, 0, gradient.n_elem - 1, 0) = - arma::reshape(arma::sum(error, 0), error.n_cols, 1); -} - -template -template -void LayerNorm::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(size); - - if (Archive::is_loading::value) - { - weights.set_size(size + size, 1); - loading = true; - } - - ar & BOOST_SERIALIZATION_NVP(eps); - ar & BOOST_SERIALIZATION_NVP(gamma); - ar & BOOST_SERIALIZATION_NVP(beta); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_traits.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_traits.hpp deleted file mode 100644 index 02691f7b7..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_traits.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file layer_traits.hpp - * @author Marcus Edel - * - * This provides the LayerTraits class, a template class to get information - * about various layers. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LAYER_TRAITS_HPP -#define MLPACK_METHODS_ANN_LAYER_LAYER_TRAITS_HPP - -#include - -namespace mlpack { -namespace ann { - -/** - * This is a template class that can provide information about various layers. - * By default, this class will provide the weakest possible assumptions on - * layer, and each layer should override values as necessary. If a layer - * doesn't need to override a value, then there's no need to write a LayerTraits - * specialization for that class. - */ -template -class LayerTraits -{ - public: - /** - * This is true if the layer is a binary layer. - */ - static const bool IsBinary = false; - - /** - * This is true if the layer is an output layer. - */ - static const bool IsOutputLayer = false; - - /** - * This is true if the layer is a bias layer. - */ - static const bool IsBiasLayer = false; - - /* - * This is true if the layer is a LSTM layer. - **/ - static const bool IsLSTMLayer = false; - - /* - * This is true if the layer is a connection layer. - **/ - static const bool IsConnection = false; -}; - -// This gives us a HasGradientCheck type (where U is a function pointer) -// we can use with SFINAE to catch when a type has a Gradient(...) function. -HAS_MEM_FUNC(Gradient, HasGradientCheck); - -// This gives us a HasDeterministicCheck type (where U is a function -// pointer) we can use with SFINAE to catch when a type has a Deterministic() -// function. -HAS_MEM_FUNC(Deterministic, HasDeterministicCheck); - -// This gives us a HasParametersCheck type (where U is a function pointer) -// we can use with SFINAE to catch when a type has a Parameters() function. -HAS_MEM_FUNC(Parameters, HasParametersCheck); - -// This gives us a HasAddCheck type (where U is a function pointer) we -// can use with SFINAE to catch when a type has a Add() function. -HAS_MEM_FUNC(Add, HasAddCheck); - -// This gives us a HasModelCheck type we can use with SFINAE to catch when -// a type has a function named Model. -HAS_ANY_METHOD_FORM(Model, HasModelCheck); - -// This gives us a HasLocationCheck type (where U is a function pointer) -// we can use with SFINAE to catch when a type has a Location() function. -HAS_MEM_FUNC(Location, HasLocationCheck); - -// This gives us a HasResetCheck type (where U is a function pointer) -// we can use with SFINAE to catch when a type has a Reset() function. -HAS_MEM_FUNC(Reset, HasResetCheck); - -// This gives us a HasResetCheck type (where U is a function pointer) -// we can use with SFINAE to catch when a type has a ResetCell() function. -HAS_MEM_FUNC(ResetCell, HasResetCellCheck); - -// This gives us a HasRewardCheck type (where U is a function pointer) we -// can use with SFINAE to catch when a type has a Reward() function. -HAS_MEM_FUNC(Reward, HasRewardCheck); - -// This gives us a HasInputWidth type (where U is a function pointer) we -// can use with SFINAE to catch when a type has a InputWidth() function. -HAS_MEM_FUNC(InputWidth, HasInputWidth); - -// This gives us a HasInputHeight type (where U is a function pointer) we -// can use with SFINAE to catch when a type has a InputHeight() function. -HAS_MEM_FUNC(InputHeight, HasInputHeight); - -// This gives us a HasRho type (where U is a function pointer) we -// can use with SFINAE to catch when a type has a Rho() function. -HAS_MEM_FUNC(Rho, HasRho); - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_types.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_types.hpp deleted file mode 100644 index bc2f46dbe..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/layer_types.hpp +++ /dev/null @@ -1,189 +0,0 @@ -/** - * @file layer_types.hpp - * @author Marcus Edel - * - * This provides a list of all modules that can be used to construct a model. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LAYER_TYPES_HPP -#define MLPACK_METHODS_ANN_LAYER_LAYER_TYPES_HPP - -#include - -// Layer modules. -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Convolution modules. -#include -#include -#include - -namespace mlpack { -namespace ann { - -template class BatchNorm; -template class DropConnect; -template class Glimpse; -template class LayerNorm; -template class Linear; -template class LinearNoBias; -template class LSTM; -template class GRU; -template class FastLSTM; -template class VRClassReward; - -template -class AddMerge; - -template -class Sequential; - -template -class Recurrent; - -template -class Concat; - -template< - typename OutputLayerType, - typename InputDataType, - typename OutputDataType -> -class ConcatPerformance; - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -class Convolution; - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -class TransposedConvolution; - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -class AtrousConvolution; - -template< - typename InputDataType, - typename OutputDataType -> -class RecurrentAttention; - -template -class MultiplyMerge; - -template -using LayerTypes = boost::variant< - Add*, - AddMerge*, - AtrousConvolution, - NaiveConvolution, - NaiveConvolution, - arma::mat, arma::mat>*, - BaseLayer*, - BaseLayer*, - BaseLayer*, - BaseLayer*, - BatchNorm*, - BilinearInterpolation*, - Concat*, - ConcatPerformance, - arma::mat, arma::mat>*, - Constant*, - Convolution, - NaiveConvolution, - NaiveConvolution, arma::mat, arma::mat>*, - TransposedConvolution, - NaiveConvolution, - NaiveConvolution, arma::mat, arma::mat>*, - DropConnect*, - Dropout*, - AlphaDropout*, - ELU*, - FlexibleReLU*, - Glimpse*, - HardTanH*, - Join*, - LayerNorm*, - LeakyReLU*, - Linear*, - LinearNoBias*, - LogSoftMax*, - Lookup*, - LSTM*, - GRU*, - FastLSTM*, - MaxPooling*, - MeanPooling*, - MultiplyConstant*, - MultiplyMerge*, - NegativeLogLikelihood*, - PReLU*, - Recurrent*, - RecurrentAttention*, - ReinforceNormal*, - Select*, - Sequential*, - VRClassReward*, - CustomLayers*... ->; - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/leaky_relu.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/leaky_relu.hpp deleted file mode 100644 index dfa7af8e9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/leaky_relu.hpp +++ /dev/null @@ -1,176 +0,0 @@ -/** - * @file leaky_relu.hpp - * @author Dhawal Arora - * - * Definition of LeakyReLU layer first introduced in the acoustic model, - * Andrew L. Maas, Awni Y. Hannun, Andrew Y. Ng, - * "Rectifier Nonlinearities Improve Neural Network Acoustic Models", 2014 - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LEAKYRELU_HPP -#define MLPACK_METHODS_ANN_LAYER_LEAKYRELU_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The LeakyReLU activation function, defined by - * - * @f{eqnarray*}{ - * f(x) &=& \max(x, alpha*x) \\ - * f'(x) &=& \left\{ - * \begin{array}{lr} - * 1 & : x > 0 \\ - * alpha & : x \le 0 - * \end{array} - * \right. - * @f} - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class LeakyReLU -{ - public: - /** - * Create the LeakyReLU object using the specified parameters. - * The non zero gradient can be adjusted by specifying tha parameter - * alpha in the range 0 to 1. Default (alpha = 0.03) - * - * @param alpha Non zero gradient - */ - LeakyReLU(const double alpha = 0.03); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const DataType&& input, DataType&& gy, DataType&& g); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the non zero gradient. - double const& Alpha() const { return alpha; } - //! Modify the non zero gradient. - double& Alpha() { return alpha; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /** - * Computes the LeakyReLU function - * - * @param x Input data. - * @return f(x). - */ - double Fn(const double x) - { - return std::max(x, alpha * x); - } - - /** - * Computes the LeakyReLU function using a dense matrix as input. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - void Fn(const arma::Mat& x, arma::Mat& y) - { - y = arma::max(x, alpha * x); - } - - /** - * Computes the first derivative of the LeakyReLU function. - * - * @param x Input data. - * @return f'(x) - */ - double Deriv(const double x) - { - return (x >= 0) ? 1 : alpha; - } - - /** - * Computes the first derivative of the LeakyReLU function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - - template - void Deriv(const InputType& x, OutputType& y) - { - y = x; - - for (size_t i = 0; i < x.n_elem; i++) - { - y(i) = Deriv(x(i)); - } - } - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Leakyness Parameter in the range 0 -LeakyReLU::LeakyReLU( - const double alpha) : alpha(alpha) -{ - // Nothing to do here. -} - -template -template -void LeakyReLU::Forward( - const InputType&& input, OutputType&& output) -{ - Fn(input, output); -} - -template -template -void LeakyReLU::Backward( - const DataType&& input, DataType&& gy, DataType&& g) -{ - DataType derivative; - Deriv(input, derivative); - g = gy % derivative; -} - -template -template -void LeakyReLU::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(alpha); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear.hpp deleted file mode 100644 index 7de48ece1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear.hpp +++ /dev/null @@ -1,157 +0,0 @@ -/** - * @file linear.hpp - * @author Marcus Edel - * - * Definition of the Linear layer class also known as fully-connected layer or - * affine transformation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LINEAR_HPP -#define MLPACK_METHODS_ANN_LAYER_LINEAR_HPP - -#include - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Linear layer class. The Linear class represents a - * single layer of a neural network. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class Linear -{ - public: - //! Create the Linear object. - Linear(); - - /** - * Create the Linear layer object using the specified number of units. - * - * @param inSize The number of input units. - * @param outSize The number of output units. - */ - Linear(const size_t inSize, const size_t outSize);; - - /* - * Reset the layer parameter. - */ - void Reset(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored weight paramters. - OutputDataType weight; - - //! Locally-stored bias term parameters. - OutputDataType bias; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class Linear - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "linear_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_impl.hpp deleted file mode 100644 index 92f58351d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_impl.hpp +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @file linear_impl.hpp - * @author Marcus Edel - * - * Implementation of the Linear layer class also known as fully-connected layer - * or affine transformation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LINEAR_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_LINEAR_IMPL_HPP - -// In case it hasn't yet been included. -#include "linear.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Linear::Linear() -{ - // Nothing to do here. -} - -template -Linear::Linear( - const size_t inSize, - const size_t outSize) : - inSize(inSize), - outSize(outSize) -{ - weights.set_size(outSize * inSize + outSize, 1); -} - -template -void Linear::Reset() -{ - weight = arma::mat(weights.memptr(), outSize, inSize, false, false); - bias = arma::mat(weights.memptr() + weight.n_elem, - outSize, 1, false, false); -} - -template -template -void Linear::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - output = weight * input; - output.each_col() += bias; -} - -template -template -void Linear::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - g = weight.t() * gy; -} - -template -template -void Linear::Gradient( - const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient) -{ - gradient.submat(0, 0, weight.n_elem - 1, 0) = arma::vectorise( - error * input.t()); - gradient.submat(weight.n_elem, 0, gradient.n_elem - 1, 0) = - arma::sum(error, 1); -} - -template -template -void Linear::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); - - // This is inefficient, but we have to allocate this memory so that - // WeightSetVisitor gets the right size. - if (Archive::is_loading::value) - weights.set_size(outSize * inSize + outSize, 1); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_no_bias.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_no_bias.hpp deleted file mode 100644 index d171e2c2d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_no_bias.hpp +++ /dev/null @@ -1,153 +0,0 @@ -/** - * @file linear.hpp - * @author Marcus Edel - * - * Definition of the LinearNoBias class also known as fully-connected layer or - * affine transformation without the bias term. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LINEAR_NO_BIAS_HPP -#define MLPACK_METHODS_ANN_LAYER_LINEAR_NO_BIAS_HPP - -#include - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the LinearNoBias class. The LinearNoBias class represents a - * single layer of a neural network. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class LinearNoBias -{ - public: - //! Create the LinearNoBias object. - LinearNoBias(); - /** - * Create the LinearNoBias object using the specified number of units. - * - * @param inSize The number of input units. - * @param outSize The number of output units. - */ - LinearNoBias(const size_t inSize, const size_t outSize); - - /* - * Reset the layer parameter. - */ - void Reset(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored weight parameter. - OutputDataType weight; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class LinearNoBias - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "linear_no_bias_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_no_bias_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_no_bias_impl.hpp deleted file mode 100644 index 42070c2d3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/linear_no_bias_impl.hpp +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @file linear_no_bias_impl.hpp - * @author Marcus Edel - * - * Implementation of the LinearNoBias class also known as fully-connected layer - * or affine transformation without the bias term. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LINEAR_NO_BIAS_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_LINEAR_NO_BIAS_IMPL_HPP - -// In case it hasn't yet been included. -#include "linear_no_bias.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -LinearNoBias::LinearNoBias() -{ - // Nothing to do here. -} - -template -LinearNoBias::LinearNoBias( - const size_t inSize, const size_t outSize) : - inSize(inSize), - outSize(outSize) -{ - weights.set_size(outSize * inSize, 1); -} - -template -void LinearNoBias::Reset() -{ - weight = arma::mat(weights.memptr(), outSize, inSize, false, false); -} - -template -template -void LinearNoBias::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - output = weight * input; -} - -template -template -void LinearNoBias::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - g = weight.t() * gy; -} - -template -template -void LinearNoBias::Gradient( - const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient) -{ - gradient.submat(0, 0, weight.n_elem - 1, 0) = arma::vectorise( - error * input.t()); -} - -template -template -void LinearNoBias::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); - - // This is inefficient, but necessary so that WeightSetVisitor sets the right - // size. - if (Archive::is_loading::value) - weights.set_size(outSize * inSize, 1); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/log_softmax.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/log_softmax.hpp deleted file mode 100644 index 62654907d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/log_softmax.hpp +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @file log_softmax.hpp - * @author Marcus Edel - * - * Definition of the LogSoftmax class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_HPP -#define MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the log softmax layer. The log softmax loss layer computes - * the multinomial logistic loss of the softmax of its inputs. This layer is - * meant to be used in combination with the negative log likelihood layer - * (NegativeLogLikelihoodLayer), which expects that the input contains - * log-probabilities for each class. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class LogSoftMax -{ - public: - /** - * Create the LogSoftmax object. - */ - LogSoftMax(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& input, - arma::Mat&& gy, - arma::Mat&& g); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - InputDataType& Delta() const { return delta; } - //! Modify the delta. - InputDataType& Delta() { return delta; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class LogSoftmax - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "log_softmax_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/log_softmax_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/log_softmax_impl.hpp deleted file mode 100644 index d4ca9c53a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/log_softmax_impl.hpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file log_softmax_impl.hpp - * @author Marcus Edel - * - * Implementation of the LogSoftmax class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_IMPL_HPP - -// In case it hasn't yet been included. -#include "log_softmax.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -LogSoftMax::LogSoftMax() -{ - // Nothing to do here. -} - -template -template -void LogSoftMax::Forward( - const InputType&& input, OutputType&& output) -{ - arma::mat maxInput = arma::repmat(arma::max(input), input.n_rows, 1); - output = (maxInput - input); - - // Approximation of the base-e exponential function. The acuracy however is - // about 0.00001 lower as using exp. Credits go to Leon Bottou. - output.transform([](double x) - { - //! Fast approximation of exp(-x) for x positive. - static constexpr double A0 = 1.0; - static constexpr double A1 = 0.125; - static constexpr double A2 = 0.0078125; - static constexpr double A3 = 0.00032552083; - static constexpr double A4 = 1.0172526e-5; - - if (x < 13.0) - { - double y = A0 + x * (A1 + x * (A2 + x * (A3 + x * A4))); - y *= y; - y *= y; - y *= y; - y = 1 / y; - - return y; - } - - return 0.0; - }); - - maxInput.each_row() += arma::log(arma::sum(output)); - output = input - maxInput; -} - -template -template -void LogSoftMax::Backward( - const arma::Mat&& input, - arma::Mat&& gy, - arma::Mat&& g) -{ - g = arma::exp(input) + gy; -} - -template -template -void LogSoftMax::serialize( - Archive& /* ar */, - const unsigned int /* version */) -{ - // Nothing to do here. -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/lookup.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/lookup.hpp deleted file mode 100644 index 5c5109cf0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/lookup.hpp +++ /dev/null @@ -1,147 +0,0 @@ -/** - * @file lookup.hpp - * @author Marcus Edel - * - * Definition of the Lookup class a particular convolution, where the width of - * the convolution is 1. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LOOKUP_HPP -#define MLPACK_METHODS_ANN_LAYER_LOOKUP_HPP - -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Lookup class. The Lookup class is a particular - * convolution, where the width of the convolution is 1. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class Lookup -{ - public: - /** - * Create the Lookup object using the specified number of input and output - * units. - * - * @param inSize The number of input units. - * @param outSize The number of output units. - */ - Lookup(const size_t inSize = 0, const size_t outSize = 0); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - const arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class Lookup - -// Alias for using as embedding layer. -template -using Embedding = Lookup; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "lookup_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/lookup_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/lookup_impl.hpp deleted file mode 100644 index 3c4b8e96c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/lookup_impl.hpp +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file lookup_impl.hpp - * @author Marcus Edel - * - * Implementation of the Lookup class a particular convolution, where the width - * of the convolution is 1. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LOOKUP_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_LOOKUP_IMPL_HPP - -// In case it hasn't yet been included. -#include "lookup.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Lookup::Lookup( - const size_t inSize, - const size_t outSize) : - inSize(inSize), - outSize(outSize) -{ - weights.set_size(outSize, inSize); -} - -template -template -void Lookup::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - output = weights.cols(arma::conv_to::from(input) - 1); -} - -template -template -void Lookup::Backward( - const arma::Mat&& /* input */, - const arma::Mat&& gy, - arma::Mat&& g) -{ - g = gy; -} - -template -template -void Lookup::Gradient( - const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient) -{ - gradient = arma::zeros >(weights.n_rows, weights.n_cols); - gradient.cols(arma::conv_to::from(input) - 1) = error; -} - -template -template -void Lookup::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/lstm.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/lstm.hpp deleted file mode 100644 index cd0f86713..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/lstm.hpp +++ /dev/null @@ -1,324 +0,0 @@ -/** - * @file lstm.hpp - * @author Marcus Edel - * - * Definition of the LSTM class, which implements a LSTM network layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LSTM_HPP -#define MLPACK_METHODS_ANN_LAYER_LSTM_HPP - -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * An implementation of a lstm network layer. - * - * This class allows specification of the type of the activation functions used - * for the gates and cells and also of the type of the function used to - * initialize and update the peephole weights. - - * The implementation corresponds to the following algorithm: - * - * @f{eqnarray}{ - * i &=& sigmoid(W \cdot x + W \cdot h + W \cdot c + b) \\ - * f &=& sigmoid(W \cdot x + W \cdot h + W \cdot c + b) \\ - * z &=& tanh(W \cdot x + W \cdot h + b) \\ - * c &=& f \cdot c + i \cdot z \\ - * o &=& sigmoid(W \cdot x + W \cdot h + W \cdot c + b) \\ - * h &=& o \cdot tanh(c) - * @f} - * - * For more information, see the following. - * - * @code - * @article{Graves2013, - * author = {Alex Graves and Abdel{-}rahman Mohamed and Geoffrey E. Hinton}, - * title = {Speech Recognition with Deep Recurrent Neural Networks}, - * journal = CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1303.5778}, - * } - * @endcode - * - * \see FastLSTM for a faster LSTM version which combines the calculation of the - * input, forget, output gates and hidden state in a single step. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class LSTM -{ - public: - //! Create the LSTM object. - LSTM(); - - /** - * Create the LSTM layer object using the specified parameters. - * - * @param inSize The number of input units. - * @param outSize The number of output units. - * @param rho Maximum number of steps to backpropagate through time (BPTT). - */ - LSTM(const size_t inSize, - const size_t outSize, - const size_t rho = std::numeric_limits::max()); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const InputType&& input, - ErrorType&& gy, - GradientType&& g); - - /* - * Reset the layer parameter. - */ - void Reset(); - - /* - * Resets the cell to accept a new input. This breaks the BPTT chain starts a - * new one. - * - * @param size The current maximum number of steps through time. - */ - void ResetCell(const size_t size); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(InputType&& input, - ErrorType&& error, - GradientType&& gradient); - - //! Get the maximum number of steps to backpropagate through time (BPTT). - size_t Rho() const { return rho; } - //! Modify the maximum number of steps to backpropagate through time (BPTT). - size_t& Rho() { return rho; } - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return grad; } - //! Modify the gradient. - OutputDataType& Gradient() { return grad; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Number of steps to backpropagate through time (BPTT). - size_t rho; - - //! Locally-stored number of forward steps. - size_t forwardStep; - - //! Locally-stored number of backward steps. - size_t backwardStep; - - //! Locally-stored number of gradient steps. - size_t gradientStep; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored previous output. - OutputDataType prevOutput; - - //! Locally-stored batch size. - size_t batchSize; - - //! Current batch step, alias for batchSize - 1. - size_t batchStep; - - //! Current gradient step to keep track of the backpropagate through time - //! step. - size_t gradientStepIdx; - - //! Locally-stored cell activation error. - OutputDataType cellActivationError; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType grad; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Weights between the output and input gate. - OutputDataType output2GateInputWeight; - - //! Weights between the input and gate. - OutputDataType input2GateInputWeight; - - //! Bias between the input and input gate. - OutputDataType input2GateInputBias; - - //! Weights between the cell and input gate. - OutputDataType cell2GateInputWeight; - - //! Weights between the output and forget gate. - OutputDataType output2GateForgetWeight; - - //! Weights between the input and gate. - OutputDataType input2GateForgetWeight; - - //! Bias between the input and gate. - OutputDataType input2GateForgetBias; - - //! Bias between the input and gate. - OutputDataType cell2GateForgetWeight; - - //! Weights between the output and gate. - OutputDataType output2GateOutputWeight; - - //! Weights between the input and gate. - OutputDataType input2GateOutputWeight; - - //! Bias between the input and gate. - OutputDataType input2GateOutputBias; - - //! Weights between cell and output gate. - OutputDataType cell2GateOutputWeight; - - //! Locally-stored input gate parameter. - OutputDataType inputGate; - - //! Locally-stored forget gate parameter. - OutputDataType forgetGate; - - //! Locally-stored hidden layer parameter. - OutputDataType hiddenLayer; - - //! Locally-stored output gate parameter. - OutputDataType outputGate; - - //! Locally-stored input gate activation. - OutputDataType inputGateActivation; - - //! Locally-stored forget gate activation. - OutputDataType forgetGateActivation; - - //! Locally-stored output gate activation. - OutputDataType outputGateActivation; - - //! Locally-stored hidden layer activation. - OutputDataType hiddenLayerActivation; - - //! Locally-stored input to hidden weight. - OutputDataType input2HiddenWeight; - - //! Locally-stored input to hidden bias. - OutputDataType input2HiddenBias; - - //! Locally-stored output to hidden weight. - OutputDataType output2HiddenWeight; - - //! Locally-stored cell parameter. - OutputDataType cell; - - //! Locally-stored cell activation error. - OutputDataType cellActivation; - - //! Locally-stored forget gate error. - OutputDataType forgetGateError; - - //! Locally-stored output gate error. - OutputDataType outputGateError; - - //! Locally-stored previous error. - OutputDataType prevError; - - //! Locally-stored output parameters. - OutputDataType outParameter; - - //! Locally-stored input cell error parameter. - OutputDataType inputCellError; - - //! Locally-stored input gate error. - OutputDataType inputGateError; - - //! Locally-stored hidden layer error. - OutputDataType hiddenError; - - //! Locally-stored current rho size. - size_t rhoSize; - - //! Current backpropagate through time steps. - size_t bpttSteps; -}; // class LSTM - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "lstm_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/lstm_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/lstm_impl.hpp deleted file mode 100644 index ea06e8e61..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/lstm_impl.hpp +++ /dev/null @@ -1,458 +0,0 @@ -/** - * @file lstm_impl.hpp - * @author Marcus Edel - * - * Implementation of the LSTM class, which implements a lstm network layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_LSTM_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_LSTM_IMPL_HPP - -// In case it hasn't yet been included. -#include "lstm.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -LSTM::LSTM() -{ - // Nothing to do here. -} - -template -LSTM::LSTM( - const size_t inSize, const size_t outSize, const size_t rho) : - inSize(inSize), - outSize(outSize), - rho(rho), - forwardStep(0), - backwardStep(0), - gradientStep(0), - batchSize(0), - batchStep(0), - gradientStepIdx(0), - rhoSize(rho), - bpttSteps(0) -{ - weights.set_size(4 * outSize * inSize + 7 * outSize + - 4 * outSize * outSize, 1); -} - -template -void LSTM::ResetCell(const size_t size) -{ - if (size == std::numeric_limits::max()) - return; - - rhoSize = size; - - if (batchSize == 0) - return; - - bpttSteps = std::min(rho, rhoSize); - forwardStep = 0; - gradientStepIdx = 0; - backwardStep = batchSize * size - 1; - gradientStep = batchSize * size - 1; - - const size_t rhoBatchSize = size * batchSize; - if (inputGate.is_empty() || inputGate.n_cols < rhoBatchSize) - { - inputGate.set_size(outSize, rhoBatchSize); - forgetGate.set_size(outSize, rhoBatchSize); - hiddenLayer.set_size(outSize, rhoBatchSize); - outputGate.set_size(outSize, rhoBatchSize); - - inputGateActivation.set_size(outSize, rhoBatchSize); - forgetGateActivation.set_size(outSize, rhoBatchSize); - outputGateActivation.set_size(outSize, rhoBatchSize); - hiddenLayerActivation.set_size(outSize, rhoBatchSize); - - cellActivation.set_size(outSize, rhoBatchSize); - prevError.set_size(4 * outSize, batchSize); - - if (cell.is_empty()) - { - cell = arma::zeros(outSize, size * batchSize); - outParameter = arma::zeros( - outSize, (size + 1) * batchSize); - } - else - { - // To preserve the leading zeros, recreate the object according to given - // size specifications, while preserving the elements as well as the - // layout of the elements. - cell.resize(outSize, size * batchSize); - outParameter.resize(outSize, (size + 1) * batchSize); - } - } -} - -template -void LSTM::Reset() -{ - // Set the weight parameter for the output gate. - input2GateOutputWeight = OutputDataType(weights.memptr(), outSize, inSize, - false, false); - input2GateOutputBias = OutputDataType(weights.memptr() + - input2GateOutputWeight.n_elem, outSize, 1, false, false); - size_t offset = input2GateOutputWeight.n_elem + input2GateOutputBias.n_elem; - - // Set the weight parameter for the forget gate. - input2GateForgetWeight = OutputDataType(weights.memptr() + offset, - outSize, inSize, false, false); - input2GateForgetBias = OutputDataType(weights.memptr() + - offset + input2GateForgetWeight.n_elem, outSize, 1, false, false); - offset += input2GateForgetWeight.n_elem + input2GateForgetBias.n_elem; - - // Set the weight parameter for the input gate. - input2GateInputWeight = OutputDataType(weights.memptr() + - offset, outSize, inSize, false, false); - input2GateInputBias = OutputDataType(weights.memptr() + - offset + input2GateInputWeight.n_elem, outSize, 1, false, false); - offset += input2GateInputWeight.n_elem + input2GateInputBias.n_elem; - - // Set the weight parameter for the hidden gate. - input2HiddenWeight = OutputDataType(weights.memptr() + - offset, outSize, inSize, false, false); - input2HiddenBias = OutputDataType(weights.memptr() + - offset + input2HiddenWeight.n_elem, outSize, 1, false, false); - offset += input2HiddenWeight.n_elem + input2HiddenBias.n_elem; - - // Set the weight parameter for the output multiplication. - output2GateOutputWeight = OutputDataType(weights.memptr() + - offset, outSize, outSize, false, false); - offset += output2GateOutputWeight.n_elem; - - // Set the weight parameter for the output multiplication. - output2GateForgetWeight = OutputDataType(weights.memptr() + - offset, outSize, outSize, false, false); - offset += output2GateForgetWeight.n_elem; - - // Set the weight parameter for the input multiplication. - output2GateInputWeight = OutputDataType(weights.memptr() + - offset, outSize, outSize, false, false); - offset += output2GateInputWeight.n_elem; - - // Set the weight parameter for the hidden multiplication. - output2HiddenWeight = OutputDataType(weights.memptr() + - offset, outSize, outSize, false, false); - offset += output2HiddenWeight.n_elem; - - // Set the weight parameter for the cell multiplication. - cell2GateOutputWeight = OutputDataType(weights.memptr() + - offset, outSize, 1, false, false); - offset += cell2GateOutputWeight.n_elem; - - // Set the weight parameter for the cell - forget gate multiplication. - cell2GateForgetWeight = OutputDataType(weights.memptr() + - offset, outSize, 1, false, false); - offset += cell2GateOutputWeight.n_elem; - - // Set the weight parameter for the cell - input gate multiplication. - cell2GateInputWeight = OutputDataType(weights.memptr() + - offset, outSize, 1, false, false); -} - -template -template -void LSTM::Forward( - InputType&& input, OutputType&& output) -{ - // Check if the batch size changed, the number of cols is defines the input - // batch size. - if (input.n_cols != batchSize) - { - batchSize = input.n_cols; - batchStep = batchSize - 1; - ResetCell(rhoSize); - } - - inputGate.cols(forwardStep, forwardStep + batchStep) = input2GateInputWeight * - input + output2GateInputWeight * outParameter.cols(forwardStep, - forwardStep + batchStep); - inputGate.cols(forwardStep, forwardStep + batchStep).each_col() += - input2GateInputBias; - - forgetGate.cols(forwardStep, forwardStep + batchStep) = input2GateForgetWeight - * input + output2GateForgetWeight * outParameter.cols( - forwardStep, forwardStep + batchStep); - forgetGate.cols(forwardStep, forwardStep + batchStep).each_col() += - input2GateForgetBias; - - if (forwardStep > 0) - { - inputGate.cols(forwardStep, forwardStep + batchStep) += - arma::repmat(cell2GateInputWeight, 1, batchSize) % - cell.cols(forwardStep - batchSize, forwardStep - batchSize + batchStep); - - forgetGate.cols(forwardStep, forwardStep + batchStep) += - arma::repmat(cell2GateForgetWeight, 1, batchSize) % - cell.cols(forwardStep - batchSize, forwardStep - batchSize + batchStep); - } - - inputGateActivation.cols(forwardStep, forwardStep + batchStep) = 1.0 / - (1 + arma::exp(-inputGate.cols(forwardStep, forwardStep + batchStep))); - - forgetGateActivation.cols(forwardStep, forwardStep + batchStep) = 1.0 / - (1 + arma::exp(-forgetGate.cols(forwardStep, forwardStep + batchStep))); - - hiddenLayer.cols(forwardStep, forwardStep + batchStep) = input2HiddenWeight * - input + output2HiddenWeight * outParameter.cols( - forwardStep, forwardStep + batchStep); - - hiddenLayer.cols(forwardStep, forwardStep + batchStep).each_col() += - input2HiddenBias; - - hiddenLayerActivation.cols(forwardStep, forwardStep + batchStep) = - arma::tanh(hiddenLayer.cols(forwardStep, forwardStep + batchStep)); - - if (forwardStep == 0) - { - cell.cols(forwardStep, forwardStep + batchStep) = - inputGateActivation.cols(forwardStep, forwardStep + batchStep) % - hiddenLayerActivation.cols(forwardStep, forwardStep + batchStep); - } - else - { - cell.cols(forwardStep, forwardStep + batchStep) = - forgetGateActivation.cols(forwardStep, forwardStep + batchStep) % - cell.cols(forwardStep - batchSize, forwardStep - batchSize + batchStep) - + inputGateActivation.cols(forwardStep, forwardStep + batchStep) % - hiddenLayerActivation.cols(forwardStep, forwardStep + batchStep); - } - - outputGate.cols(forwardStep, forwardStep + batchStep) = input2GateOutputWeight - * input + output2GateOutputWeight * outParameter.cols( - forwardStep, forwardStep + batchStep) + cell.cols(forwardStep, - forwardStep + batchStep).each_col() % cell2GateOutputWeight; - - outputGate.cols(forwardStep, forwardStep + batchStep).each_col() += - input2GateOutputBias; - - outputGateActivation.cols(forwardStep, forwardStep + batchStep) = 1.0 / - (1 + arma::exp(-outputGate.cols(forwardStep, forwardStep + batchStep))); - - cellActivation.cols(forwardStep, forwardStep + batchStep) = - arma::tanh(cell.cols(forwardStep, forwardStep + batchStep)); - - outParameter.cols(forwardStep + batchSize, - forwardStep + batchSize + batchStep) = - cellActivation.cols(forwardStep, forwardStep + batchStep) % - outputGateActivation.cols(forwardStep, forwardStep + batchStep); - - output = OutputType(outParameter.memptr() + - (forwardStep + batchSize) * outSize, outSize, batchSize, false, false); - - forwardStep += batchSize; - if ((forwardStep / batchSize) == bpttSteps) - { - forwardStep = 0; - } -} - -template -template -void LSTM::Backward( - const InputType&& /* input */, ErrorType&& gy, GradientType&& g) -{ - if (gradientStepIdx > 0) - { - gy += prevError; - } - - outputGateError = - gy % cellActivation.cols(backwardStep - batchStep, backwardStep) % - (outputGateActivation.cols(backwardStep - batchStep, backwardStep) % - (1.0 - outputGateActivation.cols(backwardStep - batchStep, - backwardStep))); - - OutputDataType cellError = gy % - outputGateActivation.cols(backwardStep - batchStep, backwardStep) % - (1 - arma::pow(cellActivation.cols(backwardStep - - batchStep, backwardStep), 2)) + outputGateError.each_col() % - cell2GateOutputWeight; - - if (gradientStepIdx > 0) - { - cellError += inputCellError; - } - - if (backwardStep > batchStep) - { - forgetGateError = cell.cols((backwardStep - batchSize) - batchStep, - (backwardStep - batchSize)) % cellError % (forgetGateActivation.cols( - backwardStep - batchStep, backwardStep) % (1.0 - - forgetGateActivation.cols(backwardStep - batchStep, backwardStep))); - } - else - { - forgetGateError.zeros(); - } - - inputGateError = hiddenLayerActivation.cols(backwardStep - batchStep, - backwardStep) % cellError % - (inputGateActivation.cols(backwardStep - batchStep, backwardStep) % - (1.0 - inputGateActivation.cols(backwardStep - batchStep, backwardStep))); - - hiddenError = inputGateActivation.cols(backwardStep - batchStep, - backwardStep) % cellError % (1 - arma::pow(hiddenLayerActivation.cols( - backwardStep - batchStep, backwardStep), 2)); - - inputCellError = forgetGateActivation.cols(backwardStep - batchStep, - backwardStep) % cellError + forgetGateError.each_col() % - cell2GateForgetWeight + inputGateError.each_col() % cell2GateInputWeight; - - g = input2GateInputWeight.t() * inputGateError + - input2HiddenWeight.t() * hiddenError + - input2GateForgetWeight.t() * forgetGateError + - input2GateOutputWeight.t() * outputGateError; - - prevError = output2GateOutputWeight.t() * outputGateError + - output2GateForgetWeight.t() * forgetGateError + - output2GateInputWeight.t() * inputGateError + - output2HiddenWeight.t() * hiddenError; - - backwardStep -= batchSize; - gradientStepIdx++; - if (gradientStepIdx == bpttSteps) - { - backwardStep = bpttSteps - 1; - gradientStepIdx = 0; - } -} - -template -template -void LSTM::Gradient( - InputType&& input, ErrorType&& /* error */, GradientType&& gradient) -{ - // Input2GateOutputWeight and input2GateOutputBias gradients. - gradient.submat(0, 0, input2GateOutputWeight.n_elem - 1, 0) = - arma::vectorise(outputGateError * input.t()); - gradient.submat(input2GateOutputWeight.n_elem, 0, - input2GateOutputWeight.n_elem + input2GateOutputBias.n_elem - 1, 0) = - arma::sum(outputGateError, 1); - size_t offset = input2GateOutputWeight.n_elem + input2GateOutputBias.n_elem; - - // Input2GateForgetWeight and input2GateForgetBias gradients. - gradient.submat(offset, 0, offset + input2GateForgetWeight.n_elem - 1, 0) = - arma::vectorise(forgetGateError * input.t()); - gradient.submat(offset + input2GateForgetWeight.n_elem, 0, - offset + input2GateForgetWeight.n_elem + - input2GateForgetBias.n_elem - 1, 0) = arma::sum(forgetGateError, 1); - offset += input2GateForgetWeight.n_elem + input2GateForgetBias.n_elem; - - // Input2GateInputWeight and input2GateInputBias gradients. - gradient.submat(offset, 0, offset + input2GateInputWeight.n_elem - 1, 0) = - arma::vectorise(inputGateError * input.t()); - gradient.submat(offset + input2GateInputWeight.n_elem, 0, - offset + input2GateInputWeight.n_elem + - input2GateInputBias.n_elem - 1, 0) = arma::sum(inputGateError, 1); - offset += input2GateInputWeight.n_elem + input2GateInputBias.n_elem; - - // Input2HiddenWeight and input2HiddenBias gradients. - gradient.submat(offset, 0, offset + input2HiddenWeight.n_elem - 1, 0) = - arma::vectorise(hiddenError * input.t()); - gradient.submat(offset + input2HiddenWeight.n_elem, 0, - offset + input2HiddenWeight.n_elem + input2HiddenBias.n_elem - 1, 0) = - arma::sum(hiddenError, 1); - offset += input2HiddenWeight.n_elem + input2HiddenBias.n_elem; - - // Output2GateOutputWeight gradients. - gradient.submat(offset, 0, offset + output2GateOutputWeight.n_elem - 1, 0) = - arma::vectorise(outputGateError * - outParameter.cols(gradientStep - batchStep, gradientStep).t()); - offset += output2GateOutputWeight.n_elem; - - // Output2GateForgetWeight gradients. - gradient.submat(offset, 0, offset + output2GateForgetWeight.n_elem - 1, 0) = - arma::vectorise(forgetGateError * - outParameter.cols(gradientStep - batchStep, gradientStep).t()); - offset += output2GateForgetWeight.n_elem; - - // Output2GateInputWeight gradients. - gradient.submat(offset, 0, offset + output2GateInputWeight.n_elem - 1, 0) = - arma::vectorise(inputGateError * - outParameter.cols(gradientStep - batchStep, gradientStep).t()); - offset += output2GateInputWeight.n_elem; - - // Output2HiddenWeight gradients. - gradient.submat(offset, 0, offset + output2HiddenWeight.n_elem - 1, 0) = - arma::vectorise(hiddenError * - outParameter.cols(gradientStep - batchStep, gradientStep).t()); - offset += output2HiddenWeight.n_elem; - - // Cell2GateOutputWeight gradients. - gradient.submat(offset, 0, offset + cell2GateOutputWeight.n_elem - 1, 0) = - arma::sum(outputGateError % - cell.cols(gradientStep - batchStep, gradientStep), 1); - offset += cell2GateOutputWeight.n_elem; - - // Cell2GateForgetWeight and cell2GateInputWeight gradients. - if (gradientStep > batchStep) - { - gradient.submat(offset, 0, offset + cell2GateForgetWeight.n_elem - 1, 0) = - arma::sum(forgetGateError % - cell.cols((gradientStep - batchSize) - batchStep, - (gradientStep - batchSize)), 1); - gradient.submat(offset + cell2GateForgetWeight.n_elem, 0, offset + - cell2GateForgetWeight.n_elem + cell2GateInputWeight.n_elem - 1, 0) = - arma::sum(inputGateError % - cell.cols((gradientStep - batchSize) - batchStep, - (gradientStep - batchSize)), 1); - } - else - { - gradient.submat(offset, 0, offset + - cell2GateForgetWeight.n_elem - 1, 0).zeros(); - gradient.submat(offset + cell2GateForgetWeight.n_elem, 0, offset + - cell2GateForgetWeight.n_elem + - cell2GateInputWeight.n_elem - 1, 0).zeros(); - } - - if (gradientStep == 0) - { - gradientStep = batchSize * bpttSteps - 1; - } - else - { - gradientStep -= batchSize; - } -} - -template -template -void LSTM::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(weights); - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); - ar & BOOST_SERIALIZATION_NVP(rho); - ar & BOOST_SERIALIZATION_NVP(bpttSteps); - ar & BOOST_SERIALIZATION_NVP(batchSize); - ar & BOOST_SERIALIZATION_NVP(batchStep); - ar & BOOST_SERIALIZATION_NVP(forwardStep); - ar & BOOST_SERIALIZATION_NVP(backwardStep); - ar & BOOST_SERIALIZATION_NVP(gradientStep); - ar & BOOST_SERIALIZATION_NVP(gradientStepIdx); - ar & BOOST_SERIALIZATION_NVP(cell); - ar & BOOST_SERIALIZATION_NVP(inputGateActivation); - ar & BOOST_SERIALIZATION_NVP(forgetGateActivation); - ar & BOOST_SERIALIZATION_NVP(outputGateActivation); - ar & BOOST_SERIALIZATION_NVP(hiddenLayerActivation); - ar & BOOST_SERIALIZATION_NVP(cellActivation); - ar & BOOST_SERIALIZATION_NVP(prevError); - ar & BOOST_SERIALIZATION_NVP(outParameter); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/max_pooling.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/max_pooling.hpp deleted file mode 100644 index 000181995..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/max_pooling.hpp +++ /dev/null @@ -1,278 +0,0 @@ -/** - * @file max_pooling.hpp - * @author Marcus Edel - * @author Nilay Jain - * - * Definition of the MaxPooling class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_MAX_POOLING_HPP -#define MLPACK_METHODS_ANN_LAYER_MAX_POOLING_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/* - * The max pooling rule for convolution neural networks. Take the maximum value - * within the receptive block. - */ -class MaxPoolingRule -{ - public: - /* - * Return the maximum value within the receptive block. - * - * @param input Input used to perform the pooling operation. - */ - template - size_t Pooling(const MatType& input) - { - return arma::as_scalar(arma::find(input.max() == input, 1)); - } -}; - -/** - * Implementation of the MaxPooling layer. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class MaxPooling -{ - public: - //! Create the MaxPooling object. - MaxPooling(); - - /** - * Create the MaxPooling object using the specified number of units. - * - * @param kW Width of the pooling window. - * @param kH Height of the pooling window. - * @param dW Width of the stride operation. - * @param dH Width of the stride operation. - * @param floor Rounding operator (floor or ceil). - */ - MaxPooling(const size_t kW, - const size_t kH, - const size_t dW = 1, - const size_t dH = 1, - const bool floor = true); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, using 3rd-order tensors as - * input, calculating the function f(x) by propagating x backwards through f. - * Using the results from the feed forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the width. - size_t const& InputWidth() const { return inputWidth; } - //! Modify the width. - size_t& InputWidth() { return inputWidth; } - - //! Get the height. - size_t const& InputHeight() const { return inputHeight; } - //! Modify the height. - size_t& InputHeight() { return inputHeight; } - - //! Get the width. - size_t const& OutputWidth() const { return outputWidth; } - //! Modify the width. - size_t& OutputWidth() { return outputWidth; } - - //! Get the height. - size_t const& OutputHeight() const { return outputHeight; } - //! Modify the height. - size_t& OutputHeight() { return outputHeight; } - - //! Get the value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /** - * Apply pooling to the input and store the results. - * - * @param input The input to be apply the pooling rule. - * @param output The pooled result. - * @param poolingIndices The pooled indices. - */ - template - void PoolingOperation(const arma::Mat& input, - arma::Mat& output, - arma::Mat& poolingIndices) - { - for (size_t j = 0, colidx = 0; j < output.n_cols; ++j, colidx += dW) - { - for (size_t i = 0, rowidx = 0; i < output.n_rows; ++i, rowidx += dH) - { - arma::mat subInput = input(arma::span(rowidx, rowidx + kW - 1 - offset), - arma::span(colidx, colidx + kH - 1 - offset)); - - const size_t idx = pooling.Pooling(subInput); - output(i, j) = subInput(idx); - - if (!deterministic) - { - arma::Mat subIndices = indices(arma::span(rowidx, - rowidx + kW - 1 - offset), - arma::span(colidx, colidx + kH - 1 - offset)); - - poolingIndices(i, j) = subIndices(idx); - } - } - } - } - - /** - * Apply unpooling to the input and store the results. - * - * @param error The backward error. - * @param output The pooled result. - * @param poolingIndices The pooled indices. - */ - template - void Unpooling(const arma::Mat& error, - arma::Mat& output, - arma::Mat& poolingIndices) - { - for (size_t i = 0; i < poolingIndices.n_elem; ++i) - { - output(poolingIndices(i)) += error(i); - } - } - - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored width of the pooling window. - size_t kW; - - //! Locally-stored height of the pooling window. - size_t kH; - - //! Locally-stored width of the stride operation. - size_t dW; - - //! Locally-stored height of the stride operation. - size_t dH; - - //! Locally-stored reset parameter used to initialize the module once. - bool reset; - - //! Rounding operation used. - bool floor; - - //! Locally-stored stored rounding offset. - size_t offset; - - //! Locally-stored input width. - size_t inputWidth; - - //! Locally-stored input height. - size_t inputHeight; - - //! Locally-stored output width. - size_t outputWidth; - - //! Locally-stored output height. - size_t outputHeight; - - //! If true use maximum a posteriori during the forward pass. - bool deterministic; - - //! Locally-stored output parameter. - arma::cube outputTemp; - - //! Locally-stored transformed input parameter. - arma::cube inputTemp; - - //! Locally-stored transformed output parameter. - arma::cube gTemp; - - //! Locally-stored pooling strategy. - MaxPoolingRule pooling; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored indices matrix parameter. - arma::Mat indices; - - //! Locally-stored indices column parameter. - arma::Col indicesCol; - - //! Locally-stored pooling indicies. - std::vector poolingIndices; -}; // class MaxPooling - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "max_pooling_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/max_pooling_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/max_pooling_impl.hpp deleted file mode 100644 index 13ff201c5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/max_pooling_impl.hpp +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @file max_pooling_impl.hpp - * @author Marcus Edel - * @author Nilay Jain - * - * Implementation of the MaxPooling class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_MAX_POOLING_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_MAX_POOLING_IMPL_HPP - -// In case it hasn't yet been included. -#include "max_pooling.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -MaxPooling::MaxPooling() -{ - // Nothing to do here. -} - -template -MaxPooling::MaxPooling( - const size_t kW, - const size_t kH, - const size_t dW, - const size_t dH, - const bool floor) : - kW(kW), - kH(kH), - dW(dW), - dH(dH), - reset(false), - floor(floor), - offset(0), - inputWidth(0), - inputHeight(0), - outputWidth(0), - outputHeight(0), - deterministic(false) -{ - // Nothing to do here. -} - -template -template -void MaxPooling::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - const size_t slices = input.n_elem / (inputWidth * inputHeight); - inputTemp = arma::cube(input.memptr(), inputWidth, inputHeight, slices); - - if (floor) - { - outputWidth = std::floor((inputWidth - (double) kW) / (double) dW + 1); - outputHeight = std::floor((inputHeight - (double) kH) / (double) dH + 1); - offset = 0; - } - else - { - outputWidth = std::ceil((inputWidth - (double) kW) / (double) dW + 1); - outputHeight = std::ceil((inputHeight - (double) kH) / (double) dH + 1); - offset = 1; - } - - outputTemp = arma::zeros >(outputWidth, outputHeight, - slices); - - if (!deterministic) - { - poolingIndices.push_back(outputTemp); - } - - if (!reset) - { - size_t elements = inputWidth * inputHeight; - indicesCol = arma::linspace >(0, (elements - 1), - elements); - - indices = arma::Mat(indicesCol.memptr(), inputWidth, inputHeight); - - reset = true; - } - - for (size_t s = 0; s < inputTemp.n_slices; s++) - { - if (!deterministic) - { - PoolingOperation(inputTemp.slice(s), outputTemp.slice(s), - poolingIndices.back().slice(s)); - } - else - { - PoolingOperation(inputTemp.slice(s), outputTemp.slice(s), - inputTemp.slice(s)); - } - } - - output = arma::Mat(outputTemp.memptr(), outputTemp.n_elem, 1); - - outputWidth = outputTemp.n_rows; - outputHeight = outputTemp.n_cols; - outSize = slices; -} - -template -template -void MaxPooling::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - arma::cube mappedError = arma::cube(gy.memptr(), outputWidth, - outputHeight, outSize); - - gTemp = arma::zeros(inputTemp.n_rows, - inputTemp.n_cols, inputTemp.n_slices); - - for (size_t s = 0; s < mappedError.n_slices; s++) - { - Unpooling(mappedError.slice(s), gTemp.slice(s), - poolingIndices.back().slice(s)); - } - - poolingIndices.pop_back(); - - g = arma::mat(gTemp.memptr(), gTemp.n_elem, 1); -} - -template -template -void MaxPooling::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(kW); - ar & BOOST_SERIALIZATION_NVP(kH); - ar & BOOST_SERIALIZATION_NVP(dW); - ar & BOOST_SERIALIZATION_NVP(dH); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/mean_pooling.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/mean_pooling.hpp deleted file mode 100644 index 3c77d3096..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/mean_pooling.hpp +++ /dev/null @@ -1,251 +0,0 @@ -/** - * @file mean_pooling.hpp - * @author Marcus Edel - * @author Nilay Jain - * - * Definition of the MeanPooling layer class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_MEAN_POOLING_HPP -#define MLPACK_METHODS_ANN_LAYER_MEAN_POOLING_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the MeanPooling. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class MeanPooling -{ - public: - //! Create the MeanPooling object. - MeanPooling(); - - /** - * Create the MeanPooling object using the specified number of units. - * - * @param kW Width of the pooling window. - * @param kH Height of the pooling window. - * @param dW Width of the stride operation. - * @param dH Width of the stride operation. - */ - MeanPooling(const size_t kW, - const size_t kH, - const size_t dW = 1, - const size_t dH = 1, - const bool floor = true); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, using 3rd-order tensors as - * input, calculating the function f(x) by propagating x backwards through f. - * Using the results from the feed forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the width. - size_t const& InputWidth() const { return inputWidth; } - //! Modify the width. - size_t& InputWidth() { return inputWidth; } - - //! Get the height. - size_t const& InputHeight() const { return inputHeight; } - //! Modify the height. - size_t& InputHeight() { return inputHeight; } - - //! Get the width. - size_t const& OutputWidth() const { return outputWidth; } - //! Modify the width. - size_t& OutputWidth() { return outputWidth; } - - //! Get the height. - size_t const& OutputHeight() const { return outputHeight; } - //! Modify the height. - size_t& OutputHeight() { return outputHeight; } - - //! Get the value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /** - * Apply pooling to the input and store the results. - * - * @param input The input to be apply the pooling rule. - * @param output The pooled result. - */ - template - void Pooling(const arma::Mat& input, arma::Mat& output) - { - const size_t rStep = kW; - const size_t cStep = kH; - - for (size_t j = 0, colidx = 0; j < output.n_cols; ++j, colidx += dH) - { - for (size_t i = 0, rowidx = 0; i < output.n_rows; ++i, rowidx += dW) - { - arma::mat subInput = input( - arma::span(rowidx, rowidx + rStep - 1 - offset), - arma::span(colidx, colidx + cStep - 1 - offset)); - - output(i, j) = arma::mean(arma::mean(subInput)); - } - } - } - - /** - * Apply unpooling to the input and store the results. - * - * @param input The input to be apply the unpooling rule. - * @param output The pooled result. - */ - template - void Unpooling(const arma::Mat& input, - const arma::Mat& error, - arma::Mat& output) - { - const size_t rStep = input.n_rows / error.n_rows - offset; - const size_t cStep = input.n_cols / error.n_cols - offset; - - arma::Mat unpooledError; - for (size_t j = 0; j < input.n_cols - cStep; j += cStep) - { - for (size_t i = 0; i < input.n_rows - rStep; i += rStep) - { - const arma::Mat& inputArea = input(arma::span(i, i + rStep - 1), - arma::span(j, j + cStep - 1)); - - unpooledError = arma::Mat(inputArea.n_rows, inputArea.n_cols); - unpooledError.fill(error(i / rStep, j / cStep) / inputArea.n_elem); - - output(arma::span(i, i + rStep - 1 - offset), - arma::span(j, j + cStep - 1 - offset)) += unpooledError; - } - } - } - - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored width of the pooling window. - size_t kW; - - //! Locally-stored height of the pooling window. - size_t kH; - - //! Locally-stored width of the stride operation. - size_t dW; - - //! Locally-stored height of the stride operation. - size_t dH; - - //! Locally-stored input width. - size_t inputWidth; - - //! Locally-stored input height. - size_t inputHeight; - - //! Locally-stored output width. - size_t outputWidth; - - //! Locally-stored output height. - size_t outputHeight; - - //! Locally-stored reset parameter used to initialize the module once. - bool reset; - - //! Rounding operation used. - bool floor; - - //! If true use maximum a posteriori during the forward pass. - bool deterministic; - - //! Locally-stored stored rounding offset. - size_t offset; - - //! Locally-stored output parameter. - arma::cube outputTemp; - - //! Locally-stored transformed input parameter. - arma::cube inputTemp; - - //! Locally-stored transformed output parameter. - arma::cube gTemp; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class MeanPooling - - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "mean_pooling_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/mean_pooling_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/mean_pooling_impl.hpp deleted file mode 100644 index 900843e29..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/mean_pooling_impl.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @file mean_pooling_impl.hpp - * @author Marcus Edel - * @author Nilay Jain - * - * Implementation of the MeanPooling layer class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_MEAN_POOLING_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_MEAN_POOLING_IMPL_HPP - -// In case it hasn't yet been included. -#include "mean_pooling.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -MeanPooling::MeanPooling() -{ - // Nothing to do here. -} - -template -MeanPooling::MeanPooling( - const size_t kW, - const size_t kH, - const size_t dW, - const size_t dH, - const bool floor) : - kW(kW), - kH(kH), - dW(dW), - dH(dH), - inputWidth(0), - inputHeight(0), - outputWidth(0), - outputHeight(0), - reset(false), - floor(floor), - deterministic(false), - offset(0) -{ - // Nothing to do here. -} - -template -template -void MeanPooling::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - size_t slices = input.n_elem / (inputWidth * inputHeight); - inputTemp = arma::cube(input.memptr(), inputWidth, inputHeight, slices); - - if (floor) - { - outputWidth = std::floor((inputWidth - (double) kW) / (double) dW + 1); - outputHeight = std::floor((inputHeight - (double) kH) / (double) dH + 1); - - offset = 0; - } - else - { - outputWidth = std::ceil((inputWidth - (double) kW) / (double) dW + 1); - outputHeight = std::ceil((inputHeight - (double) kH) / (double) dH + 1); - - offset = 1; - } - - outputTemp = arma::zeros >(outputWidth, outputHeight, - slices); - - for (size_t s = 0; s < inputTemp.n_slices; s++) - Pooling(inputTemp.slice(s), outputTemp.slice(s)); - - output = arma::Mat(outputTemp.memptr(), outputTemp.n_elem, 1); - - outputWidth = outputTemp.n_rows; - outputHeight = outputTemp.n_cols; - outSize = slices; -} - -template -template -void MeanPooling::Backward( - const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g) -{ - arma::cube mappedError = arma::cube(gy.memptr(), outputWidth, - outputHeight, outSize); - - gTemp = arma::zeros(inputTemp.n_rows, - inputTemp.n_cols, inputTemp.n_slices); - - for (size_t s = 0; s < mappedError.n_slices; s++) - { - Unpooling(inputTemp.slice(s), mappedError.slice(s), gTemp.slice(s)); - } - - g = arma::mat(gTemp.memptr(), gTemp.n_elem, 1); -} - -template -template -void MeanPooling::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(kW); - ar & BOOST_SERIALIZATION_NVP(kH); - ar & BOOST_SERIALIZATION_NVP(dW); - ar & BOOST_SERIALIZATION_NVP(dH); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_constant.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_constant.hpp deleted file mode 100644 index c07843888..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_constant.hpp +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @file multiply_constant.hpp - * @author Marcus Edel - * - * Definition of the MultiplyConstantLayer class, which multiplies the input by - * a (non-learnable) constant. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_MULTIPLY_CONSTANT_HPP -#define MLPACK_METHODS_ANN_LAYER_MULTIPLY_CONSTANT_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the multiply constant layer. The multiply constant layer - * multiplies the input by a (non-learnable) constant. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class MultiplyConstant -{ - public: - /** - * Create the MultiplyConstant object. - */ - MultiplyConstant(const double scalar = 1.0); - - /** - * Ordinary feed forward pass of a neural network. Multiply the input with the - * specified constant scalar value. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network. The backward pass - * multiplies the error with the specified constant scalar value. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const DataType&& /* input */, DataType&& gy, DataType&& g); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored constant scalar value. - double scalar; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class MultiplyConstant - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "multiply_constant_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_constant_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_constant_impl.hpp deleted file mode 100644 index 87d0007a9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_constant_impl.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @file multiply_constant_impl.hpp - * @author Marcus Edel - * - * Implementation of the MultiplyConstantLayer class, which multiplies the - * input by a (non-learnable) constant. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_MULTIPLY_CONSTANT_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_MULTIPLY_CONSTANT_IMPL_HPP - -// In case it hasn't yet been included. -#include "multiply_constant.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -MultiplyConstant::MultiplyConstant( - const double scalar) : scalar(scalar) -{ - // Nothing to do here. -} - -template -template -void MultiplyConstant::Forward( - const InputType&& input, OutputType&& output) -{ - output = input * scalar; -} - -template -template -void MultiplyConstant::Backward( - const DataType&& /* input */, DataType&& gy, DataType&& g) -{ - g = gy * scalar; -} - -template -template -void MultiplyConstant::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(scalar); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_merge.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_merge.hpp deleted file mode 100644 index 865f291d7..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_merge.hpp +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @file multiply_merge.hpp - * @author Haritha Nair - * - * Definition of the MultiplyMerge module which multiplies the output of the - * given modules element-wise. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_MULTIPLY_MERGE_HPP -#define MLPACK_METHODS_ANN_LAYER_MULTIPLY_MERGE_HPP - -#include - -#include "../visitor/delete_visitor.hpp" -#include "../visitor/delta_visitor.hpp" -#include "../visitor/output_parameter_visitor.hpp" - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the MultiplyMerge module class. The MultiplyMerge class - * multiplies the output of various modules element-wise. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam CustomLayers Additional custom layers that can be added. - */ -template< - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat, - typename... CustomLayers -> -class MultiplyMerge -{ - public: - /** - * Create the MultiplyMerge object using the specified parameters. - * - * @param model Expose all the network modules. - */ - MultiplyMerge(const bool model = false); - - //! Destructor to release allocated memory. - ~MultiplyMerge(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& /* input */, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f, using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - void Add(LayerTypes layer) { network.push_back(layer); } - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - template - void Add(const LayerType& layer) { network.push_back(new LayerType(layer)); } - - /* - * Add a new module to the model. - * - * @param args The layer parameter. - */ - template - void Add(Args... args) { network.push_back(new LayerType(args...)); } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Return the model modules. - std::vector >& Model() - { - if (model) - { - return network; - } - - return empty; - } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Parameter which indicates if the modules should be exposed. - bool model; - - //! We need this to know whether we should delete the layer in the destructor. - bool ownsLayer; - - //! Locally-stored network modules. - std::vector > network; - - //! Locally-stored empty list of modules. - std::vector > empty; - - //! Locally-stored delete visitor module object. - DeleteVisitor deleteVisitor; - - //! Locally-stored output parameter visitor module object. - OutputParameterVisitor outputParameterVisitor; - - //! Locally-stored delta visitor module object. - DeltaVisitor deltaVisitor; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class MultiplyMerge - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "multiply_merge_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_merge_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_merge_impl.hpp deleted file mode 100644 index 6738bac8c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/multiply_merge_impl.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file multiply_merge_impl.hpp - * @author Haritha Nair - * - * Definition of the MultiplyMerge module which multiplies the output of the - * given modules element-wise. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_MULTIPLY_MERGE_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_MULTIPLY_MERGE_IMPL_HPP - -// In case it hasn't yet been included. -#include "multiply_merge.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -MultiplyMerge::MultiplyMerge( - const bool model) : model(model), ownsLayer(!model) -{ - // Nothing to do here. -} - -template -MultiplyMerge::~MultiplyMerge() -{ - if (ownsLayer) - { - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deleteVisitor)); - } -} - -template -template -void MultiplyMerge::Forward( - const InputType&& /* input */, OutputType&& output) -{ - output = boost::apply_visitor(outputParameterVisitor, network.front()); - - for (size_t i = 1; i < network.size(); ++i) - { - output %= boost::apply_visitor(outputParameterVisitor, network[i]); - } -} - -template -template -void MultiplyMerge::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - g = gy; -} - -template -template -void MultiplyMerge::serialize( - Archive& ar, const unsigned int /* version */) -{ - if (Archive::is_loading::value) - network.clear(); - - ar & BOOST_SERIALIZATION_NVP(network); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/negative_log_likelihood.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/negative_log_likelihood.hpp deleted file mode 100644 index cd92765d1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/negative_log_likelihood.hpp +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @file negative_log_likelihood.hpp - * @author Marcus Edel - * - * Definition of the NegativeLogLikelihood class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_NEGATIVE_LOG_LIKELIHOOD_HPP -#define MLPACK_METHODS_ANN_LAYER_NEGATIVE_LOG_LIKELIHOOD_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the negative log likelihood layer. The negative log - * likelihood layer expectes that the input contains log-probabilities for each - * class. The layer also expects a class index, in the range between 1 and the - * number of classes, as target when calling the Forward function. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class NegativeLogLikelihood -{ - public: - /** - * Create the NegativeLogLikelihoodLayer object. - */ - NegativeLogLikelihood(); - - /* - * Computes the Negative log likelihood. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - double Forward(const InputType&& input, TargetType&& target); - - /** - * Ordinary feed backward pass of a neural network. The negative log - * likelihood layer expectes that the input contains log-probabilities for - * each class. The layer also expects a class index, in the range between 1 - * and the number of classes, as target when calling the Forward function. - * - * @param input The propagated input activation. - * @param target The target vector, that contains the class index in the range - * between 1 and the number of classes. - * @param output The calculated error. - */ - template - void Backward(const InputType&& input, - const TargetType&& target, - OutputType&& output); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class NegativeLogLikelihood - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "negative_log_likelihood_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/negative_log_likelihood_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/negative_log_likelihood_impl.hpp deleted file mode 100644 index 922546753..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/negative_log_likelihood_impl.hpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file negative_log_likelihood_impl.hpp - * @author Marcus Edel - * - * Implementation of the NegativeLogLikelihood class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_NEGATIVE_LOG_LIKELIHOOD_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_NEGATIVE_LOG_LIKELIHOOD_IMPL_HPP - -// In case it hasn't yet been included. -#include "negative_log_likelihood.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -NegativeLogLikelihood::NegativeLogLikelihood() -{ - // Nothing to do here. -} - -template -template -double NegativeLogLikelihood::Forward( - const InputType&& input, TargetType&& target) -{ - double output = 0; - for (size_t i = 0; i < input.n_cols; ++i) - { - size_t currentTarget = target(i) - 1; - Log::Assert(currentTarget >= 0 && currentTarget < input.n_rows, - "Target class out of range."); - - output -= input(currentTarget, i); - } - - return output; -} - -template -template -void NegativeLogLikelihood::Backward( - const InputType&& input, - const TargetType&& target, - OutputType&& output) -{ - output = arma::zeros(input.n_rows, input.n_cols); - for (size_t i = 0; i < input.n_cols; ++i) - { - size_t currentTarget = target(i) - 1; - Log::Assert(currentTarget >= 0 && currentTarget < input.n_rows, - "Target class out of range."); - - output(currentTarget, i) = -1; - } -} - -template -template -void NegativeLogLikelihood::serialize( - Archive& /* ar */, - const unsigned int /* version */) -{ - // Nothing to do here. -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/parametric_relu.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/parametric_relu.hpp deleted file mode 100644 index 8fcfc7e9c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/parametric_relu.hpp +++ /dev/null @@ -1,213 +0,0 @@ -/** - * @file parametric_relu.hpp - * @author Prasanna Patil - * - * Definition of PReLU layer first introduced in the, - * Kaiming He, Xiangyu Zhang, Shaoqing, Ren Jian Sun, - * "Delving Deep into Rectifiers: - * Surpassing Human-Level Performance on ImageNet Classification", 2014 - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_PReLU_HPP -#define MLPACK_METHODS_ANN_LAYER_PReLU_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The PReLU activation function, defined by (where alpha is trainable) - * - * @f{eqnarray*}{ - * f(x) &=& \max(x, alpha*x) \\ - * f'(x) &=& \left\{ - * \begin{array}{lr} - * 1 & : x > 0 \\ - * alpha & : x \le 0 - * \end{array} - * \right. - * @f} - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class PReLU -{ - public: - /** - * Create the PReLU object using the specified parameters. - * The non zero gradient can be adjusted by specifying tha parameter - * alpha in the range 0 to 1. Default (alpha = 0.03). This parameter - * is trainable. - * - * @param alpha Non zero gradient - */ - PReLU(const double userAlpha = 0.03); - - /* - * Reset the layer parameter. - */ - void Reset(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const InputType&& input, OutputType&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const DataType&& input, DataType&& gy, DataType&& g); - - /** - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return alpha; } - //! Modify the parameters. - OutputDataType& Parameters() { return alpha; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! Get the non zero gradient. - double const& Alpha() const { return alpha(0); } - //! Modify the non zero gradient. - double& Alpha() { return alpha(0); } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /** - * Computes the parametric ReLU function. - * - * @param x Input data. - * @return f(x). - */ - double Fn(const double x) - { - return std::max(x, alpha(0) * x); - } - - /** - * Computes the parametric ReLU function using a dense matrix as input. - * - * @param x Input data. - * @param y The resulting output activation. - */ - template - void Fn(const arma::Mat& x, arma::Mat& y) - { - y = x; - arma::uvec negative = arma::find(x < 0); - y(negative) = x(negative) * alpha(0); - } - - /** - * Computes the first derivative of the parametric ReLU function. - * - * @param x Input data. - * @return f'(x) - */ - double Deriv(const double x) - { - return (x >= 0) ? 1 : alpha(0); - } - - /** - * Computes the first derivative of the PReLU function. - * - * @param y Input activations. - * @param x The resulting derivatives. - */ - - template - void Deriv(const InputType& x, OutputType& y) - { - y = x; - - for (size_t i = 0; i < x.n_elem; i++) - { - y(i) = Deriv(x(i)); - } - } - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Leakyness Parameter object. - OutputDataType alpha; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Leakyness Parameter given by user in the range 0 < alpha < 1. - double userAlpha; -}; // class PReLU - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "parametric_relu_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/parametric_relu_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/parametric_relu_impl.hpp deleted file mode 100644 index 67bcb7e37..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/parametric_relu_impl.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file parametric_relu_impl.hpp - * @author Prasanna Patil - * - * Definition of PReLU layer first introduced in the, - * Kaiming He, Xiangyu Zhang, Shaoqing, Ren Jian Sun, - * "Delving Deep into Rectifiers: - * Surpassing Human-Level Performance on ImageNet Classification", 2014 - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_PReLU_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_PReLU_IMPL_HPP - -// In case it hasn't yet been included. -#include "parametric_relu.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -PReLU::PReLU( - const double userAlpha) : userAlpha(userAlpha) -{ - alpha.set_size(1, 1); - alpha(0) = userAlpha; -} - -template -void PReLU::Reset() -{ - //! Set value of alpha to the one given by user. - alpha(0) = userAlpha; -} - -template -template -void PReLU::Forward( - const InputType&& input, OutputType&& output) -{ - Fn(input, output); -} - -template -template -void PReLU::Backward( - const DataType&& input, DataType&& gy, DataType&& g) -{ - DataType derivative; - Deriv(input, derivative); - g = gy % derivative; -} - -template -template -void PReLU::Gradient( - const arma::Mat&& input, arma::Mat&& error, - arma::Mat&& gradient) -{ - if (gradient.n_elem == 0) - { - gradient = arma::zeros(1, 1); - } - - arma::mat zeros = arma::zeros(input.n_rows, input.n_cols); - gradient(0) = arma::accu(error % arma::min(zeros, input)) / input.n_cols; -} - -template -template -void PReLU::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(alpha); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent.hpp deleted file mode 100644 index e9e401274..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent.hpp +++ /dev/null @@ -1,234 +0,0 @@ -/** - * @file recurrent.hpp - * @author Marcus Edel - * - * Definition of the LinearLayer class also known as fully-connected layer or - * affine transformation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_RECURRENT_HPP -#define MLPACK_METHODS_ANN_LAYER_RECURRENT_HPP - -#include - -#include "../visitor/delete_visitor.hpp" -#include "../visitor/delta_visitor.hpp" -#include "../visitor/output_parameter_visitor.hpp" -#include "../visitor/weight_size_visitor.hpp" - -#include "layer_types.hpp" -#include "add_merge.hpp" -#include "sequential.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the RecurrentLayer class. Recurrent layers can be used - * similarly to feed-forward layers. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat, - typename... CustomLayers -> -class Recurrent -{ - public: - /** - * Default constructor---this will create a Recurrent object that can't be - * used, so be careful! Make sure to set all the parameters before use. - */ - Recurrent(); - - //! Destructor to release allocated memory. - ~Recurrent(); - - /** - * Create the Recurrent object using the specified modules. - * - * @param start The start module. - * @param input The input module. - * @param feedback The feedback module. - * @param transfer The transfer module. - * @param rho Maximum number of steps to backpropagate through time (BPTT). - */ - template - Recurrent(const StartModuleType& start, - const InputModuleType& input, - const FeedbackModuleType& feedback, - const TransferModuleType& transfer, - const size_t rho); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& /* gradient */); - - //! Get the model modules. - std::vector >& Model() { return network; } - - //! The value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - //! Get the parameters. - OutputDataType const& Parameters() const { return parameters; } - //! Modify the parameters. - OutputDataType& Parameters() { return parameters; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored delete visitor module object. - DeleteVisitor deleteVisitor; - - //! Locally-stored start module. - LayerTypes startModule; - - //! Locally-stored input module. - LayerTypes inputModule; - - //! Locally-stored feedback module. - LayerTypes feedbackModule; - - //! Locally-stored transfer module. - LayerTypes transferModule; - - //! Number of steps to backpropagate through time (BPTT). - size_t rho; - - //! Locally-stored number of forward steps. - size_t forwardStep; - - //! Locally-stored number of backward steps. - size_t backwardStep; - - //! Locally-stored number of gradient steps. - size_t gradientStep; - - //! If true dropout and scaling is disabled, see notes above. - bool deterministic; - - //! To know whether this object allocated memory. We need this to know - //! whether we should delete the metric member variable in the destructor. - bool ownsLayer; - - //! Locally-stored weight object. - OutputDataType parameters; - - //! Locally-stored initial module. - LayerTypes initialModule; - - //! Locally-stored recurrent module. - LayerTypes recurrentModule; - - //! Locally-stored model modules. - std::vector > network; - - //! Locally-stored merge module. - LayerTypes mergeModule; - - //! Locally-stored weight size visitor. - WeightSizeVisitor weightSizeVisitor; - - //! Locally-stored delta visitor. - DeltaVisitor deltaVisitor; - - //! Locally-stored output parameter visitor. - OutputParameterVisitor outputParameterVisitor; - - //! Locally-stored feedback output parameters. - std::vector feedbackOutputParameter; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored recurrent error parameter. - arma::mat recurrentError; -}; // class Recurrent - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "recurrent_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_attention.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_attention.hpp deleted file mode 100644 index b42f4d261..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_attention.hpp +++ /dev/null @@ -1,265 +0,0 @@ -/** - * @file recurrent_attention.hpp - * @author Marcus Edel - * - * Definition of the RecurrentAttention class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_RECURRENT_ATTENTION_HPP -#define MLPACK_METHODS_ANN_LAYER_RECURRENT_ATTENTION_HPP - -#include -#include - -#include "../visitor/delta_visitor.hpp" -#include "../visitor/output_parameter_visitor.hpp" -#include "../visitor/reset_visitor.hpp" -#include "../visitor/weight_size_visitor.hpp" - -#include "layer_types.hpp" -#include "add_merge.hpp" -#include "sequential.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * This class implements the Recurrent Model for Visual Attention, using a - * variety of possible layer implementations. - * - * For more information, see the following paper. - * - * @code - * @article{MnihHGK14, - * title={Recurrent Models of Visual Attention}, - * author={Volodymyr Mnih, Nicolas Heess, Alex Graves, Koray Kavukcuoglu}, - * journal={CoRR}, - * volume={abs/1406.6247}, - * year={2014} - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class RecurrentAttention -{ - public: - /** - * Default constructor: this will not give a usable RecurrentAttention object, - * so be sure to set all the parameters before use. - */ - RecurrentAttention(); - - /** - * Create the RecurrentAttention object using the specified modules. - * - * @param start The module output size. - * @param start The recurrent neural network module. - * @param start The action module. - * @param rho Maximum number of steps to backpropagate through time (BPTT). - */ - template - RecurrentAttention(const size_t outSize, - const RNNModuleType& rnn, - const ActionModuleType& action, - const size_t rho); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(arma::Mat&& /* input */, - arma::Mat&& /* error */, - arma::Mat&& /* gradient */); - - //! Get the model modules. - std::vector>& Model() { return network; } - - //! The value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - //! Get the parameters. - OutputDataType const& Parameters() const { return parameters; } - //! Modify the parameters. - OutputDataType& Parameters() { return parameters; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Calculate the gradient of the attention module. - void IntermediateGradient() - { - intermediateGradient.zeros(); - - // Gradient of the action module. - if (backwardStep == (rho - 1)) - { - boost::apply_visitor(GradientVisitor(std::move(initialInput), - std::move(actionError)), actionModule); - } - else - { - boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, actionModule)), std::move(actionError)), - actionModule); - } - - // Gradient of the recurrent module. - boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, rnnModule)), std::move(recurrentError)), - rnnModule); - - attentionGradient += intermediateGradient; - } - - //! Locally-stored module output size. - size_t outSize; - - //! Locally-stored start module. - LayerTypes<> rnnModule; - - //! Locally-stored input module. - LayerTypes<> actionModule; - - //! Number of steps to backpropagate through time (BPTT). - size_t rho; - - //! Locally-stored number of forward steps. - size_t forwardStep; - - //! Locally-stored number of backward steps. - size_t backwardStep; - - //! If true dropout and scaling is disabled, see notes above. - bool deterministic; - - //! Locally-stored weight object. - OutputDataType parameters; - - //! Locally-stored model modules. - std::vector> network; - - //! Locally-stored weight size visitor. - WeightSizeVisitor weightSizeVisitor; - - //! Locally-stored delta visitor. - DeltaVisitor deltaVisitor; - - //! Locally-stored output parameter visitor. - OutputParameterVisitor outputParameterVisitor; - - //! Locally-stored feedback output parameters. - std::vector feedbackOutputParameter; - - //! List of all module parameters for the backward pass (BBTT). - std::vector moduleOutputParameter; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored recurrent error parameter. - arma::mat recurrentError; - - //! Locally-stored action error parameter. - arma::mat actionError; - - //! Locally-stored action delta. - arma::mat actionDelta; - - //! Locally-stored recurrent delta. - arma::mat rnnDelta; - - //! Locally-stored initial action input. - arma::mat initialInput; - - //! Locally-stored reset visitor. - ResetVisitor resetVisitor; - - //! Locally-stored attention gradient. - arma::mat attentionGradient; - - //! Locally-stored intermediate gradient for the attention module. - arma::mat intermediateGradient; -}; // class RecurrentAttention - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "recurrent_attention_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_attention_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_attention_impl.hpp deleted file mode 100644 index b29e36982..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_attention_impl.hpp +++ /dev/null @@ -1,225 +0,0 @@ -/** - * @file recurrent_attention_impl.hpp - * @author Marcus Edel - * - * Implementation of the RecurrentAttention class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_RECURRENT_ATTENTION_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_RECURRENT_ATTENTION_IMPL_HPP - -// In case it hasn't yet been included. -#include "recurrent_attention.hpp" - -#include "../visitor/load_output_parameter_visitor.hpp" -#include "../visitor/save_output_parameter_visitor.hpp" -#include "../visitor/backward_visitor.hpp" -#include "../visitor/forward_visitor.hpp" -#include "../visitor/gradient_set_visitor.hpp" -#include "../visitor/gradient_update_visitor.hpp" -#include "../visitor/gradient_visitor.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -RecurrentAttention::RecurrentAttention() : - rho(0), - forwardStep(0), - backwardStep(0), - deterministic(false) -{ - // Nothing to do. -} - -template -template -RecurrentAttention::RecurrentAttention( - const size_t outSize, - const RNNModuleType& rnn, - const ActionModuleType& action, - const size_t rho) : - outSize(outSize), - rnnModule(new RNNModuleType(rnn)), - actionModule(new ActionModuleType(action)), - rho(rho), - forwardStep(0), - backwardStep(0), - deterministic(false) -{ - network.push_back(rnnModule); - network.push_back(actionModule); -} - -template -template -void RecurrentAttention::Forward( - arma::Mat&& input, arma::Mat&& output) -{ - // Initialize the action input. - if (initialInput.is_empty()) - { - initialInput = arma::zeros(outSize, input.n_cols); - } - - // Propagate through the action and recurrent module. - for (forwardStep = 0; forwardStep < rho; ++forwardStep) - { - if (forwardStep == 0) - { - boost::apply_visitor(ForwardVisitor(std::move(initialInput), std::move( - boost::apply_visitor(outputParameterVisitor, actionModule))), - actionModule); - } - else - { - boost::apply_visitor(ForwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, rnnModule)), std::move(boost::apply_visitor( - outputParameterVisitor, actionModule))), actionModule); - } - - // Initialize the glimpse input. - arma::mat glimpseInput = arma::zeros(input.n_elem, 2); - glimpseInput.col(0) = input; - glimpseInput.submat(0, 1, boost::apply_visitor(outputParameterVisitor, - actionModule).n_elem - 1, 1) = boost::apply_visitor( - outputParameterVisitor, actionModule); - - boost::apply_visitor(ForwardVisitor(std::move(glimpseInput), - std::move(boost::apply_visitor(outputParameterVisitor, rnnModule))), - rnnModule); - - // Save the output parameter when training the module. - if (!deterministic) - { - for (size_t l = 0; l < network.size(); ++l) - { - boost::apply_visitor(SaveOutputParameterVisitor( - std::move(moduleOutputParameter)), network[l]); - } - } - } - - output = boost::apply_visitor(outputParameterVisitor, rnnModule); - - forwardStep = 0; - backwardStep = 0; -} - -template -template -void RecurrentAttention::Backward( - const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g) -{ - if (intermediateGradient.is_empty() && backwardStep == 0) - { - // Initialize the attention gradients. - size_t weights = boost::apply_visitor(weightSizeVisitor, rnnModule) + - boost::apply_visitor(weightSizeVisitor, actionModule); - - intermediateGradient = arma::zeros(weights, 1); - attentionGradient = arma::zeros(weights, 1); - - // Initialize the action error. - actionError = arma::zeros( - boost::apply_visitor(outputParameterVisitor, actionModule).n_rows, - boost::apply_visitor(outputParameterVisitor, actionModule).n_cols); - } - - // Propagate the attention gradients. - if (backwardStep == 0) - { - size_t offset = 0; - offset += boost::apply_visitor(GradientSetVisitor( - std::move(intermediateGradient), offset), rnnModule); - boost::apply_visitor(GradientSetVisitor( - std::move(intermediateGradient), offset), actionModule); - - attentionGradient.zeros(); - } - - // Back-propagate through time. - for (; backwardStep < rho; backwardStep++) - { - if (backwardStep == 0) - { - recurrentError = gy; - } - else - { - recurrentError = actionDelta; - } - - for (size_t l = 0; l < network.size(); ++l) - { - boost::apply_visitor(LoadOutputParameterVisitor( - std::move(moduleOutputParameter)), network[network.size() - 1 - l]); - } - - if (backwardStep == (rho - 1)) - { - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, actionModule)), std::move(actionError), - std::move(actionDelta)), actionModule); - } - else - { - boost::apply_visitor(BackwardVisitor(std::move(initialInput), - std::move(actionError), std::move(actionDelta)), actionModule); - } - - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, rnnModule)), std::move(recurrentError), - std::move(rnnDelta)), rnnModule); - - if (backwardStep == 0) - { - g = rnnDelta.col(1); - } - else - { - g += rnnDelta.col(1); - } - - IntermediateGradient(); - } -} - -template -template -void RecurrentAttention::Gradient( - arma::Mat&& /* input */, - arma::Mat&& /* error */, - arma::Mat&& /* gradient */) -{ - size_t offset = 0; - offset += boost::apply_visitor(GradientUpdateVisitor( - std::move(attentionGradient), offset), rnnModule); - boost::apply_visitor(GradientUpdateVisitor( - std::move(attentionGradient), offset), actionModule); -} - -template -template -void RecurrentAttention::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(rho); - ar & BOOST_SERIALIZATION_NVP(outSize); - ar & BOOST_SERIALIZATION_NVP(forwardStep); - ar & BOOST_SERIALIZATION_NVP(backwardStep); - - ar & BOOST_SERIALIZATION_NVP(rnnModule); - ar & BOOST_SERIALIZATION_NVP(actionModule); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_impl.hpp deleted file mode 100644 index 69e9a0eee..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/recurrent_impl.hpp +++ /dev/null @@ -1,298 +0,0 @@ -/** - * @file recurrent_impl.hpp - * @author Marcus Edel - * - * Implementation of the LinearLayer class also known as fully-connected layer - * or affine transformation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_RECURRENT_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_RECURRENT_IMPL_HPP - -// In case it hasn't yet been included. -#include "recurrent.hpp" - -#include "../visitor/add_visitor.hpp" -#include "../visitor/backward_visitor.hpp" -#include "../visitor/gradient_visitor.hpp" -#include "../visitor/gradient_zero_visitor.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Recurrent::Recurrent() : - rho(0), - forwardStep(0), - backwardStep(0), - gradientStep(0), - deterministic(false), - ownsLayer(false) -{ - // Nothing to do. -} - -template -Recurrent::~Recurrent() -{ - if (ownsLayer) - { - boost::apply_visitor(DeleteVisitor(), recurrentModule); - boost::apply_visitor(DeleteVisitor(), initialModule); - boost::apply_visitor(DeleteVisitor(), startModule); - network.clear(); - } -} - -template -template< - typename StartModuleType, - typename InputModuleType, - typename FeedbackModuleType, - typename TransferModuleType -> -Recurrent::Recurrent( - const StartModuleType& start, - const InputModuleType& input, - const FeedbackModuleType& feedback, - const TransferModuleType& transfer, - const size_t rho) : - startModule(new StartModuleType(start)), - inputModule(new InputModuleType(input)), - feedbackModule(new FeedbackModuleType(feedback)), - transferModule(new TransferModuleType(transfer)), - rho(rho), - forwardStep(0), - backwardStep(0), - gradientStep(0), - deterministic(false), - ownsLayer(true) -{ - initialModule = new Sequential<>(); - mergeModule = new AddMerge<>(false); - recurrentModule = new Sequential<>(false); - - boost::apply_visitor(AddVisitor(inputModule), - initialModule); - boost::apply_visitor(AddVisitor(startModule), - initialModule); - boost::apply_visitor(AddVisitor(transferModule), - initialModule); - - boost::apply_visitor(weightSizeVisitor, startModule); - boost::apply_visitor(weightSizeVisitor, inputModule); - boost::apply_visitor(weightSizeVisitor, feedbackModule); - boost::apply_visitor(weightSizeVisitor, transferModule); - - boost::apply_visitor(AddVisitor(inputModule), mergeModule); - boost::apply_visitor(AddVisitor(feedbackModule), - mergeModule); - boost::apply_visitor(AddVisitor(mergeModule), - recurrentModule); - boost::apply_visitor(AddVisitor(transferModule), - recurrentModule); - - network.push_back(initialModule); - network.push_back(mergeModule); - network.push_back(feedbackModule); - network.push_back(recurrentModule); -} - -template -template -void Recurrent::Forward( - arma::Mat&& input, arma::Mat&& output) -{ - if (forwardStep == 0) - { - boost::apply_visitor(ForwardVisitor(std::move(input), std::move(output)), - initialModule); - } - else - { - boost::apply_visitor(ForwardVisitor(std::move(input), std::move( - boost::apply_visitor(outputParameterVisitor, inputModule))), - inputModule); - - boost::apply_visitor(ForwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, transferModule)), std::move( - boost::apply_visitor(outputParameterVisitor, feedbackModule))), - feedbackModule); - - boost::apply_visitor(ForwardVisitor(std::move(input), std::move(output)), - recurrentModule); - } - - output = boost::apply_visitor(outputParameterVisitor, transferModule); - - // Save the feedback output parameter when training the module. - if (!deterministic) - { - feedbackOutputParameter.push_back(output); - } - - forwardStep++; - if (forwardStep == rho) - { - forwardStep = 0; - backwardStep = 0; - - if (!recurrentError.is_empty()) - { - recurrentError.zeros(); - } - } -} - -template -template -void Recurrent::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - if (!recurrentError.is_empty()) - { - recurrentError += gy; - } - else - { - recurrentError = gy; - } - - if (backwardStep < (rho - 1)) - { - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, recurrentModule)), std::move(recurrentError), - std::move(boost::apply_visitor(deltaVisitor, recurrentModule))), - recurrentModule); - - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, inputModule)), std::move( - boost::apply_visitor(deltaVisitor, recurrentModule)), std::move(g)), - inputModule); - - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, feedbackModule)), std::move( - boost::apply_visitor(deltaVisitor, recurrentModule)), std::move( - boost::apply_visitor(deltaVisitor, feedbackModule))), feedbackModule); - } - else - { - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, initialModule)), std::move(recurrentError), - std::move(g)), initialModule); - } - - recurrentError = boost::apply_visitor(deltaVisitor, feedbackModule); - backwardStep++; -} - -template -template -void Recurrent::Gradient( - arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& /* gradient */) -{ - if (gradientStep < (rho - 1)) - { - boost::apply_visitor(GradientVisitor(std::move(input), std::move(error)), - recurrentModule); - - boost::apply_visitor(GradientVisitor(std::move(input), std::move( - boost::apply_visitor(deltaVisitor, mergeModule))), inputModule); - - boost::apply_visitor(GradientVisitor(std::move( - feedbackOutputParameter[feedbackOutputParameter.size() - 2 - - gradientStep]), std::move(boost::apply_visitor(deltaVisitor, - mergeModule))), feedbackModule); - } - else - { - boost::apply_visitor(GradientZeroVisitor(), recurrentModule); - boost::apply_visitor(GradientZeroVisitor(), inputModule); - boost::apply_visitor(GradientZeroVisitor(), feedbackModule); - - boost::apply_visitor(GradientVisitor(std::move(input), std::move( - boost::apply_visitor(deltaVisitor, startModule))), initialModule); - } - - gradientStep++; - if (gradientStep == rho) - { - gradientStep = 0; - feedbackOutputParameter.clear(); - } -} - -template -template -void Recurrent::serialize( - Archive& ar, const unsigned int /* version */) -{ - // Clean up memory, if we are loading. - if (Archive::is_loading::value) - { - // Clear old things, if needed. - boost::apply_visitor(DeleteVisitor(), recurrentModule); - boost::apply_visitor(DeleteVisitor(), initialModule); - boost::apply_visitor(DeleteVisitor(), startModule); - network.clear(); - } - - ar & BOOST_SERIALIZATION_NVP(startModule); - ar & BOOST_SERIALIZATION_NVP(inputModule); - ar & BOOST_SERIALIZATION_NVP(feedbackModule); - ar & BOOST_SERIALIZATION_NVP(transferModule); - ar & BOOST_SERIALIZATION_NVP(rho); - ar & BOOST_SERIALIZATION_NVP(ownsLayer); - - // Set up the network. - if (Archive::is_loading::value) - { - initialModule = new Sequential<>(); - mergeModule = new AddMerge<>(false); - recurrentModule = new Sequential<>(false); - - boost::apply_visitor(AddVisitor(inputModule), - initialModule); - boost::apply_visitor(AddVisitor(startModule), - initialModule); - boost::apply_visitor(AddVisitor(transferModule), - initialModule); - - boost::apply_visitor(weightSizeVisitor, startModule); - boost::apply_visitor(weightSizeVisitor, inputModule); - boost::apply_visitor(weightSizeVisitor, feedbackModule); - boost::apply_visitor(weightSizeVisitor, transferModule); - - boost::apply_visitor(AddVisitor(inputModule), - mergeModule); - boost::apply_visitor(AddVisitor(feedbackModule), - mergeModule); - boost::apply_visitor(AddVisitor(mergeModule), - recurrentModule); - boost::apply_visitor(AddVisitor(transferModule), - recurrentModule); - - network.push_back(initialModule); - network.push_back(mergeModule); - network.push_back(feedbackModule); - network.push_back(recurrentModule); - } -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/reinforce_normal.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/reinforce_normal.hpp deleted file mode 100644 index 25e8c09b9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/reinforce_normal.hpp +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @file reinforce_normal.hpp - * @author Marcus Edel - * - * Definition of the ReinforceNormalLayer class, which implements the REINFORCE - * algorithm for the normal distribution. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_REINFORCE_NORMAL_HPP -#define MLPACK_METHODS_ANN_LAYER_REINFORCE_NORMAL_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the reinforce normal layer. The reinforce normal layer - * implements the REINFORCE algorithm for the normal distribution. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class ReinforceNormal -{ - public: - /** - * Create the ReinforceNormal object. - * - * @param stdev Standard deviation used during the forward and backward pass. - */ - ReinforceNormal(const double stdev = 1.0); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const DataType&& input, DataType&& /* gy */, DataType&& g); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - //! Get the value of the reward parameter. - double Reward() const { return reward; } - //! Modify the value of the deterministic parameter. - double& Reward() { return reward; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */); - - private: - //! Standard deviation used during the forward and backward pass. - double stdev; - - //! Locally-stored reward parameter. - double reward; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Locally-stored output module parameter parameters. - std::vector moduleInputParameter; - - //! If true use maximum a posteriori during the forward pass. - bool deterministic; -}; // class ReinforceNormal - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "reinforce_normal_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/reinforce_normal_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/reinforce_normal_impl.hpp deleted file mode 100644 index dbe95e00b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/reinforce_normal_impl.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file reinforce_normal_impl.hpp - * @author Marcus Edel - * - * Implementation of the ReinforceNormalLayer class, which implements the - * REINFORCE algorithm for the normal distribution. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_REINFORCE_NORMAL_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_REINFORCE_NORMAL_IMPL_HPP - -// In case it hasn't yet been included. -#include "reinforce_normal.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -ReinforceNormal::ReinforceNormal( - const double stdev) : stdev(stdev) -{ - // Nothing to do here. -} - -template -template -void ReinforceNormal::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - if (!deterministic) - { - // Multiply by standard deviations and re-center the means to the mean. - output = arma::randn >(input.n_rows, input.n_cols) * - stdev + input; - - moduleInputParameter.push_back(input); - } - else - { - // Use maximum a posteriori. - output = input; - } -} - -template -template -void ReinforceNormal::Backward( - const DataType&& input, DataType&& /* gy */, DataType&& g) -{ - g = (input - moduleInputParameter.back()) / std::pow(stdev, 2.0); - - // Multiply by reward and multiply by -1. - g *= reward; - g *= -1; - - moduleInputParameter.pop_back(); -} - -template -template -void ReinforceNormal::serialize( - Archive& /* ar */, const unsigned int /* version */) -{ - // Nothing to do here. -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/select.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/select.hpp deleted file mode 100644 index cd57d0c27..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/select.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file select.hpp - * @author Marcus Edel - * - * Definition of the Select module. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_SELECT_HPP -#define MLPACK_METHODS_ANN_LAYER_SELECT_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The select module selects the specified column from a given input matrix. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class Select -{ - public: - /** - * Create the Select object. - * - * @param index The column which should be extracted from the given input. - * @param elements The number of elements that should be used. - */ - Select(const size_t index = 0, const size_t elements = 0); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards trough f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored column index. - size_t index; - - //! Locally-stored number of elements selected. - size_t elements; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class Select - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "select_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/select_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/select_impl.hpp deleted file mode 100644 index f3a8b6797..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/select_impl.hpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file select_impl.hpp - * @author Marcus Edel - * - * Implementation of the Select module. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_SELECT_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_SELECT_IMPL_HPP - -// In case it hasn't yet been included. -#include "constant.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Select::Select( - const size_t index, - const size_t elements) : - index(index), - elements(elements) - { - // Nothing to do here. - } - -template -template -void Select::Forward( - const arma::Mat&& input, arma::Mat&& output) -{ - if (elements == 0) - { - output = input.col(index); - } - else - { - output = input.submat(0, index, elements - 1, index); - } -} - -template -template -void Select::Backward( - const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g) -{ - if (elements == 0) - { - g = gy; - } - else - { - g = gy.submat(0, 0, elements - 1, 0); - } -} - -template -template -void Select::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(index); - ar & BOOST_SERIALIZATION_NVP(elements); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/sequential.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/sequential.hpp deleted file mode 100644 index b04f8e25c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/sequential.hpp +++ /dev/null @@ -1,208 +0,0 @@ -/** - * @file sequential.hpp - * @author Marcus Edel - * - * Definition of the Sequential class, which acts as a feed-forward fully - * connected network container. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_SEQUENTIAL_HPP -#define MLPACK_METHODS_ANN_LAYER_SEQUENTIAL_HPP - -#include - -#include - -#include "../visitor/delete_visitor.hpp" -#include "../visitor/delta_visitor.hpp" -#include "../visitor/output_height_visitor.hpp" -#include "../visitor/output_parameter_visitor.hpp" -#include "../visitor/output_width_visitor.hpp" - -#include "layer_types.hpp" -#include "add_merge.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Sequential class. The sequential class works as a - * feed-forward fully connected network container which plugs various layers - * together. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat, - typename... CustomLayers -> -class Sequential -{ - public: - /** - * Create the Sequential object using the specified parameters. - * - * @param model Expose the all network modules. - */ - Sequential(const bool model = true); - - //! Destroy the Sequential object. - ~Sequential(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, using 3rd-order tensors as - * input, calculating the function f(x) by propagating x backwards through f. - * Using the results from the feed forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& /* gradient */); - - /* - * Add a new module to the model. - * - * @param args The layer parameter. - */ - template - void Add(Args... args) { network.push_back(new LayerType(args...)); } - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - void Add(LayerTypes layer) { network.push_back(layer); } - - //! Return the model modules. - std::vector >& Model() - { - if (model) - { - return network; - } - - return empty; - } - - //! Return the initial point for the optimization. - const arma::mat& Parameters() const { return parameters; } - //! Modify the initial point for the optimization. - arma::mat& Parameters() { return parameters; } - - arma::mat const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - arma::mat& InputParameter() { return inputParameter; } - - //! Get the output parameter. - arma::mat const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - arma::mat& OutputParameter() { return outputParameter; } - - //! Get the delta.e - arma::mat const& Delta() const { return delta; } - //! Modify the delta. - arma::mat& Delta() { return delta; } - - //! Get the gradient. - arma::mat const& Gradient() const { return gradient; } - //! Modify the gradient. - arma::mat& Gradient() { return gradient; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */); - - private: - //! Parameter which indicates if the modules should be exposed. - bool model; - - //! Indicator if we already initialized the model. - bool reset; - - //! Locally-stored network modules. - std::vector > network; - - //! Locally-stored model parameters. - arma::mat parameters; - - //! Locally-stored delta visitor. - DeltaVisitor deltaVisitor; - - //! Locally-stored output parameter visitor. - OutputParameterVisitor outputParameterVisitor; - - //! Locally-stored delete visitor. - DeleteVisitor deleteVisitor; - - //! Locally-stored empty list of modules. - std::vector > empty; - - //! Locally-stored delta object. - arma::mat delta; - - //! Locally-stored input parameter object. - arma::mat inputParameter; - - //! Locally-stored output parameter object. - arma::mat outputParameter; - - //! Locally-stored gradient object. - arma::mat gradient; - - //! Locally-stored output width visitor. - OutputWidthVisitor outputWidthVisitor; - - //! Locally-stored output height visitor. - OutputHeightVisitor outputHeightVisitor; - - //! The input width. - size_t width; - - //! The input height. - size_t height; -}; // class Sequential - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "sequential_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/sequential_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/sequential_impl.hpp deleted file mode 100644 index 31aba672a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/sequential_impl.hpp +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @file sequential_impl.hpp - * @author Marcus Edel - * - * Implementation of the Sequential class, which acts as a feed-forward fully - * connected network container. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_SEQUENTIAL_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_SEQUENTIAL_IMPL_HPP - -// In case it hasn't yet been included. -#include "sequential.hpp" - -#include "../visitor/forward_visitor.hpp" -#include "../visitor/backward_visitor.hpp" -#include "../visitor/gradient_visitor.hpp" -#include "../visitor/set_input_height_visitor.hpp" -#include "../visitor/set_input_width_visitor.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -Sequential::Sequential( - const bool model) : model(model), reset(false), width(0), height(0) -{ - // Nothing to do here. -} - -template -Sequential::~Sequential() -{ - if (!model) - { - for (LayerTypes& layer : network) - boost::apply_visitor(deleteVisitor, layer); - } -} - -template -template -void Sequential::Forward( - arma::Mat&& input, arma::Mat&& output) -{ - boost::apply_visitor(ForwardVisitor(std::move(input), std::move( - boost::apply_visitor(outputParameterVisitor, network.front()))), - network.front()); - - if (!reset) - { - if (boost::apply_visitor(outputWidthVisitor, network.front()) != 0) - { - width = boost::apply_visitor(outputWidthVisitor, network.front()); - } - - if (boost::apply_visitor(outputHeightVisitor, network.front()) != 0) - { - height = boost::apply_visitor(outputHeightVisitor, network.front()); - } - } - - for (size_t i = 1; i < network.size(); ++i) - { - if (!reset) - { - // Set the input width. - boost::apply_visitor(SetInputWidthVisitor(width, true), network[i]); - - // Set the input height. - boost::apply_visitor(SetInputHeightVisitor(height, true), network[i]); - } - - boost::apply_visitor(ForwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[i - 1])), std::move( - boost::apply_visitor(outputParameterVisitor, network[i]))), - network[i]); - - if (!reset) - { - // Get the output width. - if (boost::apply_visitor(outputWidthVisitor, network[i]) != 0) - { - width = boost::apply_visitor(outputWidthVisitor, network[i]); - } - - // Get the output height. - if (boost::apply_visitor(outputHeightVisitor, network[i]) != 0) - { - height = boost::apply_visitor(outputHeightVisitor, network[i]); - } - } - } - -if (!reset) -{ - reset = true; -} - - output = boost::apply_visitor(outputParameterVisitor, network.back()); -} - -template -template -void Sequential::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network.back())), std::move(gy), - std::move(boost::apply_visitor(deltaVisitor, network.back()))), - network.back()); - - for (size_t i = 2; i < network.size() + 1; ++i) - { - boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[network.size() - i])), std::move( - boost::apply_visitor(deltaVisitor, network[network.size() - i + 1])), - std::move(boost::apply_visitor(deltaVisitor, - network[network.size() - i]))), network[network.size() - i]); - } - - g = boost::apply_visitor(deltaVisitor, network.front()); -} - -template -template -void Sequential::Gradient( - arma::Mat&& input, - arma::Mat&& error, - arma::Mat&& /* gradient */) -{ - boost::apply_visitor(GradientVisitor(std::move(input), std::move(error)), - network.front()); - - for (size_t i = 1; i < network.size() - 1; ++i) - { - boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor( - outputParameterVisitor, network[i - 1])), std::move( - boost::apply_visitor(deltaVisitor, network[i + 1]))), network[i]); - } -} - -template -template -void Sequential::serialize( - Archive& ar, const unsigned int /* version */) -{ - // If loading, delete the old layers. - if (Archive::is_loading::value) - { - for (LayerTypes& layer : network) - boost::apply_visitor(deleteVisitor, layer); - } - - ar & BOOST_SERIALIZATION_NVP(model); - ar & BOOST_SERIALIZATION_NVP(network); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/transposed_convolution.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/transposed_convolution.hpp deleted file mode 100644 index fc4b20f07..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/transposed_convolution.hpp +++ /dev/null @@ -1,345 +0,0 @@ -/** - * @file transposed_convolution.hpp - * @author Shikhar Jaiswal - * @author Marcus Edel - * - * Definition of the Transposed Convolution module class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_TRANSPOSED_CONVOLUTION_HPP -#define MLPACK_METHODS_ANN_LAYER_TRANSPOSED_CONVOLUTION_HPP - -#include - -#include -#include -#include -#include - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the Transposed Convolution class. The Transposed - * Convolution class represents a single layer of a neural network. - * - * @tparam ForwardConvolutionRule Convolution to perform forward process. - * @tparam BackwardConvolutionRule Convolution to perform backward process. - * @tparam GradientConvolutionRule Convolution to calculate gradient. - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename ForwardConvolutionRule = NaiveConvolution, - typename BackwardConvolutionRule = NaiveConvolution, - typename GradientConvolutionRule = NaiveConvolution, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class TransposedConvolution -{ - public: - //! Create the Transposed Convolution object. - TransposedConvolution(); - - /** - * Create the Transposed Convolution object using the specified number of input maps, - * output maps, filter size, stride and padding parameter. - * - * @param inSize The number of input maps. - * @param outSize The number of output maps. - * @param kW Width of the filter/kernel. - * @param kH Height of the filter/kernel. - * @param dW Stride of filter application in the x direction. - * @param dH Stride of filter application in the y direction. - * @param padW Padding width of the input. - * @param padH Padding height of the input. - * @param inputWidth The width of the input data. - * @param inputHeight The height of the input data. - */ - TransposedConvolution(const size_t inSize, - const size_t outSize, - const size_t kW, - const size_t kH, - const size_t dW = 1, - const size_t dH = 1, - const size_t padW = 0, - const size_t padH = 0, - const size_t inputWidth = 0, - const size_t inputHeight = 0); - - /* - * Set the weight and bias term. - */ - void Reset(); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - void Forward(const arma::Mat&& input, arma::Mat&& output); - - /** - * Ordinary feed backward pass of a neural network, calculating the function - * f(x) by propagating x backwards through f. Using the results from the feed - * forward pass. - * - * @param input The propagated input activation. - * @param gy The backpropagated error. - * @param g The calculated gradient. - */ - template - void Backward(const arma::Mat&& /* input */, - arma::Mat&& gy, - arma::Mat&& g); - - /* - * Calculate the gradient using the output delta and the input activation. - * - * @param input The input parameter used for calculating the gradient. - * @param error The calculated error. - * @param gradient The calculated gradient. - */ - template - void Gradient(const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient); - - //! Get the parameters. - OutputDataType const& Parameters() const { return weights; } - //! Modify the parameters. - OutputDataType& Parameters() { return weights; } - - //! Get the input parameter. - InputDataType const& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType const& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType const& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the gradient. - OutputDataType const& Gradient() const { return gradient; } - //! Modify the gradient. - OutputDataType& Gradient() { return gradient; } - - //! Get the input width. - size_t const& InputWidth() const { return inputWidth; } - //! Modify input the width. - size_t& InputWidth() { return inputWidth; } - - //! Get the input height. - size_t const& InputHeight() const { return inputHeight; } - //! Modify the input height. - size_t& InputHeight() { return inputHeight; } - - //! Get the output width. - size_t const& OutputWidth() const { return outputWidth; } - //! Modify the output width. - size_t& OutputWidth() { return outputWidth; } - - //! Get the output height. - size_t const& OutputHeight() const { return outputHeight; } - //! Modify the output height. - size_t& OutputHeight() { return outputHeight; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /* - * Return the transposed convolution output size. - * - * @param size The size of the input (row or column). - * @param k The size of the filter (width or height). - * @param s The stride size (x or y direction). - * @param p The size of the padding (width or height). - * @return The transposed convolution output size. - */ - size_t TransposedConvOutSize(const size_t size, - const size_t k, - const size_t s, - const size_t p) - { - size_t out = std::floor(size - k + 2 * p) / s; - return out * s + 2 * (k - p) - 1 + ((((size + 2 * p - k) % s) + s) % s); - } - - /* - * Rotates a 3rd-order tensor counterclockwise by 180 degrees. - * - * @param input The input data to be rotated. - * @param output The rotated output. - */ - template - void Rotate180(const arma::Cube& input, arma::Cube& output) - { - output = arma::Cube(input.n_rows, input.n_cols, input.n_slices); - - // * left-right flip, up-down flip */ - for (size_t s = 0; s < output.n_slices; s++) - output.slice(s) = arma::fliplr(arma::flipud(input.slice(s))); - } - - /* - * Rotates a dense matrix counterclockwise by 180 degrees. - * - * @param input The input data to be rotated. - * @param output The rotated output. - */ - template - void Rotate180(const arma::Mat& input, arma::Mat& output) - { - // * left-right flip, up-down flip */ - output = arma::fliplr(arma::flipud(input)); - } - - /* - * Pad the given input data. - * - * @param input The input to be padded. - * @param wPad Padding width of the input. - * @param hPad Padding height of the input. - * @param output The padded output data. - */ - template - void Pad(const arma::Mat& input, - size_t wPad, - size_t hPad, - arma::Mat& output) - { - if (output.n_rows != input.n_rows + wPad * 2 || - output.n_cols != input.n_cols + hPad * 2) - { - output = arma::zeros(input.n_rows + wPad * 2, input.n_cols + hPad * 2); - } - - output.submat(wPad, hPad, wPad + input.n_rows - 1, - hPad + input.n_cols - 1) = input; - } - - /* - * Pad the given input data. - * - * @param input The input to be padded. - * @param wPad Padding width of the input. - * @param hPad Padding height of the input. - * @param output The padded output data. - */ - template - void Pad(const arma::Cube& input, - size_t wPad, - size_t hPad, - arma::Cube& output) - { - output = arma::zeros(input.n_rows + wPad * 2, - input.n_cols + hPad * 2, input.n_slices); - - for (size_t i = 0; i < input.n_slices; ++i) - { - Pad(input.slice(i), wPad, hPad, output.slice(i)); - } - } - - //! Locally-stored number of input units. - size_t inSize; - - //! Locally-stored number of output units. - size_t outSize; - - //! Locally-stored filter/kernel width. - size_t kW; - - //! Locally-stored filter/kernel height. - size_t kH; - - //! Locally-stored stride of the filter in x-direction. - size_t dW; - - //! Locally-stored stride of the filter in y-direction. - size_t dH; - - //! Locally-stored padding width. - size_t padW; - - //! Locally-stored padding height. - size_t padH; - - //! Locally-stored weight object. - OutputDataType weights; - - //! Locally-stored weight object. - arma::cube weight; - - //! Locally-stored bias term object. - arma::mat bias; - - //! Locally-stored input width. - size_t inputWidth; - - //! Locally-stored input height. - size_t inputHeight; - - //! Locally-stored output width. - size_t outputWidth; - - //! Locally-stored output height. - size_t outputHeight; - - //! Locally-stored transformed output parameter. - arma::cube outputTemp; - - //! Locally-stored transformed input parameter. - arma::cube inputTemp; - - //! Locally-stored transformed padded input parameter. - arma::cube inputPaddedTemp; - - //! Locally-stored transformed error parameter. - arma::cube gTemp; - - //! Locally-stored transformed gradient parameter. - arma::cube gradientTemp; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored gradient object. - OutputDataType gradient; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class TransposedConvolution - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "transposed_convolution_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/transposed_convolution_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/transposed_convolution_impl.hpp deleted file mode 100644 index b667cfbc5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/transposed_convolution_impl.hpp +++ /dev/null @@ -1,268 +0,0 @@ -/** - * @file transposed_convolution_impl.hpp - * @author Shikhar Jaiswal - * @author Marcus Edel - * - * Implementation of the Transposed Convolution module class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_TRANSPOSED_CONVOLUTION_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_TRANSPOSED_CONVOLUTION_IMPL_HPP - -// In case it hasn't yet been included. -#include "transposed_convolution.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -TransposedConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::TransposedConvolution() -{ - // Nothing to do here. -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -TransposedConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::TransposedConvolution( - const size_t inSize, - const size_t outSize, - const size_t kW, - const size_t kH, - const size_t dW, - const size_t dH, - const size_t padW, - const size_t padH, - const size_t inputWidth, - const size_t inputHeight) : - inSize(inSize), - outSize(outSize), - kW(kW), - kH(kH), - dW(dW), - dH(dH), - padW(padW), - padH(padH), - inputWidth(inputWidth), - inputHeight(inputHeight), - outputWidth(0), - outputHeight(0) -{ - weights.set_size((outSize * inSize * kW * kH) + outSize, 1); -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -void TransposedConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Reset() -{ - weight = arma::cube(weights.memptr(), kW, kH, - outSize * inSize, false, false); - bias = arma::mat(weights.memptr() + weight.n_elem, - outSize, 1, false, false); -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void TransposedConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Forward(const arma::Mat&& input, arma::Mat&& output) -{ - inputTemp = arma::cube(input.memptr(), inputWidth, inputHeight, inSize); - - outputWidth = TransposedConvOutSize(inputWidth, kW, dW, padW); - outputHeight = TransposedConvOutSize(inputHeight, kH, dH, padH); - - output.set_size(outputWidth * outputHeight * outSize, 1); - outputTemp = arma::Cube(output.memptr(), outputWidth, outputHeight, - outSize, false, false); - outputTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0; inMap < inSize; inMap++, outMapIdx++) - { - arma::Mat convOutput, rotatedFilter; - Rotate180(weight.slice(outMapIdx), rotatedFilter); - - BackwardConvolutionRule::Convolution(inputTemp.slice(inMap), - rotatedFilter, convOutput, 1, 1); - - outputTemp.slice(outMap) += convOutput; - } - - outputTemp.slice(outMap) += bias(outMap); - } -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void TransposedConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Backward( - const arma::Mat&& /* input */, arma::Mat&& gy, arma::Mat&& g) -{ - arma::cube mappedError(gy.memptr(), outputWidth, outputHeight, outSize, - false, false); - - g.set_size(inputTemp.n_rows * inputTemp.n_cols * inputTemp.n_slices, 1); - gTemp = arma::Cube(g.memptr(), inputTemp.n_rows, - inputTemp.n_cols, inputTemp.n_slices, false, false); - gTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0; inMap < inSize; inMap++, outMapIdx++) - { - arma::Mat output; - - ForwardConvolutionRule::Convolution(mappedError.slice(outMap), - weight.slice(outMapIdx), output, 1, 1); - - gTemp.slice(inMap) += output; - } - } -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void TransposedConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::Gradient( - const arma::Mat&& /* input */, - arma::Mat&& error, - arma::Mat&& gradient) -{ - arma::cube mappedError(error.memptr(), outputWidth, - outputHeight, outSize, false, false); - - gradient.set_size(weights.n_elem, 1); - gradientTemp = arma::Cube(gradient.memptr(), weight.n_rows, weight.n_cols, - weight.n_slices, false, false); - gradientTemp.zeros(); - - for (size_t outMap = 0, outMapIdx = 0; outMap < outSize; outMap++) - { - for (size_t inMap = 0, s = outMap; inMap < inSize; inMap++, outMapIdx++, - s += outSize) - { - arma::Cube inputSlices, output; - inputSlices = inputTemp.slices(inMap, inMap); - arma::Cube deltaSlices = mappedError.slices(outMap, outMap); - - GradientConvolutionRule::Convolution(deltaSlices, inputSlices, - output, 1, 1); - - for (size_t i = 0; i < output.n_slices; i++) - gradientTemp.slice(s) += output.slice(i); - } - - gradient.submat(weight.n_elem + outMap, 0, weight.n_elem + outMap, 0) = - arma::accu(mappedError.slices(outMap, outMap)); - } -} - -template< - typename ForwardConvolutionRule, - typename BackwardConvolutionRule, - typename GradientConvolutionRule, - typename InputDataType, - typename OutputDataType -> -template -void TransposedConvolution< - ForwardConvolutionRule, - BackwardConvolutionRule, - GradientConvolutionRule, - InputDataType, - OutputDataType ->::serialize( - Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(inSize); - ar & BOOST_SERIALIZATION_NVP(outSize); - ar & BOOST_SERIALIZATION_NVP(kW); - ar & BOOST_SERIALIZATION_NVP(kH); - ar & BOOST_SERIALIZATION_NVP(dW); - ar & BOOST_SERIALIZATION_NVP(dH); - ar & BOOST_SERIALIZATION_NVP(padW); - ar & BOOST_SERIALIZATION_NVP(padH); - ar & BOOST_SERIALIZATION_NVP(inputWidth); - ar & BOOST_SERIALIZATION_NVP(inputHeight); - ar & BOOST_SERIALIZATION_NVP(outputWidth); - ar & BOOST_SERIALIZATION_NVP(outputHeight); - - if (Archive::is_loading::value) - weights.set_size((outSize * inSize * kW * kH) + outSize, 1); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/vr_class_reward.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/vr_class_reward.hpp deleted file mode 100644 index b75e73f43..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/vr_class_reward.hpp +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @file vr_class_reward.hpp - * @author Marcus Edel - * - * Definition of the VRClassReward class, which implements the variance - * reduced classification reinforcement layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_VR_CLASS_REWARD_HPP -#define MLPACK_METHODS_ANN_LAYER_VR_CLASS_REWARD_HPP - -#include - -#include "layer_types.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of the variance reduced classification reinforcement layer. - * This layer is meant to be used in combination with the reinforce normal layer - * (ReinforceNormalLayer), which expects that an reward: - * (1 for success, 0 otherwise). - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class VRClassReward -{ - public: - /** - * Create the VRClassReward object. - * - * @param scale Parameter used to scale the reward. - * @param sizeAverage Take the average over all batches. - */ - VRClassReward(const double scale = 1, const bool sizeAverage = true); - - /** - * Ordinary feed forward pass of a neural network, evaluating the function - * f(x) by propagating the activity forward through f. - * - * @param input Input data that contains the log-probabilities for each class. - * @param target The target vector, that contains the class index in the range - * between 1 and the number of classes. - */ - template - double Forward(const InputType&& input, const TargetType&& target); - - /** - * Ordinary feed backward pass of a neural network. The negative log - * likelihood layer expectes that the input contains log-probabilities for - * each class. The layer also expects a class index, in the range between 1 - * and the number of classes, as target when calling the Forward function. - * - * @param input The propagated input activation. - * @param target The target vector, that contains the class index in the range - * between 1 and the number of classes. - * @param output The calculated error. - */ - template - void Backward(const InputType&& input, - const TargetType&& target, - OutputType&& output); - - //! Get the input parameter. - InputDataType& InputParameter() const {return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const {return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const {return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the value of the deterministic parameter. - bool Deterministic() const { return deterministic; } - //! Modify the value of the deterministic parameter. - bool& Deterministic() { return deterministic; } - - /* - * Add a new module to the model. - * - * @param args The layer parameter. - */ - template - void Add(Args... args) { network.push_back(new LayerType(args...)); } - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - void Add(LayerTypes<> layer) { network.push_back(layer); } - - /** - * Serialize the layer - */ - template - void serialize(Archive& /* ar */, const unsigned int /* version */); - - private: - //! Locally-stored value to scale the reward. - double scale; - - //! If true take the average over all batches. - bool sizeAverage; - - //! Locally stored reward parameter. - double reward; - - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! If true dropout and scaling is disabled, see notes above. - bool deterministic; - - //! Locally-stored network modules. - std::vector > network; -}; // class VRClassReward - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "vr_class_reward_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/layer/vr_class_reward_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/layer/vr_class_reward_impl.hpp deleted file mode 100644 index 679c31467..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/layer/vr_class_reward_impl.hpp +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file vr_class_reward_impl.hpp - * @author Marcus Edel - * - * Implementation of the VRClassReward class, which implements the variance - * reduced classification reinforcement layer. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LAYER_VR_CLASS_REWARD_IMPL_HPP -#define MLPACK_METHODS_ANN_LAYER_VR_CLASS_REWARD_IMPL_HPP - -// In case it hasn't yet been included. -#include "vr_class_reward.hpp" - -#include "../visitor/reward_set_visitor.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -VRClassReward::VRClassReward( - const double scale, - const bool sizeAverage) : - scale(scale), - sizeAverage(sizeAverage) -{ - // Nothing to do here. -} - -template -template -double VRClassReward::Forward( - const InputType&& input, const TargetType&& target) -{ - double output = 0; - for (size_t i = 0; i < input.n_cols - 1; ++i) - { - size_t currentTarget = target(i) - 1; - Log::Assert(currentTarget >= 0 && currentTarget < input.n_rows, - "Target class out of range."); - - output -= input(currentTarget, i); - } - - reward = 0; - arma::uword index = 0; - - for (size_t i = 0; i < input.n_cols - 1; i++) - { - input.unsafe_col(i).max(index); - reward = ((index + 1) == target(i)) * scale; - } - - if (sizeAverage) - { - return output - reward / (input.n_cols - 1); - } - - return output - reward; -} - -template -template -void VRClassReward::Backward( - const InputType&& input, - const TargetType&& target, - OutputType&& output) -{ - output = arma::zeros(input.n_rows, input.n_cols); - for (size_t i = 0; i < (input.n_cols - 1); ++i) - { - size_t currentTarget = target(i) - 1; - Log::Assert(currentTarget >= 0 && currentTarget < input.n_rows, - "Target class out of range."); - - output(currentTarget, i) = -1; - } - - double vrReward = reward - input(0, 1); - if (sizeAverage) - { - vrReward /= input.n_cols - 1; - } - - const double norm = sizeAverage ? 2.0 / (input.n_cols - 1) : 2.0; - - output(0, 1) = norm * (input(0, 1) - reward); - boost::apply_visitor(RewardSetVisitor(vrReward), network.back()); -} - -template -template -void VRClassReward::serialize( - Archive& /* ar */, - const unsigned int /* version */) -{ - // Nothing to do here. -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/cross_entropy_error.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/cross_entropy_error.hpp deleted file mode 100644 index dad8eb8c8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/cross_entropy_error.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file cross_entropy_error.hpp - * @author Konstantin Sidorov - * - * Definition of the cross-entropy performance function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTIONS_CROSS_ENTROPY_ERROR_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTIONS_CROSS_ENTROPY_ERROR_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The cross-entropy performance function measures the network's - * performance according to the cross-entropy - * between the input and target distributions. - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class CrossEntropyError -{ - public: - /** - * Create the CrossEntropyError object. - * - * @param eps The minimum value used for computing logarithms - * and denominators in a numerically stable way. - */ - CrossEntropyError(const double eps = 1e-10); - - /* - * Computes the cross-entropy function. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - double Forward(const InputType&& input, const TargetType&& target); - /** - * Ordinary feed backward pass of a neural network. - * - * @param input The propagated input activation. - * @param target The target vector. - * @param output The calculated error. - */ - template - void Backward(const InputType&& input, - const TargetType&& target, - OutputType&& output); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the epsilon. - double Eps() const { return eps; } - //! Modify the epsilon. - double& Eps() { return eps; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! The minimum value used for computing logarithms and denominators - double eps; -}; // class CrossEntropyError - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "cross_entropy_error_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/cross_entropy_error_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/cross_entropy_error_impl.hpp deleted file mode 100644 index 1edc6df5e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/cross_entropy_error_impl.hpp +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @file cross_entropy_error_impl.hpp - * @author Konstantin Sidorov - * - * Implementation of the cross-entropy performance function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTIONS_CROSS_ENTROPY_ERROR_IMPL_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTIONS_CROSS_ENTROPY_ERROR_IMPL_HPP - -// In case it hasn't yet been included. -#include "cross_entropy_error.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -CrossEntropyError::CrossEntropyError( - const double eps) : eps(eps) -{ - // Nothing to do here. -} - -template -template -double CrossEntropyError::Forward( - const InputType&& input, const TargetType&& target) -{ - return -arma::accu(target % arma::log(input + eps) + - (1. - target) % arma::log(1. - input + eps)); -} - -template -template -void CrossEntropyError::Backward( - const InputType&& input, - const TargetType&& target, - OutputType&& output) -{ - output = (1. - target) / (1. - input + eps) - target / (input + eps); -} - -template -template -void CrossEntropyError::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(eps); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/earth_mover_distance_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/earth_mover_distance_impl.hpp deleted file mode 100644 index b7db1786a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/earth_mover_distance_impl.hpp +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @file earth_mover_distance_impl.hpp - * @author Shikhar Jaiswal - * - * Implementation of the earth mover distance function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTIONS_EARTH_MOVER_DISTANCE_IMPL_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTIONS_EARTH_MOVER_DISTANCE_IMPL_HPP - -// In case it hasn't yet been included. -#include "earth_mover_distance.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -EarthMoverDistance::EarthMoverDistance() -{ - // Nothing to do here. -} - -template -template -double EarthMoverDistance::Forward( - const InputType&& input, const TargetType&& target) -{ - return -arma::accu(target % input); -} - -template -template -void EarthMoverDistance::Backward( - const InputType&& /* input */, - const TargetType&& target, - OutputType&& output) -{ - output = -target; -} - -template -template -void EarthMoverDistance::serialize( - Archive& /* ar */, - const unsigned int /* version */) -{ - /* Nothing to do here */ -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/kl_divergence.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/kl_divergence.hpp deleted file mode 100644 index 3bfe0b7bf..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/kl_divergence.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @file kl_divergence.hpp - * @author Dakshit Agrawal - * - * Definition of the Kullback–Leibler Divergence error function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_KL_DIVERGENCE_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTION_KL_DIVERGENCE_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The Kullback–Leibler divergence is often used for continuous - * distributions (direct regression). - * - * For more information, see the following paper. - * - * @code - * article{Kullback1951, - * title = {On Information and Sufficiency}, - * author = {S. Kullback, R.A. Leibler}, - * journal = {The Annals of Mathematical Statistics}, - * year = {1951} - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class KLDivergence -{ - public: - /** - * Create the Kullback–Leibler Divergence object with the specified - * parameters. - * - * @param takeMean Boolean variable to specify whether to take mean or not. - */ - KLDivergence(const bool takeMean = false); - - /** - * Computes the Kullback–Leibler divergence error function. - * - * @param input Input data used for evaluating the specified function. - * @param target Target data to compare with. - */ - template - double Forward(const InputType&& input, const TargetType&& target); - - /** - * Ordinary feed backward pass of a neural network. - * - * @param input The propagated input activation. - * @param target The target vector. - * @param output The calculated error. - */ - template - void Backward(const InputType&& input, - const TargetType&& target, - OutputType&& output); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - //! Get the value of takeMean. - bool TakeMean() const { return takeMean; } - //! Modify the value of takeMean. - bool& TakeMean() { return takeMean; } - - /** - * Serialize the loss function - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; - - //! Boolean variable for taking mean or not. - bool takeMean; -}; // class KLDivergence - -} // namespace ann -} // namespace mlpack - -// include implementation -#include "kl_divergence_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/kl_divergence_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/kl_divergence_impl.hpp deleted file mode 100644 index 590878ed3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/kl_divergence_impl.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file kl_divergence_impl.hpp - * @author Dakshit Agrawal - * - * Implementation of the Kullback–Leibler Divergence error function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_KL_DIVERGENCE_IMPL_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTION_KL_DIVERGENCE_IMPL_HPP - -// In case it hasn't yet been included. -#include "kl_divergence.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -KLDivergence::KLDivergence(const bool takeMean) : - takeMean(takeMean) -{ - // Nothing to do here. -} - -template -template -double KLDivergence::Forward( - const InputType&& input, const TargetType&& target) -{ - if (takeMean) - { - return arma::as_scalar(arma::mean( - arma::mean(input % (arma::log(input) - arma::log(target))))); - } - else - { - return arma::accu(input % (arma::log(input) - arma::log(target))); - } -} - -template -template -void KLDivergence::Backward( - const InputType&& input, - const TargetType&& target, - OutputType&& output) -{ - if (takeMean) - { - output = arma::mean(arma::mean(arma::log(input) - arma::log(target) + 1)); - } - else - { - output = arma::accu(arma::log(input) - arma::log(target) + 1); - } -} - -template -template -void KLDivergence::serialize( - Archive& /* ar */, - const unsigned int /* version */) -{ - // Nothing to do here. -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/mean_squared_error.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/mean_squared_error.hpp deleted file mode 100644 index 46e829a8a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/mean_squared_error.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @file mean_squared_error.hpp - * @author Marcus Edel - * - * Definition of the mean squared error performance function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_MEAN_SQUARED_ERROR_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTION_MEAN_SQUARED_ERROR_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The mean squared error performance function measures the network's - * performance according to the mean of squared errors. - * - * @tparam ActivationFunction Activation function used for the embedding layer. - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class MeanSquaredError -{ - public: - /** - * Create the MeanSquaredError object. - */ - MeanSquaredError(); - - /* - * Computes the mean squared error function. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - double Forward(const InputType&& input, const TargetType&& target); - /** - * Ordinary feed backward pass of a neural network. - * - * @param input The propagated input activation. - * @param target The target vector. - * @param output The calculated error. - */ - template - void Backward(const InputType&& input, - const TargetType&& target, - OutputType&& output); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class MeanSquaredError - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "mean_squared_error_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/mean_squared_error_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/mean_squared_error_impl.hpp deleted file mode 100644 index 9461fa9ab..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/mean_squared_error_impl.hpp +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @file mean_squared_error_impl.hpp - * @author Marcus Edel - * - * Implementation of the mean squared error performance function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_MEAN_SQUARED_ERROR_IMPL_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTION_MEAN_SQUARED_ERROR_IMPL_HPP - -// In case it hasn't yet been included. -#include "mean_squared_error.hpp" - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -MeanSquaredError::MeanSquaredError() -{ - // Nothing to do here. -} - -template -template -double MeanSquaredError::Forward( - const InputType&& input, const TargetType&& target) -{ - return arma::mean(arma::mean(arma::square(input - target))); -} - -template -template -void MeanSquaredError::Backward( - const InputType&& input, - const TargetType&& target, - OutputType&& output) -{ - output = (input - target); -} - -template -template -void MeanSquaredError::serialize( - Archive& /* ar */, - const unsigned int /* version */) -{ - // Nothing to do here. -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error.hpp deleted file mode 100644 index 71440d832..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error.hpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @file sigmoid_cross_entropy_error.hpp - * @author Kris Singh - * @author Shikhar Jaiswal - * - * Definition of the cross-entropy with logit performance function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_SIGMOID_CROSS_ENTROPY_ERROR_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTION_SIGMOID_CROSS_ENTROPY_ERROR_HPP - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * The SigmoidCrossEntropyError performance function measures the network's - * performance according to the cross-entropy function between the input and - * target distributions. This function calculates the cross entropy - * given the real values instead of providing the sigmoid activations. - * The function uses this equivalent formulation: - * \f$max(x, 0) - x * z + \log(1 + e^{-|x|})\f$ - * where x = input and z = target. - * - * For more information, see the following paper. - * - * @code - * @article{Janocha2017 - * title = {On Loss Functions for Deep Neural Networks in Classification}, - * author = {Katarzyna Janocha, Wojciech Marian Czarnecki}, - * url = {http://arxiv.org/abs/1702.05659}, - * journal = {CoRR}, - * eprint = {arXiv:1702.05659}, - * year = {2017} - * } - * @endcode - * - * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, - * arma::sp_mat or arma::cube). - */ -template < - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat -> -class SigmoidCrossEntropyError -{ - public: - /** - * Create the SigmoidCrossEntropyError object. - */ - SigmoidCrossEntropyError(); - - /* - * Computes the Sigmoid CrossEntropy Error functions. - * - * @param input Input data used for evaluating the specified function. - * @param output Resulting output activation. - */ - template - inline double Forward(const arma::Mat&& input, - const arma::Mat&& target); - /** - * Ordinary feed backward pass of a neural network. - * - * @param input The propagated input activation. - * @param target The target vector. - * @param output The calculated error. - */ - template - inline void Backward(const arma::Mat&& input, - const arma::Mat&& target, - arma::Mat&& output); - - //! Get the input parameter. - InputDataType& InputParameter() const { return inputParameter; } - //! Modify the input parameter. - InputDataType& InputParameter() { return inputParameter; } - - //! Get the output parameter. - OutputDataType& OutputParameter() const { return outputParameter; } - //! Modify the output parameter. - OutputDataType& OutputParameter() { return outputParameter; } - - //! Get the delta. - OutputDataType& Delta() const { return delta; } - //! Modify the delta. - OutputDataType& Delta() { return delta; } - - /** - * Serialize the layer. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Locally-stored delta object. - OutputDataType delta; - - //! Locally-stored input parameter object. - InputDataType inputParameter; - - //! Locally-stored output parameter object. - OutputDataType outputParameter; -}; // class SigmoidCrossEntropy - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "sigmoid_cross_entropy_error_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error_impl.hpp deleted file mode 100644 index 00cb4d0c8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error_impl.hpp +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @file sigmoid_cross_entropy_error_impl.hpp - * @author Kris Singh - * @author Shikhar Jaiswal - * - * Implementation of the sigmoid cross entropy error performance function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_LOSS_FUNCTION_SIGMOID_CROSS_ENTROPY_ERROR_IMPL_HPP -#define MLPACK_METHODS_ANN_LOSS_FUNCTION_SIGMOID_CROSS_ENTROPY_ERROR_IMPL_HPP - -// In case it hasn't yet been included. -#include "sigmoid_cross_entropy_error.hpp" -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -SigmoidCrossEntropyError -::SigmoidCrossEntropyError() -{ - // Nothing to do here. -} - -template -template -inline double SigmoidCrossEntropyError::Forward( - const arma::Mat&& input, const arma::Mat&& target) -{ - double maximum = 0; - for (size_t i = 0; i < input.n_elem; ++i) - { - maximum += std::max(input[i], 0.0) + - std::log(1 + std::exp(-std::abs(input[i]))); - } - - return maximum - arma::accu(input % target); -} - -template -template -inline void SigmoidCrossEntropyError::Backward( - const arma::Mat&& input, - const arma::Mat&& target, - arma::Mat&& output) -{ - output = 1.0 / (1.0 + arma::exp(-input)) - target; -} - -template -template -void SigmoidCrossEntropyError::serialize( - Archive& /* ar */, - const unsigned int /* version */) -{ - // Nothing to do here -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/rnn.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/rnn.hpp deleted file mode 100644 index 371f149d8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/rnn.hpp +++ /dev/null @@ -1,394 +0,0 @@ -/** - * @file rnn.hpp - * @author Marcus Edel - * - * Definition of the RNN class, which implements recurrent neural networks. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_RNN_HPP -#define MLPACK_METHODS_ANN_RNN_HPP - -#include - -#include "visitor/delete_visitor.hpp" -#include "visitor/delta_visitor.hpp" -#include "visitor/output_parameter_visitor.hpp" -#include "visitor/reset_visitor.hpp" - -#include "init_rules/network_init.hpp" - -#include -#include -#include -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -/** - * Implementation of a standard recurrent neural network container. - * - * @tparam OutputLayerType The output layer type used to evaluate the network. - * @tparam InitializationRuleType Rule used to initialize the weight matrix. - */ -template< - typename OutputLayerType = NegativeLogLikelihood<>, - typename InitializationRuleType = RandomInitialization, - typename... CustomLayers -> -class RNN -{ - public: - //! Convenience typedef for the internal model construction. - using NetworkType = RNN; - - /** - * Create the RNN object. - * - * Optionally, specify which initialize rule and performance function should - * be used. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * @param rho Maximum number of steps to backpropagate through time (BPTT). - * @param single Predict only the last element of the input sequence. - * @param outputLayer Output layer used to evaluate the network. - * @param initializeRule Optional instantiated InitializationRule object - * for initializing the network parameter. - */ - RNN(const size_t rho, - const bool single = false, - OutputLayerType outputLayer = OutputLayerType(), - InitializationRuleType initializeRule = InitializationRuleType()); - - //! Destructor to release allocated memory. - ~RNN(); - - /** - * Train the recurrent neural network on the given input data using the given - * optimizer. - * - * This will use the existing model parameters as a starting point for the - * optimization. If this is not what you want, then you should access the - * parameters vector directly with Parameters() and modify it as desired. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * The format of the data should be as follows: - * - each slice should correspond to a time step - * - each column should correspond to a data point - * - each row should correspond to a dimension - * So, e.g., predictors(i, j, k) is the i'th dimension of the j'th data point - * at time slice k. - * - * @tparam OptimizerType Type of optimizer to use to train the model. - * @param predictors Input training variables. - * @param responses Outputs results from input training variables. - * @param optimizer Instantiated optimizer used to train the model. - */ - template - void Train(arma::cube predictors, - arma::cube responses, - OptimizerType& optimizer); - - /** - * Train the recurrent neural network on the given input data. By default, the - * SGD optimization algorithm is used, but others can be specified - * (such as mlpack::optimization::RMSprop). - * - * This will use the existing model parameters as a starting point for the - * optimization. If this is not what you want, then you should access the - * parameters vector directly with Parameters() and modify it as desired. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * The format of the data should be as follows: - * - each slice should correspond to a time step - * - each column should correspond to a data point - * - each row should correspond to a dimension - * So, e.g., predictors(i, j, k) is the i'th dimension of the j'th data point - * at time slice k. - * - * @tparam OptimizerType Type of optimizer to use to train the model. - * @param predictors Input training variables. - * @param responses Outputs results from input training variables. - */ - template - void Train(arma::cube predictors, arma::cube responses); - - /** - * Predict the responses to a given set of predictors. The responses will - * reflect the output of the given output layer as returned by the - * output layer function. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * The format of the data should be as follows: - * - each slice should correspond to a time step - * - each column should correspond to a data point - * - each row should correspond to a dimension - * So, e.g., predictors(i, j, k) is the i'th dimension of the j'th data point - * at time slice k. The responses will be in the same format. - * - * @param predictors Input predictors. - * @param results Matrix to put output predictions of responses into. - * @param batchSize Number of points to predict at once. - */ - void Predict(arma::cube predictors, - arma::cube& results, - const size_t batchSize = 256); - - /** - * Evaluate the recurrent neural network with the given parameters. This - * function is usually called by the optimizer to train the model. - * - * @param parameters Matrix model parameters. - * @param begin Index of the starting point to use for objective function - * evaluation. - * @param batchSize Number of points to be passed at a time to use for - * objective function evaluation. - * @param deterministic Whether or not to train or test the model. Note some - * layer act differently in training or testing mode. - */ - double Evaluate(const arma::mat& parameters, - const size_t begin, - const size_t batchSize, - const bool deterministic); - - /** - * Evaluate the recurrent neural network with the given parameters. This - * function is usually called by the optimizer to train the model. This just - * calls the other overload of Evaluate() with deterministic = true. - * - * @param parameters Matrix model parameters. - * @param begin Index of the starting point to use for objective function - * evaluation. - * @param batchSize Number of points to be passed at a time to use for - * objective function evaluation. - */ - double Evaluate(const arma::mat& parameters, - const size_t begin, - const size_t batchSize) - { - return Evaluate(parameters, begin, batchSize, true); - } - - /** - * Evaluate the gradient of the recurrent neural network with the given - * parameters, and with respect to only one point in the dataset. This is - * useful for optimizers such as SGD, which require a separable objective - * function. - * - * @param parameters Matrix of the model parameters to be optimized. - * @param begin Index of the starting point to use for objective function - * gradient evaluation. - * @param gradient Matrix to output gradient into. - * @param batchSize Number of points to be processed as a batch for objective - * function gradient evaluation. - */ - void Gradient(const arma::mat& parameters, - const size_t begin, - arma::mat& gradient, - const size_t batchSize); - - /** - * Shuffle the order of function visitation. This may be called by the - * optimizer. - */ - void Shuffle(); - - /* - * Add a new module to the model. - * - * @param args The layer parameter. - */ - template - void Add(Args... args) { network.push_back(new LayerType(args...)); } - - /* - * Add a new module to the model. - * - * @param layer The Layer to be added to the model. - */ - void Add(LayerTypes layer) { network.push_back(layer); } - - //! Return the number of separable functions (the number of predictor points). - size_t NumFunctions() const { return numFunctions; } - - //! Return the initial point for the optimization. - const arma::mat& Parameters() const { return parameter; } - //! Modify the initial point for the optimization. - arma::mat& Parameters() { return parameter; } - - //! Return the maximum length of backpropagation through time. - const size_t& Rho() const { return rho; } - //! Modify the maximum length of backpropagation through time. - size_t& Rho() { return rho; } - - //! Get the matrix of responses to the input data points. - const arma::cube& Responses() const { return responses; } - //! Modify the matrix of responses to the input data points. - arma::cube& Responses() { return responses; } - - //! Get the matrix of data points (predictors). - const arma::cube& Predictors() const { return predictors; } - //! Modify the matrix of data points (predictors). - arma::cube& Predictors() { return predictors; } - - /** - * Reset the state of the network. This ensures that all internally-held - * gradients are set to 0, all memory cells are reset, and the parameters - * matrix is the right size. - */ - void Reset(); - - /** - * Reset the module information (weights/parameters). - */ - void ResetParameters(); - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - // Helper functions. - /** - * The Forward algorithm (part of the Forward-Backward algorithm). Computes - * forward probabilities for each module. - * - * @param input Data sequence to compute probabilities for. - */ - void Forward(arma::mat&& input); - - /** - * Reset the state of RNN cells in the network for new input sequence. - */ - void ResetCells(); - - /** - * The Backward algorithm (part of the Forward-Backward algorithm). Computes - * backward pass for module. - */ - void Backward(); - - /** - * Iterate through all layer modules and update the the gradient using the - * layer defined optimizer. - */ - template - void Gradient(InputType&& input); - - /** - * Reset the module status by setting the current deterministic parameter - * for all modules that implement the Deterministic function. - */ - void ResetDeterministic(); - - /** - * Reset the gradient for all modules that implement the Gradient function. - */ - void ResetGradients(arma::mat& gradient); - - //! Number of steps to backpropagate through time (BPTT). - size_t rho; - - //! Instantiated outputlayer used to evaluate the network. - OutputLayerType outputLayer; - - //! Instantiated InitializationRule object for initializing the network - //! parameter. - InitializationRuleType initializeRule; - - //! The input size. - size_t inputSize; - - //! The output size. - size_t outputSize; - - //! The target size. - size_t targetSize; - - //! Indicator if we already trained the model. - bool reset; - - //! Only predict the last element of the input sequence. - bool single; - - //! Locally-stored model modules. - std::vector > network; - - //! The matrix of data points (predictors). - arma::cube predictors; - - //! The matrix of responses to the input data points. - arma::cube responses; - - //! Matrix of (trained) parameters. - arma::mat parameter; - - //! The number of separable functions (the number of predictor points). - size_t numFunctions; - - //! The current error for the backward pass. - arma::mat error; - - //! Locally-stored delta visitor. - DeltaVisitor deltaVisitor; - - //! Locally-stored output parameter visitor. - OutputParameterVisitor outputParameterVisitor; - - //! List of all module parameters for the backward pass (BBTT). - std::vector moduleOutputParameter; - - //! Locally-stored weight size visitor. - WeightSizeVisitor weightSizeVisitor; - - //! Locally-stored reset visitor. - ResetVisitor resetVisitor; - - //! Locally-stored delete visitor. - DeleteVisitor deleteVisitor; - - //! The current evaluation mode (training or testing). - bool deterministic; - - //! The current gradient for the gradient pass. - arma::mat currentGradient; -}; // class RNN - -} // namespace ann -} // namespace mlpack - -//! Set the serialization version of the RNN class. Multiple template arguments -//! makes this ugly... -namespace boost { -namespace serialization { - -template -struct version< - mlpack::ann::RNN> -{ - BOOST_STATIC_CONSTANT(int, value = 1); -}; - -} // namespace serialization -} // namespace boost - -// Include implementation. -#include "rnn_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/rnn_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/rnn_impl.hpp deleted file mode 100644 index 8fc49d80a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/rnn_impl.hpp +++ /dev/null @@ -1,481 +0,0 @@ -/** - * @file rnn_impl.hpp - * @author Marcus Edel - * - * Definition of the RNN class, which implements recurrent neural networks. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_RNN_IMPL_HPP -#define MLPACK_METHODS_ANN_RNN_IMPL_HPP - -// In case it hasn't been included yet. -#include "rnn.hpp" - -#include "visitor/load_output_parameter_visitor.hpp" -#include "visitor/save_output_parameter_visitor.hpp" -#include "visitor/forward_visitor.hpp" -#include "visitor/backward_visitor.hpp" -#include "visitor/reset_cell_visitor.hpp" -#include "visitor/deterministic_set_visitor.hpp" -#include "visitor/gradient_set_visitor.hpp" -#include "visitor/gradient_visitor.hpp" -#include "visitor/weight_set_visitor.hpp" - -#include - -namespace mlpack { -namespace ann /** Artificial Neural Network. */ { - -template -RNN::RNN( - const size_t rho, - const bool single, - OutputLayerType outputLayer, - InitializationRuleType initializeRule) : - rho(rho), - outputLayer(std::move(outputLayer)), - initializeRule(std::move(initializeRule)), - inputSize(0), - outputSize(0), - targetSize(0), - reset(false), - single(single), - numFunctions(0), - deterministic(true) -{ - /* Nothing to do here */ -} - -template -RNN::~RNN() -{ - for (LayerTypes& layer : network) - { - boost::apply_visitor(deleteVisitor, layer); - } -} - -template -template -void RNN::Train( - arma::cube predictors, - arma::cube responses, - OptimizerType& optimizer) -{ - numFunctions = responses.n_cols; - - this->predictors = std::move(predictors); - this->responses = std::move(responses); - - this->deterministic = true; - ResetDeterministic(); - - if (!reset) - { - ResetParameters(); - } - - // Train the model. - Timer::Start("rnn_optimization"); - const double out = optimizer.Optimize(*this, parameter); - Timer::Stop("rnn_optimization"); - - Log::Info << "RNN::RNN(): final objective of trained model is " << out - << "." << std::endl; -} - -template -void RNN::ResetCells() -{ - for (size_t i = 1; i < network.size(); ++i) - { - boost::apply_visitor(ResetCellVisitor(rho), network[i]); - } -} - -template -template -void RNN::Train( - arma::cube predictors, - arma::cube responses) -{ - numFunctions = responses.n_cols; - - this->predictors = std::move(predictors); - this->responses = std::move(responses); - - this->deterministic = true; - ResetDeterministic(); - - if (!reset) - { - ResetParameters(); - } - - OptimizerType optimizer; - - // Train the model. - Timer::Start("rnn_optimization"); - const double out = optimizer.Optimize(*this, parameter); - Timer::Stop("rnn_optimization"); - - Log::Info << "RNN::RNN(): final objective of trained model is " << out - << "." << std::endl; -} - -template -void RNN::Predict( - arma::cube predictors, arma::cube& results, const size_t batchSize) -{ - ResetCells(); - - if (parameter.is_empty()) - { - ResetParameters(); - } - - if (!deterministic) - { - deterministic = true; - ResetDeterministic(); - } - - results = arma::zeros(outputSize, predictors.n_cols, rho); - // Process in accordance with the given batch size. - for (size_t begin = 0; begin < predictors.n_cols; begin += batchSize) - { - const size_t effectiveBatchSize = std::min(batchSize, - size_t(predictors.n_cols - begin)); - for (size_t seqNum = 0; seqNum < rho; ++seqNum) - { - Forward(std::move(arma::mat(predictors.slice(seqNum).colptr(begin), - predictors.n_rows, effectiveBatchSize, false, true))); - - results.slice(seqNum).submat(0, begin, results.n_rows - 1, begin + - effectiveBatchSize - 1) = boost::apply_visitor(outputParameterVisitor, - network.back()); - } - } -} - -template -double RNN::Evaluate( - const arma::mat& /* parameters */, - const size_t begin, - const size_t batchSize, - const bool deterministic) -{ - if (parameter.is_empty()) - { - ResetParameters(); - } - - if (deterministic != this->deterministic) - { - this->deterministic = deterministic; - ResetDeterministic(); - } - - if (!inputSize) - { - inputSize = predictors.n_rows; - targetSize = responses.n_rows; - } - else if (targetSize == 0) - { - targetSize = responses.n_rows; - } - - ResetCells(); - - double performance = 0; - size_t responseSeq = 0; - - for (size_t seqNum = 0; seqNum < rho; ++seqNum) - { - // Wrap a matrix around our data to avoid a copy. - arma::mat stepData(predictors.slice(seqNum).colptr(begin), - predictors.n_rows, batchSize, false, true); - Forward(std::move(stepData)); - if (!single) - { - responseSeq = seqNum; - } - - if (!deterministic) - { - for (size_t l = 0; l < network.size(); ++l) - { - boost::apply_visitor(SaveOutputParameterVisitor( - std::move(moduleOutputParameter)), network[l]); - } - } - - performance += outputLayer.Forward(std::move(boost::apply_visitor( - outputParameterVisitor, network.back())), - std::move(arma::mat(responses.slice(responseSeq).colptr(begin), - responses.n_rows, batchSize, false, true))); - } - - if (outputSize == 0) - { - outputSize = boost::apply_visitor(outputParameterVisitor, - network.back()).n_elem / batchSize; - } - - return performance; -} - -template -void RNN::Gradient( - const arma::mat& parameters, - const size_t begin, - arma::mat& gradient, - const size_t batchSize) -{ - // Initialize passed gradient. - if (gradient.is_empty()) - { - if (parameter.is_empty()) - { - ResetParameters(); - } - - gradient = arma::zeros(parameter.n_rows, parameter.n_cols); - } - else - { - gradient.zeros(); - } - - Evaluate(parameters, begin, batchSize, false); - - // Initialize current/working gradient. - if (currentGradient.is_empty()) - { - currentGradient = arma::zeros(parameter.n_rows, - parameter.n_cols); - } - - ResetGradients(currentGradient); - - for (size_t seqNum = 0; seqNum < rho; ++seqNum) - { - currentGradient.zeros(); - - for (size_t l = 0; l < network.size(); ++l) - { - boost::apply_visitor(LoadOutputParameterVisitor( - std::move(moduleOutputParameter)), network[network.size() - 1 - l]); - } - - if (single && seqNum > 0) - { - error.zeros(); - } - else if (single && seqNum == 0) - { - outputLayer.Backward(std::move(boost::apply_visitor( - outputParameterVisitor, network.back())), - std::move(arma::mat(responses.slice(0).colptr(begin), - responses.n_rows, batchSize, false, true)), std::move(error)); - } - else - { - outputLayer.Backward(std::move(boost::apply_visitor( - outputParameterVisitor, network.back())), - std::move(arma::mat(responses.slice(rho - seqNum - 1).colptr(begin), - responses.n_rows, batchSize, false, true)), std::move(error)); - } - - Backward(); - Gradient(std::move( - arma::mat(predictors.slice(rho - seqNum - 1).colptr(begin), - predictors.n_rows, batchSize, false, true))); - gradient += currentGradient; - } -} - -template -void RNN::Shuffle() -{ - arma::cube newPredictors, newResponses; - math::ShuffleData(predictors, responses, newPredictors, newResponses); - - predictors = std::move(newPredictors); - responses = std::move(newResponses); -} - -template -void RNN::ResetParameters() -{ - ResetDeterministic(); - - // Reset the network parameter with the given initialization rule. - NetworkInitialization networkInit(initializeRule); - networkInit.Initialize(network, parameter); - - reset = true; -} - -template -void RNN::Reset() -{ - ResetParameters(); - ResetCells(); - currentGradient.zeros(); - ResetGradients(currentGradient); -} - -template -void RNN::ResetDeterministic() -{ - DeterministicSetVisitor deterministicSetVisitor(deterministic); - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deterministicSetVisitor)); -} - -template -void RNN::ResetGradients( - arma::mat& gradient) -{ - size_t offset = 0; - for (LayerTypes& layer : network) - { - offset += boost::apply_visitor(GradientSetVisitor(std::move(gradient), - offset), layer); - } -} - -template -void RNN::Forward(arma::mat&& input) -{ - boost::apply_visitor(ForwardVisitor(std::move(input), std::move( - boost::apply_visitor(outputParameterVisitor, network.front()))), - network.front()); - - for (size_t i = 1; i < network.size(); ++i) - { - boost::apply_visitor(ForwardVisitor( - std::move(boost::apply_visitor(outputParameterVisitor, network[i - 1])), - std::move(boost::apply_visitor(outputParameterVisitor, network[i]))), - network[i]); - } -} - -template -void RNN::Backward() -{ - boost::apply_visitor(BackwardVisitor( - std::move(boost::apply_visitor(outputParameterVisitor, network.back())), - std::move(error), std::move(boost::apply_visitor(deltaVisitor, - network.back()))), network.back()); - - for (size_t i = 2; i < network.size(); ++i) - { - boost::apply_visitor(BackwardVisitor( - std::move(boost::apply_visitor(outputParameterVisitor, - network[network.size() - i])), std::move(boost::apply_visitor( - deltaVisitor, network[network.size() - i + 1])), std::move( - boost::apply_visitor(deltaVisitor, network[network.size() - i]))), - network[network.size() - i]); - } -} - -template -template -void RNN::Gradient(InputType&& input) -{ - boost::apply_visitor(GradientVisitor(std::move(input), std::move( - boost::apply_visitor(deltaVisitor, network[1]))), network.front()); - - for (size_t i = 1; i < network.size() - 1; ++i) - { - boost::apply_visitor(GradientVisitor( - std::move(boost::apply_visitor(outputParameterVisitor, network[i - 1])), - std::move(boost::apply_visitor(deltaVisitor, network[i + 1]))), - network[i]); - } -} - -template -template -void RNN::serialize( - Archive& ar, const unsigned int version) -{ - ar & BOOST_SERIALIZATION_NVP(parameter); - ar & BOOST_SERIALIZATION_NVP(rho); - ar & BOOST_SERIALIZATION_NVP(single); - ar & BOOST_SERIALIZATION_NVP(inputSize); - ar & BOOST_SERIALIZATION_NVP(outputSize); - ar & BOOST_SERIALIZATION_NVP(targetSize); - - // Earlier versions of the RNN code did not serialize the 'reset' variable. - if (version > 0) - { - ar & BOOST_SERIALIZATION_NVP(reset); - } - - if (Archive::is_loading::value) - { - std::for_each(network.begin(), network.end(), - boost::apply_visitor(deleteVisitor)); - network.clear(); - } - - ar & BOOST_SERIALIZATION_NVP(network); - - // If we are loading, we need to initialize the weights. - if (Archive::is_loading::value) - { - // Earlier versions of the RNN code assumed that the weights needed to be - // reset on load. - if (version == 0) - reset = false; - - size_t offset = 0; - for (LayerTypes& layer : network) - { - offset += boost::apply_visitor(WeightSetVisitor(std::move(parameter), - offset), layer); - - boost::apply_visitor(resetVisitor, layer); - } - - deterministic = true; - ResetDeterministic(); - } -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/add_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/add_visitor.hpp deleted file mode 100644 index c5dd2c625..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/add_visitor.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file add_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Add() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_ADD_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_ADD_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * AddVisitor exposes the Add() method of the given module. - */ -template -class AddVisitor : public boost::static_visitor -{ - public: - //! Exposes the Add() method of the given module. - template - AddVisitor(T newLayer); - - //! Exposes the Add() method. - template - void operator()(LayerType* layer) const; - - private: - //! The layer that should be added. - LayerTypes newLayer; - - //! Only add the layer if the module implements the Add() function. - template - typename std::enable_if< - HasAddCheck)>::value, void>::type - LayerAdd(T* layer) const; - - //! Do not add the layer if the module doesn't implement the Add() function. - template - typename std::enable_if< - !HasAddCheck)>::value, void>::type - LayerAdd(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "add_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/add_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/add_visitor_impl.hpp deleted file mode 100644 index 2a8b40257..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/add_visitor_impl.hpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file add_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Add() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_ADD_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_ADD_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "add_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! AddVisitor visitor class. -template -template -inline AddVisitor::AddVisitor(T newLayer) : - newLayer(std::move(newLayer)) -{ - /* Nothing to do here. */ -} - -template -template -inline void AddVisitor::operator()(LayerType* layer) const -{ - LayerAdd(layer); -} - -template -template -inline typename std::enable_if< - HasAddCheck)>::value, void>::type -AddVisitor::LayerAdd(T* layer) const -{ - layer->Add(newLayer); -} - -template -template -inline typename std::enable_if< - !HasAddCheck)>::value, void>::type -AddVisitor::LayerAdd(T* /* layer */) const -{ - /* Nothing to do here. */ -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/backward_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/backward_visitor.hpp deleted file mode 100644 index 77bf65452..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/backward_visitor.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @file backward_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Backward() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_BACKWARD_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_BACKWARD_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * BackwardVisitor executes the Backward() function given the input, error and - * delta parameter. - */ -class BackwardVisitor : public boost::static_visitor -{ - public: - //! Execute the Backward() function given the input, error and delta - //! parameter. - BackwardVisitor(arma::mat&& input, arma::mat&& error, arma::mat&& delta); - - //! Execute the Backward() function. - template - void operator()(LayerType* layer) const; - - private: - //! The input parameter set. - arma::mat&& input; - - //! The error parameter. - arma::mat&& error; - - //! The delta parameter. - arma::mat&& delta; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "backward_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/backward_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/backward_visitor_impl.hpp deleted file mode 100644 index 8a6c2552f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/backward_visitor_impl.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file backward_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Backward() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_BACKWARD_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_BACKWARD_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "backward_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! BackwardVisitor visitor class. -inline BackwardVisitor::BackwardVisitor(arma::mat&& input, - arma::mat&& error, - arma::mat&& delta) : - input(std::move(input)), - error(std::move(error)), - delta(std::move(delta)) -{ - /* Nothing to do here. */ -} - -template -inline void BackwardVisitor::operator()(LayerType* layer) const -{ - layer->Backward(std::move(input), std::move(error), std::move(delta)); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/copy_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/copy_visitor.hpp deleted file mode 100644 index 9c6260ed4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/copy_visitor.hpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @file copy_visitor.hpp - * @author Shangtong Zhang - * - * This file provides an abstraction for copy between layers. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_COPY_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_COPY_VISITOR_HPP - -#include -#include - -namespace mlpack { -namespace ann { - -/** - * This visitor is to support copy constructor for neural network module. - * We want a layer-wise copy rather than simple duplicate the pointer. - */ -template -class CopyVisitor : public boost::static_visitor > -{ - public: - template - LayerTypes operator()(LayerType*) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation -#include "copy_visitor_impl.hpp" -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/copy_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/copy_visitor_impl.hpp deleted file mode 100644 index 0cf21b031..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/copy_visitor_impl.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * @file copy_visitor_impl.hpp - * @author Shangtong Zhang - * - * This file provides an implementation for copy between layers - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_COPY_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_COPY_VISITOR_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace ann { - -template -template -inline LayerTypes -CopyVisitor::operator()(LayerType* layer) const -{ - return new LayerType(*layer); -} - -} // namespace ann -} // namespace mlpack - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delete_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delete_visitor.hpp deleted file mode 100644 index d1dac9985..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delete_visitor.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file delete_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Delete() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_DELETE_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_DELETE_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * DeleteVisitor executes the destructor of the instantiated object. - */ -class DeleteVisitor : public boost::static_visitor -{ - public: - //! Execute the destructor. - template - void operator()(LayerType* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "delete_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delete_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delete_visitor_impl.hpp deleted file mode 100644 index 43306b760..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delete_visitor_impl.hpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @file delete_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Delete() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_DELETE_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_DELETE_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "delete_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! DeleteVisitor visitor class. -template -inline void DeleteVisitor::operator()(LayerType* layer) const -{ - if (layer) - delete layer; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delta_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delta_visitor.hpp deleted file mode 100644 index 2631755b5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delta_visitor.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file delta_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Delta() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_DELTA_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_DELTA_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * DeltaVisitor exposes the delta parameter of the given module. - */ -class DeltaVisitor : public boost::static_visitor -{ - public: - //! Return the delta parameter. - template - arma::mat& operator()(LayerType* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "delta_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delta_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delta_visitor_impl.hpp deleted file mode 100644 index 84bcc7a28..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/delta_visitor_impl.hpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @file delta_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Delta() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_DELTA_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_DELTA_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "delta_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! DeltaVisitor visitor class. -template -inline arma::mat& DeltaVisitor::operator()(LayerType *layer) const -{ - return layer->Delta(); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/deterministic_set_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/deterministic_set_visitor.hpp deleted file mode 100644 index a0098f10e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/deterministic_set_visitor.hpp +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file deterministic_set_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Deterministic() function for - * different layers and automatically directs any parameter to the right layer - * type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_DETERMINISTIC_SET_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_DETERMINISTIC_SET_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * DeterministicSetVisitor set the deterministic parameter given the - * deterministic value. - */ -class DeterministicSetVisitor : public boost::static_visitor -{ - public: - //! Set the deterministic parameter given the current deterministic value. - DeterministicSetVisitor(const bool deterministic = true); - - //! Set the deterministic parameter. - template - void operator()(LayerType* layer) const; - - private: - //! The deterministic parameter. - const bool deterministic; - - //! Set the deterministic parameter if the module implements the - //! Deterministic() and Model() function. - template - typename std::enable_if< - HasDeterministicCheck::value && - HasModelCheck::value, void>::type - LayerDeterministic(T* layer) const; - - //! Set the deterministic parameter if the module implements the - //! Model() function. - template - typename std::enable_if< - !HasDeterministicCheck::value && - HasModelCheck::value, void>::type - LayerDeterministic(T* layer) const; - - //! Set the deterministic parameter if the module implements the - //! Deterministic() function. - template - typename std::enable_if< - HasDeterministicCheck::value && - !HasModelCheck::value, void>::type - LayerDeterministic(T* layer) const; - - //! Do not set the deterministic parameter if the module doesn't implement the - //! Deterministic() or Model() function. - template - typename std::enable_if< - !HasDeterministicCheck::value && - !HasModelCheck::value, void>::type - LayerDeterministic(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "deterministic_set_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/deterministic_set_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/deterministic_set_visitor_impl.hpp deleted file mode 100644 index 3ffc3efb0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/deterministic_set_visitor_impl.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @file deterministic_set_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Deterministic() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_DETERMINISTIC_SET_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_DETERMINISTIC_SET_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "deterministic_set_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! DeterministicSetVisitor visitor class. -inline DeterministicSetVisitor::DeterministicSetVisitor( - const bool deterministic) : deterministic(deterministic) -{ - /* Nothing to do here. */ -} - -template -inline void DeterministicSetVisitor::operator()(LayerType* layer) const -{ - LayerDeterministic(layer); -} - -template -inline typename std::enable_if< - HasDeterministicCheck::value && - HasModelCheck::value, void>::type -DeterministicSetVisitor::LayerDeterministic(T* layer) const -{ - layer->Deterministic() = deterministic; - - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(DeterministicSetVisitor(deterministic), - layer->Model()[i]); - } -} - -template -inline typename std::enable_if< - !HasDeterministicCheck::value && - HasModelCheck::value, void>::type -DeterministicSetVisitor::LayerDeterministic(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(DeterministicSetVisitor(deterministic), - layer->Model()[i]); - } -} - -template -inline typename std::enable_if< - HasDeterministicCheck::value && - !HasModelCheck::value, void>::type -DeterministicSetVisitor::LayerDeterministic(T* layer) const -{ - layer->Deterministic() = deterministic; -} - -template -inline typename std::enable_if< - !HasDeterministicCheck::value && - !HasModelCheck::value, void>::type -DeterministicSetVisitor::LayerDeterministic(T* /* input */) const -{ - /* Nothing to do here. */ -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/forward_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/forward_visitor.hpp deleted file mode 100644 index 9f363995d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/forward_visitor.hpp +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @file forward_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Forward() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_FORWARD_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_FORWARD_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * ForwardVisitor executes the Forward() function given the input and output - * parameter. - */ -class ForwardVisitor : public boost::static_visitor -{ - public: - //! Execute the Foward() function given the input and output parameter. - ForwardVisitor(arma::mat&& input, arma::mat&& output); - - //! Execute the Foward() function. - template - void operator()(LayerType* layer) const; - - private: - //! The input parameter set. - arma::mat&& input; - - //! The output parameter set. - arma::mat&& output; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "forward_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/forward_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/forward_visitor_impl.hpp deleted file mode 100644 index ce1c36e36..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/forward_visitor_impl.hpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @file forward_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Forward() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_FORWARD_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_FORWARD_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "forward_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! ForwardVisitor visitor class. -inline ForwardVisitor::ForwardVisitor(arma::mat&& input, arma::mat&& output) : - input(std::move(input)), - output(std::move(output)) -{ - /* Nothing to do here. */ -} - -template -inline void ForwardVisitor::operator()(LayerType* layer) const -{ - layer->Forward(std::move(input), std::move(output)); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_set_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_set_visitor.hpp deleted file mode 100644 index c260c7b14..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_set_visitor.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file gradient_set_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Gradient() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_GRADIENT_SET_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_GRADIENT_SET_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * GradientSetVisitor update the gradient parameter given the gradient set. - */ -class GradientSetVisitor : public boost::static_visitor -{ - public: - //! Update the gradient parameter given the gradient set. - GradientSetVisitor(arma::mat&& gradient, size_t offset = 0); - - //! Update the gradient parameter. - template - size_t operator()(LayerType* layer) const; - - private: - //! The gradient set. - arma::mat&& gradient; - - //! The gradient offset. - size_t offset; - - //! Update the gradient if the module implements the Gradient() function. - template - typename std::enable_if< - HasGradientCheck::value && - !HasModelCheck::value, size_t>::type - LayerGradients(T* layer, arma::mat& input) const; - - //! Update the gradient if the module implements the Model() function. - template - typename std::enable_if< - !HasGradientCheck::value && - HasModelCheck::value, size_t>::type - LayerGradients(T* layer, arma::mat& input) const; - - //! Update the gradient if the module implements the Gradient() and Model() - //! function. - template - typename std::enable_if< - HasGradientCheck::value && - HasModelCheck::value, size_t>::type - LayerGradients(T* layer, arma::mat& input) const; - - //! Do not update the gradient parameter if the module doesn't implement the - //! Gradient() or Model() function. - template - typename std::enable_if< - !HasGradientCheck::value && - !HasModelCheck::value, size_t>::type - LayerGradients(T* layer, P& input) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "gradient_set_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_set_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_set_visitor_impl.hpp deleted file mode 100644 index a6c443e05..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_set_visitor_impl.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @file gradient_set_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Gradient() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_GRADIENT_SET_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_GRADIENT_SET_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "gradient_set_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! GradientSetVisitor visitor class. -inline GradientSetVisitor::GradientSetVisitor(arma::mat&& gradient, - size_t offset) : - gradient(std::move(gradient)), - offset(offset) -{ - /* Nothing to do here. */ -} - -template -inline size_t GradientSetVisitor::operator()(LayerType* layer) const -{ - return LayerGradients(layer, layer->OutputParameter()); -} - -template -inline typename std::enable_if< - HasGradientCheck::value && - !HasModelCheck::value, size_t>::type -GradientSetVisitor::LayerGradients(T* layer, arma::mat& /* input */) const -{ - layer->Gradient() = arma::mat(gradient.memptr() + offset, - layer->Parameters().n_rows, layer->Parameters().n_cols, false, false); - - return layer->Parameters().n_elem; -} - -template -inline typename std::enable_if< - !HasGradientCheck::value && - HasModelCheck::value, size_t>::type -GradientSetVisitor::LayerGradients(T* layer, arma::mat& /* input */) const -{ - size_t modelOffset = 0; - for (size_t i = 0; i < layer->Model().size(); ++i) - { - modelOffset += boost::apply_visitor(GradientSetVisitor( - std::move(gradient), modelOffset + offset), layer->Model()[i]); - } - - return modelOffset; -} - -template -inline typename std::enable_if< - HasGradientCheck::value && - HasModelCheck::value, size_t>::type -GradientSetVisitor::LayerGradients(T* layer, arma::mat& /* input */) const -{ - layer->Gradient() = arma::mat(gradient.memptr() + offset, - layer->Parameters().n_rows, layer->Parameters().n_cols, false, false); - - size_t modelOffset = layer->Parameters().n_elem; - for (size_t i = 0; i < layer->Model().size(); ++i) - { - modelOffset += boost::apply_visitor(GradientSetVisitor( - std::move(gradient), modelOffset + offset), layer->Model()[i]); - } - - return modelOffset; -} - -template -inline typename std::enable_if< - !HasGradientCheck::value && - !HasModelCheck::value, size_t>::type -GradientSetVisitor::LayerGradients(T* /* layer */, P& /* input */) const -{ - return 0; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_update_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_update_visitor.hpp deleted file mode 100644 index 8afade254..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_update_visitor.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file gradient_update_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Gradient() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_GRADIENT_UPDATE_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_GRADIENT_UPDATE_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * GradientUpdateVisitor update the gradient parameter given the gradient set. - */ -class GradientUpdateVisitor : public boost::static_visitor -{ - public: - //! Update the gradient parameter given the gradient set. - GradientUpdateVisitor(arma::mat&& gradient, size_t offset = 0); - - //! Update the gradient parameter. - template - size_t operator()(LayerType* layer) const; - - private: - //! The gradient set. - arma::mat&& gradient; - - //! The gradient offset. - size_t offset; - - //! Update the gradient if the module implements the Gradient() function. - template - typename std::enable_if< - HasGradientCheck::value && - !HasModelCheck::value, size_t>::type - LayerGradients(T* layer, arma::mat& input) const; - - //! Update the gradient if the module implements the Model() function. - template - typename std::enable_if< - !HasGradientCheck::value && - HasModelCheck::value, size_t>::type - LayerGradients(T* layer, arma::mat& input) const; - - //! Update the gradient if the module implements the Gradient() and Model() - //! function. - template - typename std::enable_if< - HasGradientCheck::value && - HasModelCheck::value, size_t>::type - LayerGradients(T* layer, arma::mat& input) const; - - //! Do not update the gradient parameter if the module doesn't implement the - //! Gradient() or Model() function. - template - typename std::enable_if< - !HasGradientCheck::value && - !HasModelCheck::value, size_t>::type - LayerGradients(T* layer, P& input) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "gradient_update_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_update_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_update_visitor_impl.hpp deleted file mode 100644 index 561767271..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_update_visitor_impl.hpp +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @file gradient_update_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Gradient() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_GRADIENT_UPDATE_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_GRADIENT_UPDATE_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "gradient_update_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! GradientUpdateVisitor visitor class. -inline GradientUpdateVisitor::GradientUpdateVisitor(arma::mat&& gradient, - size_t offset) : - gradient(std::move(gradient)), - offset(offset) -{ - /* Nothing to do here. */ -} - -template -inline size_t GradientUpdateVisitor::operator()(LayerType* layer) const -{ - return LayerGradients(layer, layer->OutputParameter()); -} - -template -inline typename std::enable_if< - HasGradientCheck::value && - !HasModelCheck::value, size_t>::type -GradientUpdateVisitor::LayerGradients(T* layer, arma::mat& /* input */) const -{ - if (layer->Parameters().n_elem != 0) - { - layer->Gradient() = gradient.submat(offset, 0, - offset + layer->Parameters().n_elem - 1, 0);; - } - - return layer->Parameters().n_elem; -} - -template -inline typename std::enable_if< - !HasGradientCheck::value && - HasModelCheck::value, size_t>::type -GradientUpdateVisitor::LayerGradients(T* layer, arma::mat& /* input */) const -{ - size_t modelOffset = 0; - for (size_t i = 0; i < layer->Model().size(); ++i) - { - modelOffset += boost::apply_visitor(GradientUpdateVisitor( - std::move(gradient), modelOffset + offset), layer->Model()[i]); - } - - return modelOffset; -} - -template -inline typename std::enable_if< - HasGradientCheck::value && - HasModelCheck::value, size_t>::type -GradientUpdateVisitor::LayerGradients(T* layer, arma::mat& /* input */) const -{ - if (layer->Parameters().n_elem != 0) - { - layer->Gradient() = gradient.submat(offset, 0, - offset + layer->Parameters().n_elem - 1, 0);; - } - - size_t modelOffset = layer->Parameters().n_elem; - for (size_t i = 0; i < layer->Model().size(); ++i) - { - modelOffset += boost::apply_visitor(GradientUpdateVisitor( - std::move(gradient), modelOffset + offset), layer->Model()[i]); - } - - return modelOffset; -} - -template -inline typename std::enable_if< - !HasGradientCheck::value && - !HasModelCheck::value, size_t>::type -GradientUpdateVisitor::LayerGradients(T* /* layer */, P& /* input */) const -{ - return 0; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_visitor.hpp deleted file mode 100644 index 043f03f06..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_visitor.hpp +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @file gradient_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Gradient() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_GRADIENT_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_GRADIENT_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * SearchModeVisitor executes the Gradient() method of the given module using - * the input and delta parameter. - */ -class GradientVisitor : public boost::static_visitor -{ - public: - //! Executes the Gradient() method of the given module using the input and - //! delta parameter. - GradientVisitor(arma::mat&& input, arma::mat&& delta); - - //! Executes the Gradient() method. - template - void operator()(LayerType* layer) const; - - private: - //! The input set. - arma::mat&& input; - - //! The delta parameter. - arma::mat&& delta; - - //! Execute the Gradient() function if the module implements the Gradient() - //! function. - template - typename std::enable_if< - HasGradientCheck::value, void>::type - LayerGradients(T* layer, arma::mat& input) const; - - //! Do not execute the Gradient() function if the module doesn't implement - //! the Gradient() function. - template - typename std::enable_if< - !HasGradientCheck::value, void>::type - LayerGradients(T* layer, P& input) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "gradient_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_visitor_impl.hpp deleted file mode 100644 index 47d594439..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_visitor_impl.hpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @file gradient_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Gradient() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_GRADIENT_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_GRADIENT_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "gradient_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! GradientVisitor visitor class. -inline GradientVisitor::GradientVisitor(arma::mat&& input, arma::mat&& delta) : - input(std::move(input)), - delta(std::move(delta)) -{ - /* Nothing to do here. */ -} - -template -inline void GradientVisitor::operator()(LayerType* layer) const -{ - LayerGradients(layer, layer->OutputParameter()); -} - -template -inline typename std::enable_if< - HasGradientCheck::value, void>::type -GradientVisitor::LayerGradients(T* layer, arma::mat& /* input */) const -{ - layer->Gradient(std::move(input), std::move(delta), - std::move(layer->Gradient())); -} - -template -inline typename std::enable_if< - !HasGradientCheck::value, void>::type -GradientVisitor::LayerGradients(T* /* layer */, P& /* input */) const -{ - /* Nothing to do here. */ -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_zero_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_zero_visitor.hpp deleted file mode 100644 index 130e1f75a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_zero_visitor.hpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file gradient_zero_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Gradient() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_GRADIENT_ZERO_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_GRADIENT_ZERO_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/* - * GradientZeroVisitor set the gradient to zero for the given module. - */ -class GradientZeroVisitor : public boost::static_visitor -{ - public: - //! Set the gradient to zero for the given module. - GradientZeroVisitor(); - - //! Set the gradient to zero. - template - void operator()(LayerType* layer) const; - - private: - //! Set the gradient to zero if the module implements the Gradient() function. - template - typename std::enable_if< - HasGradientCheck::value, void>::type - LayerGradients(T* layer, arma::mat& input) const; - - //! Do not set the gradient to zero if the module doesn't implement the - //! Gradient() function. - template - typename std::enable_if< - !HasGradientCheck::value, void>::type - LayerGradients(T* layer, P& input) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "gradient_zero_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_zero_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_zero_visitor_impl.hpp deleted file mode 100644 index 5de2dc95e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/gradient_zero_visitor_impl.hpp +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @file gradient_zero_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Gradient() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_GRADIENT_ZERO_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_GRADIENT_ZERO_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "gradient_zero_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! GradientZeroVisitor visitor class. -inline GradientZeroVisitor::GradientZeroVisitor() -{ - /* Nothing to do here. */ -} - -template -inline void GradientZeroVisitor::operator()(LayerType* layer) const -{ - LayerGradients(layer, layer->OutputParameter()); -} - -template -inline typename std::enable_if< - HasGradientCheck::value, void>::type -GradientZeroVisitor::LayerGradients(T* layer, arma::mat& /* input */) const -{ - layer->Gradient().zeros(); -} - -template -inline typename std::enable_if< - !HasGradientCheck::value, void>::type -GradientZeroVisitor::LayerGradients(T* /* layer */, P& /* input */) const -{ - /* Nothing to do here. */ -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/load_output_parameter_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/load_output_parameter_visitor.hpp deleted file mode 100644 index 7150af13e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/load_output_parameter_visitor.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file load_output_parameter_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the OutputParameter() function for - * different layers and automatically directs any parameter to the right layer - * type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_LOAD_OUTPUT_PARAMETER_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_LOAD_OUTPUT_PARAMETER_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * LoadOutputParameterVisitor restores the output parameter using the given - * parameter set. - */ -class LoadOutputParameterVisitor : public boost::static_visitor -{ - public: - //! Restore the output parameter given a parameter set. - LoadOutputParameterVisitor(std::vector&& parameter); - - //! Restore the output parameter. - template - void operator()(LayerType* layer) const; - - private: - //! The parameter set. - std::vector&& parameter; - - //! Restore the output parameter for a module which doesn't implement the - //! Model() function. - template - typename std::enable_if< - !HasModelCheck::value, void>::type - OutputParameter(T* layer) const; - - //! Restore the output parameter for a module which implements the Model() - //! function. - template - typename std::enable_if< - HasModelCheck::value, void>::type - OutputParameter(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "load_output_parameter_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/load_output_parameter_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/load_output_parameter_visitor_impl.hpp deleted file mode 100644 index ad341c7e3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/load_output_parameter_visitor_impl.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @file load_output_parameter_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the OutputParameter() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_LOAD_OUTPUT_PARAMETER_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_LOAD_OUTPUT_PARAMETER_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "load_output_parameter_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! LoadOutputParameterVisitor visitor class. -inline LoadOutputParameterVisitor::LoadOutputParameterVisitor( - std::vector&& parameter) : parameter(std::move(parameter)) -{ - /* Nothing to do here. */ -} - -template -inline void LoadOutputParameterVisitor::operator()(LayerType* layer) const -{ - OutputParameter(layer); -} - -template -inline typename std::enable_if< - !HasModelCheck::value, void>::type -LoadOutputParameterVisitor::OutputParameter(T* layer) const -{ - layer->OutputParameter() = parameter.back(); - parameter.pop_back(); -} - -template -inline typename std::enable_if< - HasModelCheck::value, void>::type -LoadOutputParameterVisitor::OutputParameter(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(LoadOutputParameterVisitor(std::move(parameter)), - layer->Model()[layer->Model().size() - i - 1]); - } - - layer->OutputParameter() = parameter.back(); - parameter.pop_back(); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_height_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_height_visitor.hpp deleted file mode 100644 index b2d968d64..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_height_visitor.hpp +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file output_height_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the OutputHeight() function for - * different layers and automatically directs any parameter to the right layer - * type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_OUTPUT_HEIGHT_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_OUTPUT_HEIGHT_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * OutputWidthVisitor exposes the OutputHeight() method of the given module. - */ -class OutputHeightVisitor : public boost::static_visitor -{ - public: - //! Return the output height. - template - size_t operator()(LayerType* layer) const; - - private: - //! Return 0 if the module doesn't implement the InputHeight() or Model() - //! function. - template - typename std::enable_if< - !HasInputHeight::value && - !HasModelCheck::value, size_t>::type - LayerOutputHeight(T* layer) const; - - //! Return the output height if the module implements the InputHeight() - //! function. - template - typename std::enable_if< - HasInputHeight::value && - !HasModelCheck::value, size_t>::type - LayerOutputHeight(T* layer) const; - - //! Return the output height if the module implements the Model() function. - template - typename std::enable_if< - !HasInputHeight::value && - HasModelCheck::value, size_t>::type - LayerOutputHeight(T* layer) const; - - //! Return the output height if the module implement the Model() or - //! InputHeight() function. - template - typename std::enable_if< - HasInputHeight::value && - HasModelCheck::value, size_t>::type - LayerOutputHeight(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "output_height_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_height_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_height_visitor_impl.hpp deleted file mode 100644 index f6c04b42f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_height_visitor_impl.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file output_height_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the OutputHeight() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_OUTPUT_HEIGHT_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_OUTPUT_HEIGHT_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "output_height_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! OutputHeightVisitor visitor class. -template -inline size_t OutputHeightVisitor::operator()(LayerType* layer) const -{ - return LayerOutputHeight(layer); -} - -template -inline typename std::enable_if< - !HasInputHeight::value && - !HasModelCheck::value, size_t>::type -OutputHeightVisitor::LayerOutputHeight(T* /* layer */) const -{ - return 0; -} - -template -inline typename std::enable_if< - HasInputHeight::value && - !HasModelCheck::value, size_t>::type -OutputHeightVisitor::LayerOutputHeight(T* layer) const -{ - return layer->OutputHeight(); -} - -template -inline typename std::enable_if< - !HasInputHeight::value && - HasModelCheck::value, size_t>::type -OutputHeightVisitor::LayerOutputHeight(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - size_t outputHeight = boost::apply_visitor(OutputHeightVisitor(), - layer->Model()[layer->Model().size() - 1 - i]); - - if (outputHeight != 0) - { - return outputHeight; - } - } - - return 0; -} - -template -inline typename std::enable_if< - HasInputHeight::value && - HasModelCheck::value, size_t>::type -OutputHeightVisitor::LayerOutputHeight(T* layer) const -{ - size_t outputHeight = layer->OutputHeight(); - - if (outputHeight == 0) - { - for (size_t i = 0; i < layer->Model().size(); ++i) - { - outputHeight = boost::apply_visitor(OutputHeightVisitor(), - layer->Model()[layer->Model().size() - 1 - i]); - - if (outputHeight != 0) - { - return outputHeight; - } - } - } - - return outputHeight; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_parameter_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_parameter_visitor.hpp deleted file mode 100644 index ec7884e55..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_parameter_visitor.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file output_parameter_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the OutputParameter() function for - * different layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_OUTPUT_PARAMETER_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_OUTPUT_PARAMETER_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * OutputParameterVisitor exposes the output parameter of the given module. - */ -class OutputParameterVisitor : public boost::static_visitor -{ - public: - //! Return the output parameter set. - template - arma::mat& operator()(LayerType* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "output_parameter_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_parameter_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_parameter_visitor_impl.hpp deleted file mode 100644 index 8ce201f21..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_parameter_visitor_impl.hpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @file output_parameter_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the OutputParameter() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_OUTPUT_PARAMETER_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_OUTPUT_PARAMETER_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "output_parameter_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! OutputParameterVisitor visitor class. -template -inline arma::mat& OutputParameterVisitor::operator()(LayerType *layer) const -{ - return layer->OutputParameter(); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_width_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_width_visitor.hpp deleted file mode 100644 index 0167860e4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_width_visitor.hpp +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file output_width_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the OutputWidth() function for - * different layers and automatically directs any parameter to the right layer - * type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_OUTPUT_WIDTH_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_OUTPUT_WIDTH_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * OutputWidthVisitor exposes the OutputWidth() method of the given module. - */ -class OutputWidthVisitor : public boost::static_visitor -{ - public: - //! Return the output width. - template - size_t operator()(LayerType* layer) const; - - private: - //! Return 0 if the module doesn't implement the InputWidth() or Model() - //! function. - template - typename std::enable_if< - !HasInputWidth::value && - !HasModelCheck::value, size_t>::type - LayerOutputWidth(T* layer) const; - - //! Return the output width if the module implements the InputWidth() - //! function. - template - typename std::enable_if< - HasInputWidth::value && - !HasModelCheck::value, size_t>::type - LayerOutputWidth(T* layer) const; - - //! Return the output width if the module implements the Model() function. - template - typename std::enable_if< - !HasInputWidth::value && - HasModelCheck::value, size_t>::type - LayerOutputWidth(T* layer) const; - - //! Return the output width if the module implements the Model() or - //! InputWidth() function. - template - typename std::enable_if< - HasInputWidth::value && - HasModelCheck::value, size_t>::type - LayerOutputWidth(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "output_width_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_width_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_width_visitor_impl.hpp deleted file mode 100644 index b541d0f49..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/output_width_visitor_impl.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file output_width_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the OutputWidth() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_OUTPUT_WIDTH_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_OUTPUT_WIDTH_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "output_width_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! OutputWidthVisitor visitor class. -template -inline size_t OutputWidthVisitor::operator()(LayerType* layer) const -{ - return LayerOutputWidth(layer); -} - -template -inline typename std::enable_if< - !HasInputWidth::value && - !HasModelCheck::value, size_t>::type -OutputWidthVisitor::LayerOutputWidth(T* /* layer */) const -{ - return 0; -} - -template -inline typename std::enable_if< - HasInputWidth::value && - !HasModelCheck::value, size_t>::type -OutputWidthVisitor::LayerOutputWidth(T* layer) const -{ - return layer->OutputWidth(); -} - -template -inline typename std::enable_if< - !HasInputWidth::value && - HasModelCheck::value, size_t>::type -OutputWidthVisitor::LayerOutputWidth(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - size_t outputWidth = boost::apply_visitor(OutputWidthVisitor(), - layer->Model()[layer->Model().size() - 1 - i]); - - if (outputWidth != 0) - { - return outputWidth; - } - } - - return 0; -} - -template -inline typename std::enable_if< - HasInputWidth::value && - HasModelCheck::value, size_t>::type -OutputWidthVisitor::LayerOutputWidth(T* layer) const -{ - size_t outputWidth = layer->OutputWidth(); - - if (outputWidth == 0) - { - for (size_t i = 0; i < layer->Model().size(); ++i) - { - outputWidth = boost::apply_visitor(OutputWidthVisitor(), - layer->Model()[layer->Model().size() - 1 - i]); - - if (outputWidth != 0) - { - return outputWidth; - } - } - } - - return outputWidth; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_set_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_set_visitor.hpp deleted file mode 100644 index 3f6e11749..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_set_visitor.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file parameters_set_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Parameters() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_PARAMETERS_SET_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_PARAMETERS_SET_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * ParametersSetVisitor update the parameters set using the given matrix. - */ -class ParametersSetVisitor : public boost::static_visitor -{ - public: - //! Update the parameters set given the parameters matrix. - ParametersSetVisitor(arma::mat&& parameters); - - //! Update the parameters set. - template - void operator()(LayerType *layer) const; - - private: - //! The parameters set. - arma::mat&& parameters; - - //! Do not update the parameters set if the module doesn't implement the - //! Parameters() function. - template - typename std::enable_if< - !HasParametersCheck::value, void>::type - LayerParameters(T* layer, P& output) const; - - //! Update the parameters set if the module implements the Parameters() - //! function. - template - typename std::enable_if< - HasParametersCheck::value, void>::type - LayerParameters(T* layer, P& output) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "parameters_set_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_set_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_set_visitor_impl.hpp deleted file mode 100644 index 42a149a12..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_set_visitor_impl.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file parameters_set_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Parameters() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_PARAMETERS_SET_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_PARAMETERS_SET_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "parameters_set_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! ParametersSetVisitor visitor class. -inline ParametersSetVisitor::ParametersSetVisitor(arma::mat&& parameters) : - parameters(std::move(parameters)) -{ - /* Nothing to do here. */ -} - -template -inline void ParametersSetVisitor::operator()(LayerType *layer) const -{ - LayerParameters(layer, layer->OutputParameter()); -} - -template -inline typename std::enable_if< - !HasParametersCheck::value, void>::type -ParametersSetVisitor::LayerParameters(T* /* layer */, P& /* output */) const -{ - /* Nothing to do here. */ -} - -template -inline typename std::enable_if< - HasParametersCheck::value, void>::type -ParametersSetVisitor::LayerParameters(T* layer, P& /* output */) const -{ - layer->Parameters() = parameters; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_visitor.hpp deleted file mode 100644 index c09c801d9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_visitor.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file parameters_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Parameters() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_PARAMETERS_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_PARAMETERS_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * ParametersVisitor exposes the parameters set of the given module and stores - * the parameters set into the given matrix. - */ -class ParametersVisitor : public boost::static_visitor -{ - public: - //! Store the parameters set into the given parameters matrix. - ParametersVisitor(arma::mat&& parameters); - - //! Set the parameters set. - template - void operator()(LayerType* layer) const; - - private: - //! The parameters set. - arma::mat&& parameters; - - //! Do not set the parameters set if the module doesn't implement the - //! Parameters() function. - template - typename std::enable_if< - !HasParametersCheck::value, void>::type - LayerParameters(T* layer, P& output) const; - - //! Set the parameters set if the module implements the Parameters() function. - template - typename std::enable_if< - HasParametersCheck::value, void>::type - LayerParameters(T* layer, P& output) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "parameters_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_visitor_impl.hpp deleted file mode 100644 index d26cd699e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/parameters_visitor_impl.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file parameters_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Parameters() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_PARAMETERS_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_PARAMETERS_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "parameters_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! ParametersVisitor visitor class. -inline ParametersVisitor::ParametersVisitor(arma::mat&& parameters) : - parameters(std::move(parameters)) -{ - /* Nothing to do here. */ -} - -template -inline void ParametersVisitor::operator()(LayerType *layer) const -{ - LayerParameters(layer, layer->OutputParameter()); -} - -template -inline typename std::enable_if< - !HasParametersCheck::value, void>::type -ParametersVisitor::LayerParameters(T* /* layer */, P& /* output */) const -{ - /* Nothing to do here. */ -} - -template -inline typename std::enable_if< - HasParametersCheck::value, void>::type -ParametersVisitor::LayerParameters(T* layer, P& /* output */) const -{ - parameters = layer->Parameters(); -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_cell_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_cell_visitor.hpp deleted file mode 100644 index d1fdee57f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_cell_visitor.hpp +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @file reset_cell_visitor.hpp - * @author Sumedh Ghaisas - * - * Boost static visitor abstraction for calling ResetCell function on RNN cells. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_RESET_CELL_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_RESET_CELL_VISITOR_HPP - -#include -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * ResetCellVisitor executes the ResetCell() function. - */ -class ResetCellVisitor : public boost::static_visitor -{ - public: - //! Reset the cell using the given size. - ResetCellVisitor(const size_t size); - - //! Execute the ResetCell() function. - template - void operator()(LayerType* layer) const; - - private: - size_t size; - - //! Execute the ResetCell() function for a module which implements - //! the ResetCell() function. - template - typename std::enable_if< - HasResetCellCheck::value, void>::type - ResetCell(T* layer) const; - - //! Do not execute the Reset() function for a module which doesn't implement - // the Reset() or Model() function. - template - typename std::enable_if< - !HasResetCellCheck::value, void>::type - ResetCell(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "reset_cell_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_cell_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_cell_visitor_impl.hpp deleted file mode 100644 index 659b9b5c9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_cell_visitor_impl.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file reset_cell_visitor_impl.hpp - * @author Sumedh Ghaisas - * - * Implementation of the ResetCell() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_RESET_CELL_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_RESET_CELL_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "reset_cell_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! ResetVisitor visitor class. -inline ResetCellVisitor::ResetCellVisitor(const size_t size) : size(size) -{ - /* Nothing to do here. */ -} - -//! ResetVisitor visitor class. -template -inline void ResetCellVisitor::operator()(LayerType* layer) const -{ - ResetCell(layer); -} - -template -inline typename std::enable_if< - HasResetCellCheck::value, void>::type -ResetCellVisitor::ResetCell(T* layer) const -{ - layer->ResetCell(size); -} - -template -inline typename std::enable_if< - !HasResetCellCheck::value, void>::type -ResetCellVisitor::ResetCell(T* /* layer */) const -{ - /* Nothing to do here. */ -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_visitor.hpp deleted file mode 100644 index e8d340f42..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_visitor.hpp +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @file reset_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Reset() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_RESET_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_RESET_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * ResetVisitor executes the Reset() function. - */ -class ResetVisitor : public boost::static_visitor -{ - public: - //! Execute the Reset() function. - template - void operator()(LayerType* layer) const; - - private: - //! Execute the Reset() function for a module which implements the Reset() - //! function. - template - typename std::enable_if< - HasResetCheck::value && - !HasModelCheck::value, void>::type - ResetParameter(T* layer) const; - - //! Execute the Reset() function for a module which implements the Model() - //! function. - template - typename std::enable_if< - !HasResetCheck::value && - HasModelCheck::value, void>::type - ResetParameter(T* layer) const; - - //! Execute the Reset() function for a module which implements the Reset() - //! and Model() function. - template - typename std::enable_if< - HasResetCheck::value && - HasModelCheck::value, void>::type - ResetParameter(T* layer) const; - - //! Do not execute the Reset() function for a module which doesn't implement - // the Reset() or Model() function. - template - typename std::enable_if< - !HasResetCheck::value && - !HasModelCheck::value, void>::type - ResetParameter(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "reset_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_visitor_impl.hpp deleted file mode 100644 index 4f847c254..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reset_visitor_impl.hpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file reset_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Reset() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_RESET_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_RESET_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "reset_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! ResetVisitor visitor class. -template -inline void ResetVisitor::operator()(LayerType* layer) const -{ - ResetParameter(layer); -} - -template -inline typename std::enable_if< - HasResetCheck::value && - !HasModelCheck::value, void>::type -ResetVisitor::ResetParameter(T* layer) const -{ - layer->Reset(); -} - -template -inline typename std::enable_if< - !HasResetCheck::value && - HasModelCheck::value, void>::type -ResetVisitor::ResetParameter(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(ResetVisitor(), layer->Model()[i]); - } -} - -template -inline typename std::enable_if< - HasResetCheck::value && - HasModelCheck::value, void>::type -ResetVisitor::ResetParameter(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(ResetVisitor(), layer->Model()[i]); - } - - layer->Reset(); -} - -template -inline typename std::enable_if< - !HasResetCheck::value && - !HasModelCheck::value, void>::type -ResetVisitor::ResetParameter(T* /* layer */) const -{ - /* Nothing to do here. */ -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reward_set_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reward_set_visitor.hpp deleted file mode 100644 index 376ed1317..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reward_set_visitor.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file reward_set_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Reward() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_REWARD_SET_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_REWARD_SET_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * RewardSetVisitor set the reward parameter given the reward value. - */ -class RewardSetVisitor : public boost::static_visitor -{ - public: - //! Set the reward parameter given the reward value. - RewardSetVisitor(const double reward); - - //! Set the reward parameter. - template - void operator()(LayerType* layer) const; - - private: - //! The reward value. - const double reward; - - //! Set the deterministic parameter if the module implements the - //! Deterministic() and Model() function. - template - typename std::enable_if< - HasRewardCheck::value && - HasModelCheck::value, void>::type - LayerReward(T* layer) const; - - //! Set the deterministic parameter if the module implements the - //! Model() function. - template - typename std::enable_if< - !HasRewardCheck::value && - HasModelCheck::value, void>::type - LayerReward(T* layer) const; - - //! Set the deterministic parameter if the module implements the - //! Deterministic() function. - template - typename std::enable_if< - HasRewardCheck::value && - !HasModelCheck::value, void>::type - LayerReward(T* layer) const; - - //! Do not set the deterministic parameter if the module doesn't implement the - //! Deterministic() or Model() function. - template - typename std::enable_if< - !HasRewardCheck::value && - !HasModelCheck::value, void>::type - LayerReward(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "reward_set_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reward_set_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reward_set_visitor_impl.hpp deleted file mode 100644 index f6a6171d0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/reward_set_visitor_impl.hpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file reward_set_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Reward() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_REWARD_SET_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_REWARD_SET_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "reward_set_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! RewardSetVisitor visitor class. -inline RewardSetVisitor::RewardSetVisitor(const double reward) : reward(reward) -{ - /* Nothing to do here. */ -} - -template -inline void RewardSetVisitor::operator()(LayerType* layer) const -{ - LayerReward(layer); -} - -template -inline typename std::enable_if< - HasRewardCheck::value && - HasModelCheck::value, void>::type -RewardSetVisitor::LayerReward(T* layer) const -{ - layer->Reward() = reward; - - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(RewardSetVisitor(reward), - layer->Model()[i]); - } -} - -template -inline typename std::enable_if< - !HasRewardCheck::value && - HasModelCheck::value, void>::type -RewardSetVisitor::LayerReward(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(RewardSetVisitor(reward), - layer->Model()[i]); - } -} - -template -inline typename std::enable_if< - HasRewardCheck::value && - !HasModelCheck::value, void>::type -RewardSetVisitor::LayerReward(T* layer) const -{ - layer->Reward() = reward; -} - -template -inline typename std::enable_if< - !HasRewardCheck::value && - !HasModelCheck::value, void>::type -RewardSetVisitor::LayerReward(T* /* input */) const -{ - /* Nothing to do here. */ -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/save_output_parameter_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/save_output_parameter_visitor.hpp deleted file mode 100644 index 8f7411033..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/save_output_parameter_visitor.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file save_output_parameter_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the OutputParameter() function for - * different layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_SAVE_OUTPUT_PARAMETER_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_SAVE_OUTPUT_PARAMETER_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * SaveOutputParameterVisitor saves the output parameter into the given - * parameter set. - */ -class SaveOutputParameterVisitor : public boost::static_visitor -{ - public: - //! Save the output parameter into the given parameter set. - SaveOutputParameterVisitor(std::vector&& parameter); - - //! Save the output parameter. - template - void operator()(LayerType* layer) const; - - private: - //! The parameter set. - std::vector&& parameter; - - //! Save the output parameter for a module which doesn't implement the - //! Model() function. - template - typename std::enable_if< - !HasModelCheck::value, void>::type - OutputParameter(T* layer) const; - - //! Save the output parameter for a module which implements the Model() - //! function. - template - typename std::enable_if< - HasModelCheck::value, void>::type - OutputParameter(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "save_output_parameter_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/save_output_parameter_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/save_output_parameter_visitor_impl.hpp deleted file mode 100644 index 8b6707769..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/save_output_parameter_visitor_impl.hpp +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @file save_output_parameter_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the OutputParameter() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_SAVE_OUTPUT_PARAMETER_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_SAVE_OUTPUT_PARAMETER_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "load_output_parameter_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! SaveOutputParameterVisitor visitor class. -inline SaveOutputParameterVisitor::SaveOutputParameterVisitor( - std::vector&& parameter) : parameter(std::move(parameter)) -{ - /* Nothing to do here. */ -} - -template -inline void SaveOutputParameterVisitor::operator()(LayerType* layer) const -{ - OutputParameter(layer); -} - -template -inline typename std::enable_if< - !HasModelCheck::value, void>::type -SaveOutputParameterVisitor::OutputParameter(T* layer) const -{ - parameter.push_back(layer->OutputParameter()); -} - -template -inline typename std::enable_if< - HasModelCheck::value, void>::type -SaveOutputParameterVisitor::OutputParameter(T* layer) const -{ - parameter.push_back(layer->OutputParameter()); - - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(SaveOutputParameterVisitor(std::move(parameter)), - layer->Model()[i]); - } -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_height_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_height_visitor.hpp deleted file mode 100644 index 777454ca0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_height_visitor.hpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file set_input_height_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the InputHeight() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_SET_INPUT_HEIGHT_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_SET_INPUT_HEIGHT_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * SetInputHeightVisitor updates the input height parameter with the given input - * height. - */ -class SetInputHeightVisitor : public boost::static_visitor -{ - public: - //! Update the input height parameter with the given input height. - SetInputHeightVisitor(const size_t inputHeight = 0, const bool reset = false); - - //! Update the input height parameter. - template - bool operator()(LayerType* layer) const; - - private: - //! The input height parameter. - size_t inputHeight; - - //! If set reset the height parameter if already set. - bool reset; - - //! Do nothing if the module doesn't implement the InputHeight() or Model() - //! function. - template - typename std::enable_if< - !HasInputHeight::value && - !HasModelCheck::value, bool>::type - LayerInputHeight(T* layer) const; - - //! Update the input height if the module implements the InputHeight() - //! function. - template - typename std::enable_if< - HasInputHeight::value && - !HasModelCheck::value, bool>::type - LayerInputHeight(T* layer) const; - - //! Update the input height if the module implements the Model() function. - template - typename std::enable_if< - !HasInputHeight::value && - HasModelCheck::value, bool>::type - LayerInputHeight(T* layer) const; - - //! Update the input height if the module implements the InputHeight() or - //! Model() function. - template - typename std::enable_if< - HasInputHeight::value && - HasModelCheck::value, bool>::type - LayerInputHeight(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "set_input_height_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_height_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_height_visitor_impl.hpp deleted file mode 100644 index afd465b40..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_height_visitor_impl.hpp +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @file set_input_height_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the InputHeight() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_SET_INPUT_HEIGHT_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_SET_INPUT_HEIGHT_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "set_input_height_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! SetInputHeightVisitor visitor class. -inline SetInputHeightVisitor::SetInputHeightVisitor(const size_t inputHeight, - const bool reset) : - inputHeight(inputHeight), - reset(reset) -{ - /* Nothing to do here. */ -} - -template -inline bool SetInputHeightVisitor::operator()(LayerType* layer) const -{ - return LayerInputHeight(layer); -} - -template -inline typename std::enable_if< - !HasInputHeight::value && - !HasModelCheck::value, bool>::type -SetInputHeightVisitor::LayerInputHeight(T* /* layer */) const -{ - return false; -} - -template -inline typename std::enable_if< - HasInputHeight::value && - !HasModelCheck::value, bool>::type -SetInputHeightVisitor::LayerInputHeight(T* layer) const -{ - if (layer->InputHeight() == 0 || reset) - { - layer->InputHeight() = inputHeight; - } - - return true; -} - -template -inline typename std::enable_if< - !HasInputHeight::value && - HasModelCheck::value, bool>::type -SetInputHeightVisitor::LayerInputHeight(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(SetInputHeightVisitor(inputHeight, reset), - layer->Model()[i]); - } - - return true; -} - -template -inline typename std::enable_if< - HasInputHeight::value && - HasModelCheck::value, bool>::type -SetInputHeightVisitor::LayerInputHeight(T* layer) const -{ - if (layer->InputHeight() == 0 || reset) - { - layer->InputHeight() = inputHeight; - } - - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(SetInputHeightVisitor(inputHeight, reset), - layer->Model()[i]); - } - - return true; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_width_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_width_visitor.hpp deleted file mode 100644 index 0b75f29d0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_width_visitor.hpp +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file set_input_width_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the InputWidth() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_SET_INPUT_WIDTH_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_SET_INPUT_WIDTH_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * SetInputWidthVisitor updates the input width parameter with the given input - * width. - */ -class SetInputWidthVisitor : public boost::static_visitor -{ - public: - //! Update the input width parameter with the given input width. - SetInputWidthVisitor(const size_t inputWidth = 0, const bool reset = false); - - //! Update the input width parameter. - template - bool operator()(LayerType* layer) const; - - private: - //! The input width parameter. - size_t inputWidth; - - //! If set reset the height parameter if already set. - bool reset; - - //! Do nothing if the module doesn't implement the InputWidth() or Model() - //! function. - template - typename std::enable_if< - !HasInputWidth::value && - !HasModelCheck::value, bool>::type - LayerInputWidth(T* layer) const; - - //! Update the input width if the module implements the InputWidth() function. - template - typename std::enable_if< - HasInputWidth::value && - !HasModelCheck::value, bool>::type - LayerInputWidth(T* layer) const; - - //! Update the input width if the module implements the Model() function. - template - typename std::enable_if< - !HasInputWidth::value && - HasModelCheck::value, bool>::type - LayerInputWidth(T* layer) const; - - //! Update the input width if the module implements the InputWidth() or - //! Model() function. - template - typename std::enable_if< - HasInputWidth::value && - HasModelCheck::value, bool>::type - LayerInputWidth(T* layer) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "set_input_width_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_width_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_width_visitor_impl.hpp deleted file mode 100644 index 7f57f82bf..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/set_input_width_visitor_impl.hpp +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @file set_input_width_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the InputWidth() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_SET_INPUT_WIDTH_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_SET_INPUT_WIDTH_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "set_input_width_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! SetInputWidthVisitor visitor class. -inline SetInputWidthVisitor::SetInputWidthVisitor(const size_t inputWidth, - const bool reset) : - inputWidth(inputWidth), - reset(reset) -{ - /* Nothing to do here. */ -} - -template -inline bool SetInputWidthVisitor::operator()(LayerType* layer) const -{ - return LayerInputWidth(layer); -} - -template -inline typename std::enable_if< - !HasInputWidth::value && - !HasModelCheck::value, bool>::type -SetInputWidthVisitor::LayerInputWidth(T* /* layer */) const -{ - return false; -} - -template -inline typename std::enable_if< - HasInputWidth::value && - !HasModelCheck::value, bool>::type -SetInputWidthVisitor::LayerInputWidth(T* layer) const -{ - if (layer->InputWidth() == 0 || reset) - { - layer->InputWidth() = inputWidth; - } - - return true; -} - -template -inline typename std::enable_if< - !HasInputWidth::value && - HasModelCheck::value, bool>::type -SetInputWidthVisitor::LayerInputWidth(T* layer) const -{ - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(SetInputWidthVisitor(inputWidth, reset), - layer->Model()[i]); - } - - return true; -} - -template -inline typename std::enable_if< - HasInputWidth::value && - HasModelCheck::value, bool>::type -SetInputWidthVisitor::LayerInputWidth(T* layer) const -{ - if (layer->InputWidth() == 0 || reset) - { - layer->InputWidth() = inputWidth; - } - - for (size_t i = 0; i < layer->Model().size(); ++i) - { - boost::apply_visitor(SetInputWidthVisitor(inputWidth, reset), - layer->Model()[i]); - } - - return true; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_set_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_set_visitor.hpp deleted file mode 100644 index e37d7ef56..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_set_visitor.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file weight_set_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the Weight() function for different - * layers and automatically directs any parameter to the right layer type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_WEIGHT_SET_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_WEIGHT_SET_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * WeightSetVisitor update the module parameters given the parameters set. - */ -class WeightSetVisitor : public boost::static_visitor -{ - public: - //! Update the parameters given the parameters set and offset. - WeightSetVisitor(arma::mat&& weight, const size_t offset = 0); - - //! Update the parameters set. - template - size_t operator()(LayerType* layer) const; - - private: - //! The parameters set. - arma::mat&& weight; - - //! The parameters offset. - const size_t offset; - - //! Do not update the parameters if the module doesn't implement the - //! Parameters() or Model() function. - template - typename std::enable_if< - !HasParametersCheck::value && - !HasModelCheck::value, size_t>::type - LayerSize(T* layer, P&& input) const; - - //! Update the parameters if the module implements the Model() function. - template - typename std::enable_if< - !HasParametersCheck::value && - HasModelCheck::value, size_t>::type - LayerSize(T* layer, P&& input) const; - - //! Update the parameters if the module implements the Parameters() function. - template - typename std::enable_if< - HasParametersCheck::value && - !HasModelCheck::value, size_t>::type - LayerSize(T* layer, P&& input) const; - - //! Update the parameters if the module implements the Model() and - //! Parameters() function. - template - typename std::enable_if< - HasParametersCheck::value && - HasModelCheck::value, size_t>::type - LayerSize(T* layer, P&& input) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "weight_set_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_set_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_set_visitor_impl.hpp deleted file mode 100644 index c26cd3148..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_set_visitor_impl.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @file weight_set_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the Weight() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_WEIGHT_SET_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_WEIGHT_SET_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "weight_set_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! WeightSetVisitor visitor class. -inline WeightSetVisitor::WeightSetVisitor(arma::mat&& weight, - const size_t offset) : - weight(std::move(weight)), - offset(offset) -{ - /* Nothing to do here. */ -} - -template -inline size_t WeightSetVisitor::operator()(LayerType* layer) const -{ - return LayerSize(layer, std::move(layer->OutputParameter())); -} - -template -inline typename std::enable_if< - !HasParametersCheck::value && - !HasModelCheck::value, size_t>::type -WeightSetVisitor::LayerSize(T* /* layer */, P&& /*output */) const -{ - return 0; -} - -template -inline typename std::enable_if< - !HasParametersCheck::value && - HasModelCheck::value, size_t>::type -WeightSetVisitor::LayerSize(T* layer, P&& /*output */) const -{ - size_t modelOffset = 0; - for (size_t i = 0; i < layer->Model().size(); ++i) - { - modelOffset += boost::apply_visitor(WeightSetVisitor( - std::move(weight), modelOffset + offset), layer->Model()[i]); - } - - return modelOffset; -} - -template -inline typename std::enable_if< - HasParametersCheck::value && - !HasModelCheck::value, size_t>::type -WeightSetVisitor::LayerSize(T* layer, P&& /* output */) const -{ - layer->Parameters() = arma::mat(weight.memptr() + offset, - layer->Parameters().n_rows, layer->Parameters().n_cols, false, false); - - return layer->Parameters().n_elem; -} - -template -inline typename std::enable_if< - HasParametersCheck::value && - HasModelCheck::value, size_t>::type -WeightSetVisitor::LayerSize(T* layer, P&& /* output */) const -{ - layer->Parameters() = arma::mat(weight.memptr() + offset, - layer->Parameters().n_rows, layer->Parameters().n_cols, false, false); - - size_t modelOffset = layer->Parameters().n_elem; - for (size_t i = 0; i < layer->Model().size(); ++i) - { - modelOffset += boost::apply_visitor(WeightSetVisitor( - std::move(weight), modelOffset + offset), layer->Model()[i]); - } - - return modelOffset; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_size_visitor.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_size_visitor.hpp deleted file mode 100644 index e6501095e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_size_visitor.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file weight_size_visitor.hpp - * @author Marcus Edel - * - * This file provides an abstraction for the WeightSize() function for - * different layers and automatically directs any parameter to the right layer - * type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_WEIGHT_SIZE_VISITOR_HPP -#define MLPACK_METHODS_ANN_VISITOR_WEIGHT_SIZE_VISITOR_HPP - -#include - -#include - -namespace mlpack { -namespace ann { - -/** - * WeightSizeVisitor returns the number of weights of the given module. - */ -class WeightSizeVisitor : public boost::static_visitor -{ - public: - //! Return the number of weights. - template - size_t operator()(LayerType* layer) const; - - private: - //! If the module doesn't implement the Parameters() or Model() function - //! return 0. - template - typename std::enable_if< - !HasParametersCheck::value && - !HasModelCheck::value, size_t>::type - LayerSize(T* layer, P& output) const; - - //! Return the number of parameters if the module implements the Model() - //! function. - template - typename std::enable_if< - !HasParametersCheck::value && - HasModelCheck::value, size_t>::type - LayerSize(T* layer, P& output) const; - - //! Return the number of parameters if the module implements the Parameters() - //! function. - template - typename std::enable_if< - HasParametersCheck::value && - !HasModelCheck::value, size_t>::type - LayerSize(T* layer, P& output) const; - - //! Return the accumulated number of parameters if the module implements the - //! Parameters() and Model() function. - template - typename std::enable_if< - HasParametersCheck::value && - HasModelCheck::value, size_t>::type - LayerSize(T* layer, P& output) const; -}; - -} // namespace ann -} // namespace mlpack - -// Include implementation. -#include "weight_size_visitor_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_size_visitor_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_size_visitor_impl.hpp deleted file mode 100644 index 38f5d7e4a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/ann/visitor/weight_size_visitor_impl.hpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file weight_size_visitor_impl.hpp - * @author Marcus Edel - * - * Implementation of the WeightSize() function layer abstraction. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_ANN_VISITOR_WEIGHT_SIZE_VISITOR_IMPL_HPP -#define MLPACK_METHODS_ANN_VISITOR_WEIGHT_SIZE_VISITOR_IMPL_HPP - -// In case it hasn't been included yet. -#include "weight_size_visitor.hpp" - -namespace mlpack { -namespace ann { - -//! WeightSizeVisitor visitor class. -template -inline size_t WeightSizeVisitor::operator()(LayerType* layer) const -{ - return LayerSize(layer, layer->OutputParameter()); -} - -template -inline typename std::enable_if< - !HasParametersCheck::value && - !HasModelCheck::value, size_t>::type -WeightSizeVisitor::LayerSize(T* /* layer */, P& /* output */) const -{ - return 0; -} - -template -inline typename std::enable_if< - !HasParametersCheck::value && - HasModelCheck::value, size_t>::type -WeightSizeVisitor::LayerSize(T* layer, P& /* output */) const -{ - size_t weights = 0; - for (size_t i = 0; i < layer->Model().size(); ++i) - { - weights += boost::apply_visitor(WeightSizeVisitor(), layer->Model()[i]); - } - - return weights; -} - -template -inline typename std::enable_if< - HasParametersCheck::value && - !HasModelCheck::value, size_t>::type -WeightSizeVisitor::LayerSize(T* layer, P& /* output */) const -{ - return layer->Parameters().n_elem; -} - -template -inline typename std::enable_if< - HasParametersCheck::value && - HasModelCheck::value, size_t>::type -WeightSizeVisitor::LayerSize(T* layer, P& /* output */) const -{ - size_t weights = layer->Parameters().n_elem; - for (size_t i = 0; i < layer->Model().size(); ++i) - { - weights += boost::apply_visitor(WeightSizeVisitor(), layer->Model()[i]); - } - - return weights; -} - -} // namespace ann -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/approx_kfn/drusilla_select.hpp b/src/sdk/mlpack/include/mlpack/methods/approx_kfn/drusilla_select.hpp deleted file mode 100644 index b8616cb90..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/approx_kfn/drusilla_select.hpp +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @file drusilla_select.hpp - * @author Ryan Curtin - * - * An implementation of the approximate furthest neighbor algorithm specified in - * the following paper: - * - * @code - * @incollection{curtin2016fast, - * title={Fast approximate furthest neighbors with data-dependent candidate - * selection}, - * author={Curtin, R.R., and Gardner, A.B.}, - * booktitle={Similarity Search and Applications}, - * pages={221--235}, - * year={2016}, - * publisher={Springer} - * } - * @endcode - * - * This algorithm, called DrusillaSelect, constructs a candidate set of points - * to query to find an approximate furthest neighbor. The strange name is a - * result of the algorithm being named after a cat. The cat in question may be - * viewed at http://www.ratml.org/misc_img/drusilla_fence.png. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_APPROX_KFN_DRUSILLA_SELECT_HPP -#define MLPACK_METHODS_APPROX_KFN_DRUSILLA_SELECT_HPP - -#include - -namespace mlpack { -namespace neighbor { - -template -class DrusillaSelect -{ - public: - /** - * Construct the DrusillaSelect object with the given reference set (this is - * the set that will be searched). The resulting set of candidate points that - * will be searched at query time will have size l*m. - * - * @param referenceSet Set of reference data. - * @param l Number of projections. - * @param m Number of elements to store for each projection. - */ - DrusillaSelect(const MatType& referenceSet, - const size_t l, - const size_t m); - - /** - * Construct the DrusillaSelect object with no given reference set. Be sure - * to call Train() before calling Search()! - * - * @param l Number of projections. - * @param m Number of elements to store for each projection. - */ - DrusillaSelect(const size_t l, const size_t m); - - /** - * Build the set of candidate points on the given reference set. If l and m - * are left unspecified, then the values set in the constructor will be used - * instead. - * - * @param referenceSet Set to extract candidate points from. - * @param l Number of projections. - * @param m Number of elements to store for each projection. - */ - void Train(const MatType& referenceSet, - const size_t l = 0, - const size_t m = 0); - - /** - * Search for the k furthest neighbors of the given query set. (The query set - * can contain just one point: that is okay.) The results will be stored in - * the given neighbors and distances matrices, in the same format as the - * NeighborSearch and LSHSearch classes. That is, each column in the - * neighbors and distances matrices will refer to a single query point, and - * the k'th row in that column will refer to the k'th candidate neighbor or - * distance for that query point. - * - * @param querySet Set of query points to search. - * @param k Number of furthest neighbors to search for. - * @param neighbors Matrix to store resulting neighbors in. - * @param distances Matrix to store resulting distances in. - */ - void Search(const MatType& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - /** - * Serialize the model. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - //! Access the candidate set. - const MatType& CandidateSet() const { return candidateSet; } - //! Modify the candidate set. Be careful! - MatType& CandidateSet() { return candidateSet; } - - //! Access the indices of points in the candidate set. - const arma::Col& CandidateIndices() const { return candidateIndices; } - //! Modify the indices of points in the candidate set. Be careful! - arma::Col& CandidateIndices() { return candidateIndices; } - - private: - //! The reference set. - MatType candidateSet; - //! Indices of each point in the reference set. - arma::Col candidateIndices; - - //! The number of projections. - size_t l; - //! The number of points in each projection. - size_t m; -}; - -} // namespace neighbor -} // namespace mlpack - -// Include implementation. -#include "drusilla_select_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/approx_kfn/drusilla_select_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/approx_kfn/drusilla_select_impl.hpp deleted file mode 100644 index 4b02aaa71..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/approx_kfn/drusilla_select_impl.hpp +++ /dev/null @@ -1,216 +0,0 @@ -/** - * @file drusilla_select_impl.hpp - * @author Ryan Curtin - * - * Implementation of DrusillaSelect class methods. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_APPROX_KFN_DRUSILLA_SELECT_IMPL_HPP -#define MLPACK_METHODS_APPROX_KFN_DRUSILLA_SELECT_IMPL_HPP - -// In case it hasn't been included yet. -#include "drusilla_select.hpp" - -#include -#include -#include -#include -#include - -namespace mlpack { -namespace neighbor { - -// Constructor. -template -DrusillaSelect::DrusillaSelect(const MatType& referenceSet, - const size_t l, - const size_t m) : - candidateSet(referenceSet.n_cols, l * m), - candidateIndices(l * m), - l(l), - m(m) -{ - if (l == 0) - throw std::invalid_argument("DrusillaSelect::DrusillaSelect(): invalid " - "value of l; must be greater than 0!"); - else if (m == 0) - throw std::invalid_argument("DrusillaSelect::DrusillaSelect(): invalid " - "value of m; must be greater than 0!"); - - Train(referenceSet, l, m); -} - -// Constructor with no training. -template -DrusillaSelect::DrusillaSelect(const size_t l, const size_t m) : - candidateSet(0, l * m), - candidateIndices(l * m), - l(l), - m(m) -{ - if (l == 0) - throw std::invalid_argument("DrusillaSelect::DrusillaSelect(): invalid " - "value of l; must be greater than 0!"); - else if (m == 0) - throw std::invalid_argument("DrusillaSelect::DrusillaSelect(): invalid " - "value of m; must be greater than 0!"); -} - -// Train the model. -template -void DrusillaSelect::Train( - const MatType& referenceSet, - const size_t lIn, - const size_t mIn) -{ - // Did the user specify a new size? If so, use it. - if (lIn > 0) - l = lIn; - if (mIn > 0) - m = mIn; - - if ((l * m) > referenceSet.n_cols) - throw std::invalid_argument("DrusillaSelect::Train(): l and m are too " - "large! Choose smaller values. l*m must be smaller than the number " - "of points in the dataset."); - - candidateSet.set_size(referenceSet.n_rows, l * m); - candidateIndices.set_size(l * m); - - arma::vec dataMean(arma::mean(referenceSet, 1)); - arma::vec norms(referenceSet.n_cols); - - MatType refCopy(referenceSet.n_rows, referenceSet.n_cols); - for (size_t i = 0; i < refCopy.n_cols; ++i) - { - refCopy.col(i) = referenceSet.col(i) - dataMean; - norms[i] = arma::norm(refCopy.col(i)); - } - - // Find the top m points for each of the l projections... - for (size_t i = 0; i < l; ++i) - { - // Pick best index. - arma::uword maxIndex = 0; - norms.max(maxIndex); - - arma::vec line(refCopy.col(maxIndex) / arma::norm(refCopy.col(maxIndex))); - - // Calculate distortion and offset and make scores. - std::vector closeAngle(referenceSet.n_cols, false); - arma::vec sums(referenceSet.n_cols); - for (size_t j = 0; j < referenceSet.n_cols; ++j) - { - if (norms[j] > 0.0) - { - const double offset = arma::dot(refCopy.col(j), line); - const double distortion = arma::norm(refCopy.col(j) - offset * line); - sums[j] = std::abs(offset) - std::abs(distortion); - closeAngle[j] = - (std::atan(distortion / std::abs(offset)) < (M_PI / 8.0)); - } - else - { - sums[j] = norms[j]; - } - } - - // Find the top m elements using a priority queue. - typedef std::pair Candidate; - struct CandidateCmp - { - bool operator()(const Candidate& c1, const Candidate& c2) - { - return c2.first < c1.first; - } - }; - - std::vector clist( - m, std::make_pair(double(-DBL_MAX), size_t(-1))); - std::priority_queue, CandidateCmp> - pq(CandidateCmp(), std::move(clist)); - - for (size_t j = 0; j < sums.n_elem; ++j) - { - Candidate c = std::make_pair(sums[j], j); - if (CandidateCmp()(c, pq.top())) - { - pq.pop(); - pq.push(c); - } - } - - // Take the top m elements for this table. - for (size_t j = 0; j < m; ++j) - { - const size_t index = pq.top().second; - pq.pop(); - candidateSet.col(i * m + j) = referenceSet.col(index); - candidateIndices[i * m + j] = index; - - // Mark the norm as -1 so we don't see this point again. - norms[index] = -1.0; - } - - // Calculate angles from the current projection. Anything close enough, - // mark the norm as 0. - for (size_t j = 0; j < norms.n_elem; ++j) - if (norms[j] > 0.0 && closeAngle[j]) - norms[j] = 0.0; - } -} - -// Search. -template -void DrusillaSelect::Search(const MatType& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - if (candidateSet.n_cols == 0) - throw std::runtime_error("DrusillaSelect::Search(): candidate set not " - "initialized! Call Train() first."); - - if (k > (l * m)) - throw std::invalid_argument("DrusillaSelect::Search(): requested k is " - "greater than number of points in candidate set! Increase l or m."); - - // We'll use the NeighborSearchRules class to perform our brute-force search. - // Note that we aren't using trees for our search, so we can use 'int' as a - // TreeType. - metric::EuclideanDistance metric; - NeighborSearchRules> - rules(candidateSet, querySet, k, metric, 0, false); - - for (size_t q = 0; q < querySet.n_cols; ++q) - for (size_t r = 0; r < candidateSet.n_cols; ++r) - rules.BaseCase(q, r); - - rules.GetResults(neighbors, distances); - - // Map the neighbors back to their original indices in the reference set. - for (size_t i = 0; i < neighbors.n_elem; ++i) - neighbors[i] = candidateIndices[neighbors[i]]; -} - -//! Serialize the model. -template -template -void DrusillaSelect::serialize(Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(candidateSet); - ar & BOOST_SERIALIZATION_NVP(candidateIndices); - ar & BOOST_SERIALIZATION_NVP(l); - ar & BOOST_SERIALIZATION_NVP(m); -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/approx_kfn/qdafn.hpp b/src/sdk/mlpack/include/mlpack/methods/approx_kfn/qdafn.hpp deleted file mode 100644 index d6151cdc5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/approx_kfn/qdafn.hpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @file qdafn.hpp - * @author Ryan Curtin - * - * An implementation of the query-dependent approximate furthest neighbor - * algorithm specified in the following paper: - * - * @code - * @incollection{pagh2015approximate, - * title={Approximate furthest neighbor in high dimensions}, - * author={Pagh, R. and Silvestri, F. and Sivertsen, J. and Skala, M.}, - * booktitle={Similarity Search and Applications}, - * pages={3--14}, - * year={2015}, - * publisher={Springer} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_APPROX_KFN_QDAFN_HPP -#define MLPACK_METHODS_APPROX_KFN_QDAFN_HPP - -#include -#include - -namespace mlpack { -namespace neighbor { - -template -class QDAFN -{ - public: - /** - * Construct the QDAFN object but do not train it. Be sure to call Train() - * before calling Search(). - * - * @param l Number of projections. - * @param m Number of elements to store for each projection. - */ - QDAFN(const size_t l, const size_t m); - - /** - * Construct the QDAFN object with the given reference set (this is the set - * that will be searched). - * - * @param referenceSet Set of reference data. - * @param l Number of projections. - * @param m Number of elements to store for each projection. - */ - QDAFN(const MatType& referenceSet, - const size_t l, - const size_t m); - - /** - * Train the QDAFN model on the given reference set, optionally setting new - * parameters for the number of projections/tables (l) and the number of - * elements stored for each projection/table (m). - * - * @param referenceSet Reference set to train on. - * @param l Number of projections. - * @param m Number of elements to store for each projection. - */ - void Train(const MatType& referenceSet, - const size_t l = 0, - const size_t m = 0); - - /** - * Search for the k furthest neighbors of the given query set. (The query set - * can contain just one point, that is okay.) The results will be stored in - * the given neighbors and distances matrices, in the same format as the - * mlpack NeighborSearch and LSHSearch classes. - */ - void Search(const MatType& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - //! Get the number of projections. - size_t NumProjections() const { return candidateSet.size(); } - - //! Get the candidate set for the given projection table. - const MatType& CandidateSet(const size_t t) const { return candidateSet[t]; } - //! Modify the candidate set for the given projection table. Careful! - MatType& CandidateSet(const size_t t) { return candidateSet[t]; } - - private: - //! The number of projections. - size_t l; - //! The number of elements to store for each projection. - size_t m; - //! The random lines we are projecting onto. Has l columns. - arma::mat lines; - //! Projections of each point onto each random line. - arma::mat projections; - - //! Indices of the points for each S. - arma::Mat sIndices; - //! Values of a_i * x for each point in S. - arma::mat sValues; - - // Candidate sets; one element in the vector for each table. - std::vector candidateSet; -}; - -} // namespace neighbor -} // namespace mlpack - -// Include implementation. -#include "qdafn_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/approx_kfn/qdafn_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/approx_kfn/qdafn_impl.hpp deleted file mode 100644 index 333054e6a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/approx_kfn/qdafn_impl.hpp +++ /dev/null @@ -1,190 +0,0 @@ -/** - * @file qdafn_impl.hpp - * @author Ryan Curtin - * - * Implementation of QDAFN class methods. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_APPROX_KFN_QDAFN_IMPL_HPP -#define MLPACK_METHODS_APPROX_KFN_QDAFN_IMPL_HPP - -// In case it hasn't been included yet. -#include "qdafn.hpp" - -#include -#include - -namespace mlpack { -namespace neighbor { - -// Non-training constructor. -template -QDAFN::QDAFN(const size_t l, const size_t m) : l(l), m(m) -{ - if (l == 0) - throw std::invalid_argument("QDAFN::QDAFN(): l must be greater than 0!"); - if (m == 0) - throw std::invalid_argument("QDAFN::QDAFN(): m must be greater than 0!"); -} - -// Constructor. -template -QDAFN::QDAFN(const MatType& referenceSet, - const size_t l, - const size_t m) : - l(l), - m(m) -{ - if (l == 0) - throw std::invalid_argument("QDAFN::QDAFN(): l must be greater than 0!"); - if (m == 0) - throw std::invalid_argument("QDAFN::QDAFN(): m must be greater than 0!"); - - Train(referenceSet); -} - -// Train the object. -template -void QDAFN::Train(const MatType& referenceSet, - const size_t lIn, - const size_t mIn) -{ - if (lIn != 0) - l = lIn; - if (mIn != 0) - m = mIn; - - // Build tables. This is done by drawing random points from a Gaussian - // distribution as the vectors we project onto. The Gaussian should have zero - // mean and unit variance. - mlpack::distribution::GaussianDistribution gd(referenceSet.n_rows); - lines.set_size(referenceSet.n_rows, l); - for (size_t i = 0; i < l; ++i) - lines.col(i) = gd.Random(); - - // Now, project each of the reference points onto each line, and collect the - // top m elements. - projections = referenceSet.t() * lines; - - // Loop over each projection and find the top m elements. - sIndices.set_size(m, l); - sValues.set_size(m, l); - candidateSet.resize(l); - for (size_t i = 0; i < l; ++i) - { - candidateSet[i].set_size(referenceSet.n_rows, m); - arma::uvec sortedIndices = arma::sort_index(projections.col(i), "descend"); - - // Grab the top m elements. - for (size_t j = 0; j < m; ++j) - { - sIndices(j, i) = sortedIndices[j]; - sValues(j, i) = projections(sortedIndices[j], i); - candidateSet[i].col(j) = referenceSet.col(sortedIndices[j]); - } - } -} - -// Search. -template -void QDAFN::Search(const MatType& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - if (k > m) - throw std::invalid_argument("QDAFN::Search(): requested k is greater than " - "value of m!"); - - neighbors.set_size(k, querySet.n_cols); - neighbors.fill(size_t() - 1); - distances.zeros(k, querySet.n_cols); - - // Search for each point. - for (size_t q = 0; q < querySet.n_cols; ++q) - { - // Initialize a priority queue. - // The size_t represents the index of the table, and the double represents - // the value of l_i * S_i - l_i * query (see line 6 of Algorithm 1). - std::priority_queue> queue; - for (size_t i = 0; i < l; ++i) - { - const double val = sValues(0, i) - arma::dot(querySet.col(q), - lines.col(i)); - queue.push(std::make_pair(val, i)); - } - - // To track where we are in each S table, we keep the next index to look at - // in each table (they start at 0). - arma::Col tableLocations = arma::zeros>(l); - - // Now that the queue is initialized, iterate over m elements. - std::vector> v(k, std::make_pair(-1.0, - size_t(-1))); - std::priority_queue> - resultsQueue(std::less>(), std::move(v)); - for (size_t i = 0; i < m; ++i) - { - std::pair p = queue.top(); - queue.pop(); - - // Get index of reference point to look at. - const size_t tableIndex = tableLocations[p.second]; - - // Calculate distance from query point. - const double dist = mlpack::metric::EuclideanDistance::Evaluate( - querySet.col(q), candidateSet[p.second].col(tableIndex)); - - // Is this neighbor good enough to insert into the results? - if (dist > resultsQueue.top().first) - { - resultsQueue.pop(); - resultsQueue.push(std::make_pair(dist, sIndices(tableIndex, p.second))); - } - - // Now (line 14) get the next element and insert into the queue. Do this - // by adjusting the previous value. Don't insert anything if we are at - // the end of the search, though. - if (i < m - 1) - { - tableLocations[p.second]++; - const double val = p.first - sValues(tableIndex, p.second) + - sValues(tableIndex + 1, p.second); - - queue.push(std::make_pair(val, p.second)); - } - } - - // Extract the results. - for (size_t j = 1; j <= k; ++j) - { - neighbors(k - j, q) = resultsQueue.top().second; - distances(k - j, q) = resultsQueue.top().first; - resultsQueue.pop(); - } - } -} - -template -template -void QDAFN::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(l); - ar & BOOST_SERIALIZATION_NVP(m); - ar & BOOST_SERIALIZATION_NVP(lines); - ar & BOOST_SERIALIZATION_NVP(projections); - ar & BOOST_SERIALIZATION_NVP(sIndices); - ar & BOOST_SERIALIZATION_NVP(sValues); - if (Archive::is_loading::value) - candidateSet.clear(); - ar & BOOST_SERIALIZATION_NVP(candidateSet); -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/block_krylov_svd/randomized_block_krylov_svd.hpp b/src/sdk/mlpack/include/mlpack/methods/block_krylov_svd/randomized_block_krylov_svd.hpp deleted file mode 100644 index 06ef8b4c2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/block_krylov_svd/randomized_block_krylov_svd.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @file randomized_block_krylov_svd.hpp - * @author Marcus Edel - * - * An implementation of the randomized block krylov SVD method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_BLOCK_KRYLOV_SVD_RANDOMIZED_BLOCK_KRYLOV_SVD_HPP -#define MLPACK_METHODS_BLOCK_KRYLOV_SVD_RANDOMIZED_BLOCK_KRYLOV_SVD_HPP - -#include - -namespace mlpack { -namespace svd { - -/** - * Randomized block krylov SVD is a matrix factorization that is based on - * randomized matrix approximation techniques, developed in in - * "Randomized Block Krylov Methods for Stronger and Faster Approximate - * Singular Value Decomposition". - * - * For more information, see the following. - * - * @code - * @inproceedings{Musco2015, - * author = {Cameron Musco and Christopher Musco}, - * title = {Randomized Block Krylov Methods for Stronger and Faster - * Approximate Singular Value Decomposition}, - * booktitle = {Advances in Neural Information Processing Systems 28: Annual - * Conference on Neural Information Processing Systems 2015, - * December 7-12, 2015, Montreal, Quebec, Canada}, - * pages = {1396--1404}, - * year = {2015}, - * } - * @endcode - * - * An example of how to use the interface is shown below: - * - * @code - * arma::mat data; // Rating data in the form of coordinate list. - * - * const size_t rank = 20; // Rank used for the decomposition. - * - * // Make a RandomizedBlockKrylovSVD object. - * RandomizedBlockKrylovSVD bSVD(); - * - * arma::mat u, s, v; - * - * // Use the Apply() method to get a factorization. - * bSVD.Apply(data, u, s, v, rank); - * @endcode - */ -class RandomizedBlockKrylovSVD -{ - public: - /** - * Create object for the randomized block krylov SVD method. - * - * @param data Data matrix. - * @param u First unitary matrix. - * @param v Second unitary matrix. - * @param s Diagonal matrix of singular values. - * @param maxIterations Number of iterations for the power method - * (Default: 2). - * @param rank Rank of the approximation (Default: number of rows.) - * @param blockSize The block size, must be >= rank (Default: rank + 10). - */ - RandomizedBlockKrylovSVD(const arma::mat& data, - arma::mat& u, - arma::vec& s, - arma::mat& v, - const size_t maxIterations = 2, - const size_t rank = 0, - const size_t blockSize = 0); - - /** - * Create object for the randomized block krylov SVD method. - * - * @param maxIterations Number of iterations for the power method - * (Default: 2). - * @param blockSize The block size, must be >= rank (Default: rank + 10). - */ - RandomizedBlockKrylovSVD(const size_t maxIterations = 2, - const size_t blockSize = 0); - - /** - * Apply Principal Component Analysis to the provided data set using the - * randomized block krylov SVD. - * - * @param data Data matrix. - * @param u First unitary matrix. - * @param v Second unitary matrix. - * @param s Diagonal matrix of singular values. - * @param rank Rank of the approximation. - */ - void Apply(const arma::mat& data, - arma::mat& u, - arma::vec& s, - arma::mat& v, - const size_t rank); - - //! Get the number of iterations for the power method. - size_t MaxIterations() const { return maxIterations; } - //! Modify the number of iterations for the power method. - size_t& MaxIterations() { return maxIterations; } - - //! Get the block size. - size_t BlockSize() const { return blockSize; } - //! Modify the block size. - size_t& BlockSize() { return blockSize; } - - private: - //! Locally stored number of iterations for the power method. - size_t maxIterations; - - //! The block size value. - size_t blockSize; -}; - -} // namespace svd -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/cf.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/cf.hpp deleted file mode 100644 index 6f0418075..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/cf.hpp +++ /dev/null @@ -1,256 +0,0 @@ -/** - * @file cf.hpp - * @author Mudit Raj Gupta - * @author Sumedh Ghaisas - * - * Collaborative filtering. - * - * Defines the CFType class to perform collaborative filtering on the specified data - * set using alternating least squares (ALS). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_CF_CF_HPP -#define MLPACK_METHODS_CF_CF_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace mlpack { -namespace cf /** Collaborative filtering. **/ { -/** - * This class implements Collaborative Filtering (CF). This implementation - * presently supports Alternating Least Squares (ALS) for collaborative - * filtering. - * - * A simple example of how to run Collaborative Filtering is shown below. - * - * @code - * extern arma::mat data; // (user, item, rating) table - * extern arma::Col users; // users seeking recommendations - * arma::Mat recommendations; // Recommendations - * - * CFType cf(data); // Default options. - * - * // Generate 10 recommendations for all users. - * cf.GetRecommendations(10, recommendations); - * - * // Generate 10 recommendations for specified users. - * cf.GetRecommendations(10, recommendations, users); - * - * @endcode - * - * The data matrix is a (user, item, rating) table. Each column in the matrix - * should have three rows. The first represents the user; the second represents - * the item; and the third represents the rating. The user and item, while they - * are in a matrix that holds doubles, should hold integer (or size_t) values. - * The user and item indices are assumed to start at 0. - * - * @tparam DecompositionPolicy The algorithm to use to decompose - * the rating matrix (a W and H matrix). - */ -class CFType -{ - public: - /** - * Initialize the CFType object without performing any factorization. Be sure to - * call Train() before calling GetRecommendations() or any other functions! - */ - CFType(const size_t numUsersForSimilarity = 5, - const size_t rank = 0); - - /** - * Initialize the CFType object using any decomposition method, immediately - * factorizing the given data to create a model. There are parameters that can - * be set; default values are provided for each of them. If the rank is left - * unset (or is set to 0), a simple density-based heuristic will be used to - * choose a rank. - * - * The provided dataset can be a coordinate list; that is, a 3-row matrix - * where each column corresponds to a (user, item, rating) entry in the - * matrix or a sparse matrix representing (user, item) table. - * - * @param data Data matrix: dense matrix (coordinate lists) - * or sparse matrix(cleaned). - * @param decomposition Instantiated DecompositionPolicy object. - * @param numUsersForSimilarity Size of the neighborhood. - * @param rank Rank parameter for matrix factorization. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - template - CFType(const MatType& data, - DecompositionPolicy& decomposition = DecompositionPolicy(), - const size_t numUsersForSimilarity = 5, - const size_t rank = 0, - const size_t maxIterations = 1000, - const double minResidue = 1e-5, - const bool mit = false); - - /** - * Train the CFType model (i.e. factorize the input matrix) using the - * parameters that have already been set for the model (specifically, the rank - * parameter), and optionally, using the given DecompositionPolicy. - * - * @param data Input dataset; dense matrix (coordinate lists). - * @param decomposition Instantiated DecompositionPolicy object. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - template - void Train(const arma::mat& data, - DecompositionPolicy& decomposition, - const size_t maxIterations = 1000, - const double minResidue = 1e-5, - const bool mit = false); - - /** - * Train the CFType model (i.e. factorize the input matrix) using the - * parameters that have already been set for the model (specifically, the - * rank parameter), and optionally, using the given DecompositionPolicy. - * - * @param data Input dataset; sparse matrix (user item table). - * @param decomposition Instantiated DecompositionPolicy object. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - template - void Train(const arma::sp_mat& data, - DecompositionPolicy& decomposition, - const size_t maxIterations = 1000, - const double minResidue = 1e-5, - const bool mit = false); - - //! Sets number of users for calculating similarity. - void NumUsersForSimilarity(const size_t num) - { - if (num < 1) - { - Log::Warn << "CFType::NumUsersForSimilarity(): invalid value (< 1) " - "ignored." << std::endl; - return; - } - this->numUsersForSimilarity = num; - } - - //! Gets number of users for calculating similarity. - size_t NumUsersForSimilarity() const - { - return numUsersForSimilarity; - } - - //! Sets rank parameter for matrix factorization. - void Rank(const size_t rankValue) - { - this->rank = rankValue; - } - - //! Gets rank parameter for matrix factorization. - size_t Rank() const - { - return rank; - } - - //! Get the User Matrix. - const arma::mat& W() const { return w; } - //! Get the Item Matrix. - const arma::mat& H() const { return h; } - //! Get the cleaned data matrix. - const arma::sp_mat& CleanedData() const { return cleanedData; } - - /** - * Generates the given number of recommendations for all users. - * - * @param numRecs Number of Recommendations. - * @param recommendations Matrix to save recommendations into. - */ - void GetRecommendations(const size_t numRecs, - arma::Mat& recommendations); - - /** - * Generates the given number of recommendations for the specified users. - * - * @param numRecs Number of Recommendations. - * @param recommendations Matrix to save recommendations. - * @param users Users for which recommendations are to be generated. - */ - void GetRecommendations(const size_t numRecs, - arma::Mat& recommendations, - const arma::Col& users); - - //! Converts the User, Item, Value Matrix to User-Item Table. - static void CleanData(const arma::mat& data, arma::sp_mat& cleanedData); - - /** - * Predict the rating of an item by a particular user. - * - * @param user User to predict for. - * @param item Item to predict for. - */ - double Predict(const size_t user, const size_t item) const; - - /** - * Predict ratings for each user-item combination in the given coordinate list - * matrix. The matrix 'combinations' should have two rows and number of - * columns equal to the number of desired predictions. The first element of - * each column corresponds to the user index, and the second element of each - * column corresponds to the item index. The output vector 'predictions' will - * have length equal to combinations.n_cols, and predictions[i] will be equal - * to the prediction for the user/item combination in combinations.col(i). - * - * @param combinations User/item combinations to predict. - * @param predictions Predicted ratings for each user/item combination. - */ - void Predict(const arma::Mat& combinations, - arma::vec& predictions) const; - - /** - * Serialize the CFType model to the given archive. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Number of users for similarity. - size_t numUsersForSimilarity; - //! Rank used for matrix factorization. - size_t rank; - //! User matrix. - arma::mat w; - //! Item matrix. - arma::mat h; - //! Cleaned data matrix. - arma::sp_mat cleanedData; - - //! Candidate represents a possible recommendation (value, item). - typedef std::pair Candidate; - - //! Compare two candidates based on the value. - struct CandidateCmp { - bool operator()(const Candidate& c1, const Candidate& c2) - { - return c1.first > c2.first; - }; - }; -}; // class CFType - -} // namespace cf -} // namespace mlpack - -// Include implementation of templated functions. -#include "cf_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/cf_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/cf_impl.hpp deleted file mode 100644 index 36c1965a8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/cf_impl.hpp +++ /dev/null @@ -1,133 +0,0 @@ -/** - * @file cf_impl.hpp - * @author Mudit Raj Gupta - * @author Sumedh Ghaisas - * - * Collaborative Filtering. - * - * Implementation of CF class to perform Collaborative Filtering on the - * specified data set. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_CF_CF_IMPL_HPP -#define MLPACK_METHODS_CF_CF_IMPL_HPP - -// In case it hasn't been included yet. -#include "cf.hpp" - -namespace mlpack { -namespace cf { - -/** - * Construct the CF object using an instantiated decomposition policy. - */ -template -CFType::CFType(const MatType& data, - DecompositionPolicy& decomposition, - const size_t numUsersForSimilarity, - const size_t rank, - const size_t maxIterations, - const double minResidue, - const bool mit) : - numUsersForSimilarity(numUsersForSimilarity), - rank(rank) -{ - // Validate neighbourhood size. - if (numUsersForSimilarity < 1) - { - Log::Warn << "CFType::CFType(): neighbourhood size should be > 0 (" - << numUsersForSimilarity << " given). Setting value to 5.\n"; - // Set default value of 5. - this->numUsersForSimilarity = 5; - } - - Train(data, decomposition, maxIterations, minResidue, mit); -} - -// Train when data is given in dense matrix form. -template -void CFType::Train(const arma::mat& data, - DecompositionPolicy& decomposition, - const size_t maxIterations, - const double minResidue, - const bool mit) -{ - CleanData(data, cleanedData); - - // Check if the user wanted us to choose a rank for them. - if (rank == 0) - { - // This is a simple heuristic that picks a rank based on the density of the - // dataset between 5 and 105. - const double density = (cleanedData.n_nonzero * 100.0) / cleanedData.n_elem; - const size_t rankEstimate = size_t(density) + 5; - - // Set to heuristic value. - Log::Info << "No rank given for decomposition; using rank of " - << rankEstimate << " calculated by density-based heuristic." - << std::endl; - this->rank = rankEstimate; - } - - // Decompose the data matrix (which is in coordinate list form) to user and - // data matrices. - Timer::Start("cf_factorization"); - decomposition.Apply(data, cleanedData, rank, w, - h, maxIterations, minResidue, mit); - Timer::Stop("cf_factorization"); -} - -// Train when data is given as sparse matrix of user item table. -template -void CFType::Train(const arma::sp_mat& data, - DecompositionPolicy& decomposition, - const size_t maxIterations, - const double minResidue, - const bool mit) -{ - cleanedData = data; - - // Check if the user wanted us to choose a rank for them. - if (rank == 0) - { - // This is a simple heuristic that picks a rank based on the density of the - // dataset between 5 and 105. - const double density = (cleanedData.n_nonzero * 100.0) / cleanedData.n_elem; - const size_t rankEstimate = size_t(density) + 5; - - // Set to heuristic value. - Log::Info << "No rank given for decomposition; using rank of " - << rankEstimate << " calculated by density-based heuristic." - << std::endl; - this->rank = rankEstimate; - } - - // Decompose the data matrix (which is in coordinate list form) to user and - // data matrices. - Timer::Start("cf_factorization"); - decomposition.Apply(data, cleanedData, rank, w, - h, maxIterations, minResidue, mit); - Timer::Stop("cf_factorization"); -} - -//! Serialize the model. -template -void CFType::serialize(Archive& ar, const unsigned int /* version */) -{ - // This model is simple; just serialize all the members. No special handling - // required. - ar & BOOST_SERIALIZATION_NVP(numUsersForSimilarity); - ar & BOOST_SERIALIZATION_NVP(rank); - ar & BOOST_SERIALIZATION_NVP(w); - ar & BOOST_SERIALIZATION_NVP(h); - ar & BOOST_SERIALIZATION_NVP(cleanedData); -} - -} // namespace cf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/batch_svd_method.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/batch_svd_method.hpp deleted file mode 100644 index 6ccbcc156..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/batch_svd_method.hpp +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file batch_svd_method.hpp - * @author Haritha Nair - * - * Implementation of the batch SVD method for use in Collaborative Filtering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_BATCH_SVD_HPP -#define MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_BATCH_SVD_HPP - -#include -#include -#include -#include -#include - -namespace mlpack { -namespace cf { - -/** - * Implementation of the Batch SVD policy to act as a wrapper when accessing - * Batch SVD from within CFType. - */ -class BatchSVDPolicy -{ - public: - /** - * Apply Collaborative Filtering to the provided data set using the - * batch SVD method. - * - * @param data Data matrix: dense matrix (coordinate lists) - * or sparse matrix(cleaned). - * @param cleanedData item user table in form of sparse matrix. - * @param rank Rank parameter for matrix factorization. - * @param w First matrix formed after decomposition. - * @param h Second matrix formed after decomposition. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - template - void Apply(const MatType& /* data */, - const arma::sp_mat& cleanedData, - const size_t rank, - arma::mat& w, - arma::mat& h, - const size_t maxIterations, - const double minResidue, - const bool mit) - { - if (mit) - { - amf::MaxIterationTermination iter(maxIterations); - - // Do singular value decomposition using the batch SVD algorithm. - amf::AMF svdbatch(iter); - - svdbatch.Apply(cleanedData, rank, w, h); - } - else - { - amf::SimpleResidueTermination srt(minResidue, maxIterations); - - // Do singular value decomposition using the batch SVD algorithm. - amf::SVDBatchFactorizer<> svdbatch(srt); - - svdbatch.Apply(cleanedData, rank, w, h); - } - } -}; - -} // namespace cf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/nmf_method.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/nmf_method.hpp deleted file mode 100644 index 3d7a681d2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/nmf_method.hpp +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @file nmf_method.hpp - * @author Haritha Nair - * - * Implementation of the exact svd method for use in Collaborative Filtering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_NMF_METHOD_HPP -#define MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_NMF_METHOD_HPP - -#include -#include -#include -#include -#include - -namespace mlpack { -namespace cf { - -/** - * Implementation of the NMF policy to act as a wrapper when accessing - * NMF from within CFType. - */ -class NMFPolicy -{ - public: - /** - * Apply Collaborative Filtering to the provided dataset using NMF method. - * - * @param data Data matrix: dense matrix (coordinate lists) - * or sparse matrix(cleaned). - * @param cleanedData item user table in form of sparse matrix. - * @param rank Rank parameter for matrix factorization. - * @param w First matrix formed after decomposition. - * @param h Second matrix formed after decomposition. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - template - void Apply(const MatType& /* data */, - const arma::sp_mat& cleanedData, - const size_t rank, - arma::mat& w, - arma::mat& h, - const size_t maxIterations, - const double minResidue, - const bool mit) - { - if (mit) - { - amf::MaxIterationTermination iter(maxIterations); - - // Do singular value decomposition using the NMF algorithm. - amf::AMF nmf(iter); - nmf.Apply(cleanedData, rank, w, h); - } - else - { - amf::SimpleResidueTermination srt(minResidue, maxIterations); - - // Do singular value decomposition using the NMF algorithm. - amf::NMFALSFactorizer nmf(srt); - nmf.Apply(cleanedData, rank, w, h); - } - } -}; - -} // namespace cf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/randomized_svd_method.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/randomized_svd_method.hpp deleted file mode 100644 index 979d672bb..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/randomized_svd_method.hpp +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @file randomized_svd_method.hpp - * @author Haritha Nair - * - * Implementation of the randomized svd method for use in - * Collaborative Fitlering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_RANDOMIZED_SVD_METHOD_HPP -#define MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_RANDOMIZED_SVD_METHOD_HPP - -#include -#include - -namespace mlpack { -namespace cf { - -/** - * Implementation of the Randomized SVD policy to act as a wrapper when - * accessing Randomized SVD from within CFType. - */ -class RandomizedSVDPolicy -{ - public: - /** - * Use randomized SVD method to perform collaborative filtering - * - * @param iteratedPower Size of the normalized power iterations - * (Default: rank + 2). - * @param maxIterations Number of iterations for the power method - * (Default: 2). - */ - RandomizedSVDPolicy(const size_t iteratedPower = 0, - const size_t maxIterations = 2) : - iteratedPower(iteratedPower), - maxIterations(maxIterations) - { - /* Nothing to do here */ - } - - /** - * Apply Collaborative Filtering to the provided data set using the - * randomized SVD. - * - * @param data Data matrix: dense matrix (coordinate lists) - * or sparse matrix(cleaned). - * @param cleanedData item user table in form of sparse matrix. - * @param rank Rank parameter for matrix factorization. - * @param w First matrix formed after decomposition. - * @param h Second matrix formed after decomposition. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - template - void Apply(const MatType& /* data */, - const arma::sp_mat& cleanedData, - const size_t rank, - arma::mat& w, - arma::mat& h, - const size_t maxIterations, - const double /* minResidue */, - const bool /* mit */) - { - arma::vec sigma; - - // Do singular value decomposition using the randomized SVD algorithm. - svd::RandomizedSVD rsvd(iteratedPower, maxIterations); - rsvd.Apply(cleanedData, w, sigma, h, rank); - - // Sigma matrix is multiplied to w. - w = w * arma::diagmat(sigma); - - // Take transpose of the matrix h as required by CF class. - h = arma::trans(h); - } - - //! Get the size of the normalized power iterations. - size_t IteratedPower() const { return iteratedPower; } - //! Modify the size of the normalized power iterations. - size_t& IteratedPower() { return iteratedPower; } - - //! Get the number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the number of iterations. - size_t& MaxIterations() { return maxIterations; } - - private: - //! Locally stored size of the normalized power iterations. - size_t iteratedPower; - - //! Locally stored number of iterations. - size_t maxIterations; -}; - -} // namespace cf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/regularized_svd_method.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/regularized_svd_method.hpp deleted file mode 100644 index 668206098..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/regularized_svd_method.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @file regularized_svd_method.hpp - * @author Haritha Nair - * - * Implementation of the regularized svd method for use in the Collaborative - * Filtering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_REGULARIZED_SVD_METHOD_HPP -#define MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_REGULARIZED_SVD_METHOD_HPP - -#include -#include - -namespace mlpack { -namespace cf { - -/** - * Implementation of the Regularized SVD policy to act as a wrapper when - * accessing Regularized SVD from within CFType. - */ -class RegSVDPolicy -{ - public: - /** - * Use regularized SVD method to perform collaborative filtering. - * - * @param maxIterations Number of iterations for the power method - * (Default: 2). - */ - RegSVDPolicy(const size_t maxIterations = 10) : - maxIterations(maxIterations) - { - /* Nothing to do here */ - } - - /** - * Apply Collaborative Filtering to the provided data set using the - * regularized SVD. - * - * @param data Data matrix: dense matrix (coordinate lists) - * or sparse matrix(cleaned). - * @param cleanedData item user table in form of sparse matrix. - * @param rank Rank parameter for matrix factorization. - * @param w First matrix formed after decomposition. - * @param h Second matrix formed after decomposition. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - void Apply(const arma::mat& data, - const arma::sp_mat& /* cleanedData */, - const size_t rank, - arma::mat& w, - arma::mat& h, - const size_t maxIterations, - const double /* minResidue */, - const bool /* mit */) - { - // Do singular value decomposition using the regularized SVD algorithm. - svd::RegularizedSVD<> regsvd(maxIterations); - regsvd.Apply(data, rank, w, h); - } - - //! Get the number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the number of iterations. - size_t& MaxIterations() { return maxIterations; } - - private: - //! Locally stored number of iterations. - size_t maxIterations; -}; - -} // namespace cf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/svd_complete_method.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/svd_complete_method.hpp deleted file mode 100644 index d47fa0349..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/svd_complete_method.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file SVD_complete_incremental.hpp - * @author Haritha Nair - * - * Implementation of the SVD complete incremental method for use in the - * Collaborative Filtering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_SVD_COMPLETE_METHOD_HPP -#define MLPACK_METHODS_CF_DECOMPOSITION_POLICIES_SVD_COMPLETE_METHOD_HPP - -#include -#include -#include -#include -#include - -namespace mlpack { -namespace cf { - -/** - * Implementation of the SVD complete incremental policy to act as a wrapper - * when accessing SVD complete decomposition from within CFType. - */ -class SVDCompletePolicy -{ - public: - /** - * Apply Collaborative Filtering to the provided data set using the - * SVD complete incremental policy. - * - * @param data Data matrix: dense matrix (coordinate lists) - * or sparse matrix(cleaned). - * @param cleanedData item user table in form of sparse matrix. - * @param rank Rank parameter for matrix factorization. - * @param w First matrix formed after decomposition. - * @param h Second matrix formed after decomposition. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - template - void Apply(const MatType& /* data */, - const arma::sp_mat& cleanedData, - const size_t rank, - arma::mat& w, - arma::mat& h, - const size_t maxIterations, - const double minResidue, - const bool mit) - { - if (mit) - { - amf::MaxIterationTermination iter(maxIterations); - - // Do singular value decomposition using complete incremental method - // using cleaned data in form of sparse matrix. - amf::AMF> svdci(iter); - - svdci.Apply(cleanedData, rank, w, h); - } - else - { - amf::SimpleResidueTermination srt(minResidue, maxIterations); - - // Do singular value decomposition using complete incremental method - // using cleaned data in form of sparse matrix. - amf::SVDCompleteIncrementalFactorizer svdci(srt); - - svdci.Apply(cleanedData, rank, w, h); - } - } -}; - -} // namespace cf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/svd_incomplete_method.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/svd_incomplete_method.hpp deleted file mode 100644 index dbcea7ee0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/decomposition_policies/svd_incomplete_method.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @file SVD_incomplete_incremental.hpp - * @author Haritha Nair - * - * Implementation of the SVD Incomplete Incremental method for use in - * Collaborative Filtering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_SVD_INCOMPLETE_HPP -#define MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_SVD_INCOMPLETE_HPP - -#include -#include -#include -#include -#include - -namespace mlpack { -namespace cf { - -/** - * Implementation of the SVD incomplete incremental to act as a wrapper when - * accessing SVD incomplete incremental from within CFType. - */ -class SVDIncompletePolicy -{ - public: - /** - * Apply Collaborative Filtering to the provided data set using the - * SVD incomplete incremental method. - * - * @param data Data matrix: dense matrix (coordinate lists) - * or sparse matrix(cleaned). - * @param cleanedData item user table in form of sparse matrix. - * @param rank Rank parameter for matrix factorization. - * @param w First matrix formed after decomposition. - * @param h Second matrix formed after decomposition. - * @param maxIterations Maximum number of iterations. - * @param minResidue Residue required to terminate. - * @param mit Whether to terminate only when maxIterations is reached. - */ - template - void Apply(const MatType& /* data */, - const arma::sp_mat& cleanedData, - const size_t rank, - arma::mat& w, - arma::mat& h, - const size_t maxIterations, - const double minResidue, - const bool mit) - { - if (mit) - { - amf::MaxIterationTermination iter(maxIterations); - - // Do singular value decomposition using incomplete incremental method. - amf::AMF svdici(iter); - - svdici.Apply(cleanedData, rank, w, h); - } - else - { - amf::SimpleResidueTermination srt(minResidue, maxIterations); - - // Do singular value decomposition using incomplete incremental method - // using cleaned data in form of sparse matrix. - amf::SVDIncompleteIncrementalFactorizer svdici(srt); - - svdici.Apply(cleanedData, rank, w, h); - } - } -}; - -} // namespace cf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/svd_wrapper.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/svd_wrapper.hpp deleted file mode 100644 index 8f1a87db9..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/svd_wrapper.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file svd_wrapper.hpp - * @author Sumedh Ghaisas - * - * Wrapper class for SVD factorizers used for Collaborative Filtering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SVDWRAPPER_HPP -#define MLPACK_METHODS_SVDWRAPPER_HPP - -#include - -namespace mlpack -{ -namespace cf -{ - -/** - * This class acts as a dummy class for passing as template parameter. Passing - * this class as a template parameter to class SVDWrapper will force SVDWrapper - * to use Armadillo's SVD implementation. - */ -class DummyClass {}; - -/** - * This class acts as the wrapper for all SVD factorizers which are incompatible - * with CF module. Normally SVD factrorizers implement Apply method which takes - * matrix V and factorizes it into P, sigma and Q where V = P * sigma * trans(Q). - * But CF module requires factrorization to be V = W * H. This class multiplies - * P and sigma and takes the first 'r' eigenvectors out where 'r' is the rank - * of factorization. Q matrix is transposed and trimmed to support the rank - * of factorization. The Factroizer class should implement Apply which takes - * matrices P, sigma, Q and V as their parameter respectively. - */ -template -class SVDWrapper -{ - public: - // empty constructor - SVDWrapper(const Factorizer& factorizer = Factorizer()) : - factorizer(factorizer) - { - // Nothing to do here. - } - - /** - * Factorizer function which takes SVD of the given matrix and returns the - * frobenius norm of error. - * - * @param V input matrix - * @param W first unitary matrix - * @param sigma eigenvalue matrix - * @param H second unitary matrix - * - * @note V = W * sigma * arma::trans(H) - */ - double Apply(const arma::mat& V, - arma::mat& W, - arma::mat& sigma, - arma::mat& H) const; - /** - * Factorizer function which computes SVD and returns matrices as required by - * CF module. - * - * @param V input matrix - * @param W first unitary matrix - * @param H second unitary matrix - * - * @note V = W * H - */ - double Apply(const arma::mat& V, - size_t r, - arma::mat& W, - arma::mat& H) const; - - private: - //! svd factorizer - Factorizer factorizer; -}; // class SVDWrapper - -//! add simple typedefs -typedef SVDWrapper ArmaSVDFactorizer; - -//! include the implementation -#include "svd_wrapper_impl.hpp" - -} // namespace cf -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/cf/svd_wrapper_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/cf/svd_wrapper_impl.hpp deleted file mode 100644 index 2c97eb0ef..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/cf/svd_wrapper_impl.hpp +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @file svd_wrapper_impl.hpp - * @author Sumedh Ghaisas - * - * Implementation of the SVD wrapper class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -template -double mlpack::cf::SVDWrapper::Apply(const arma::mat& V, - arma::mat& W, - arma::mat& sigma, - arma::mat& H) const -{ - // get svd factorization - arma::vec E; - factorizer.Apply(W, E, H, V); - - // construct sigma matrix - sigma.zeros(V.n_rows, V.n_cols); - - for (size_t i = 0; i < sigma.n_rows && i < sigma.n_cols; i++) - sigma(i, i) = E(i, 0); - - arma::mat V_rec = W * sigma * arma::trans(H); - - // return normalized frobenius error - return arma::norm(V - V_rec, "fro") / arma::norm(V, "fro"); -} - -template<> -double mlpack::cf::SVDWrapper::Apply(const arma::mat& V, - arma::mat& W, - arma::mat& sigma, - arma::mat& H) const -{ - // get svd factorization - arma::vec E; - arma::svd(W, E, H, V); - - // construct sigma matrix - sigma.zeros(V.n_rows, V.n_cols); - - for (size_t i = 0; i < sigma.n_rows && i < sigma.n_cols; i++) - sigma(i, i) = E(i, 0); - - arma::mat V_rec = W * sigma * arma::trans(H); - - // return normalized frobenius error - return arma::norm(V - V_rec, "fro") / arma::norm(V, "fro"); -} - -template -double mlpack::cf::SVDWrapper::Apply(const arma::mat& V, - size_t r, - arma::mat& W, - arma::mat& H) const -{ - // check if the given rank is valid - if (r > V.n_rows || r > V.n_cols) - { - Log::Info << "Rank " << r << ", given for decomposition is invalid." - << std::endl; - - r = (V.n_rows > V.n_cols) ? V.n_cols : V.n_rows; - Log::Info << "Setting decomposition rank to " << r << std::endl; - } - - // get svd factorization - arma::vec sigma; - factorizer.Apply(W, sigma, H, V); - - // remove the part of W and H depending upon the value of rank - W = W.submat(0, 0, W.n_rows - 1, r - 1); - H = H.submat(0, 0, H.n_cols - 1, r - 1); - - // take only required eigenvalues - sigma = sigma.subvec(0, r - 1); - - // eigenvalue matrix is multiplied to W - // it can either be multiplied to H matrix - W = W * arma::diagmat(sigma); - - // take transpose of the matrix H as required by CF module - H = arma::trans(H); - - // reconstruct the matrix - arma::mat V_rec = W * H; - - // return the normalized frobenius norm - return arma::norm(V - V_rec, "fro") / arma::norm(V, "fro"); -} - -template<> -double mlpack::cf::SVDWrapper::Apply(const arma::mat& V, - size_t r, - arma::mat& W, - arma::mat& H) const -{ - // check if the given rank is valid - if (r > V.n_rows || r > V.n_cols) - { - Log::Info << "Rank " << r << ", given for decomposition is invalid." - << std::endl; - - r = (V.n_rows > V.n_cols) ? V.n_cols : V.n_rows; - Log::Info << "Setting decomposition rank to " << r << std::endl; - } - - // get svd factorization - arma::vec sigma; - arma::svd(W, sigma, H, V); - - // remove the part of W and H depending upon the value of rank - W = W.submat(0, 0, W.n_rows - 1, r - 1); - H = H.submat(0, 0, H.n_cols - 1, r - 1); - - // take only required eigenvalues - sigma = sigma.subvec(0, r - 1); - - // eigenvalue matrix is multiplied to W - // it can either be multiplied to H matrix - W = W * arma::diagmat(sigma); - - // take transpose of the matrix H as required by CF module - H = arma::trans(H); - - // reconstruct the matrix - arma::mat V_rec = W * H; - - // return the normalized frobenius norm - return arma::norm(V - V_rec, "fro") / arma::norm(V, "fro"); -} diff --git a/src/sdk/mlpack/include/mlpack/methods/dbscan/dbscan.hpp b/src/sdk/mlpack/include/mlpack/methods/dbscan/dbscan.hpp deleted file mode 100644 index edbe30881..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/dbscan/dbscan.hpp +++ /dev/null @@ -1,165 +0,0 @@ -/** - * @file dbscan.hpp - * @author Ryan Curtin - * - * An implementation of the DBSCAN clustering method, which is flexible enough - * to support other algorithms for finding nearest neighbors. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DBSCAN_DBSCAN_HPP -#define MLPACK_METHODS_DBSCAN_DBSCAN_HPP - -#include -#include -#include -#include "random_point_selection.hpp" -#include - -namespace mlpack { -namespace dbscan { - -/** - * DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is a - * clustering technique described in the following paper: - * - * @code - * @inproceedings{ester1996density, - * title={A density-based algorithm for discovering clusters in large spatial - * databases with noise.}, - * author={Ester, M. and Kriegel, H.-P. and Sander, J. and Xu, X.}, - * booktitle={Proceedings of the Second International Conference on Knowledge - * Discovery and Data Mining (KDD '96)}, - * pages={226--231}, - * year={1996} - * } - * @endcode - * - * The DBSCAN algorithm iteratively clusters points using range searches with a - * specified radius parameter. This implementation allows configuration of the - * range search technique used and the point selection strategy by means of - * template parameters. - * - * @tparam RangeSearchType Class to use for range searching. - * @tparam PointSelectionPolicy Strategy for selecting next point to cluster - * with. - */ -template, - typename PointSelectionPolicy = RandomPointSelection> -class DBSCAN -{ - public: - /** - * Construct the DBSCAN object with the given parameters. The batchMode - * parameter should be set to false in the case where RAM issues will be - * encountered (i.e. if the dataset is very large or if epsilon is large). - * When batchMode is false, each point will be searched iteratively, which - * could be slower but will use less memory. - * - * @param epsilon Size of range query. - * @param minPoints Minimum number of points for each cluster. - * @param batchMode If true, all points are searched in batch. - * @param rangeSearch Optional instantiated RangeSearch object. - * @param pointSelector OptionL instantiated PointSelectionPolicy object. - */ - DBSCAN(const double epsilon, - const size_t minPoints, - const bool batchMode = true, - RangeSearchType rangeSearch = RangeSearchType(), - PointSelectionPolicy pointSelector = PointSelectionPolicy()); - - /** - * Performs DBSCAN clustering on the data, returning number of clusters - * and also the centroid of each cluster. - * - * @tparam MatType Type of matrix (arma::mat or arma::sp_mat). - * @param data Dataset to cluster. - * @param centroids Matrix in which centroids are stored. - */ - template - size_t Cluster(const MatType& data, - arma::mat& centroids); - - /** - * Performs DBSCAN clustering on the data, returning number of clusters - * and also the list of cluster assignments. If assignments[i] == SIZE_MAX, - * then the point is considered "noise". - * - * @tparam MatType Type of matrix (arma::mat or arma::sp_mat). - * @param data Dataset to cluster. - * @param assignments Vector to store cluster assignments. - */ - template - size_t Cluster(const MatType& data, - arma::Row& assignments); - - /** - * Performs DBSCAN clustering on the data, returning number of clusters, - * the centroid of each cluster and also the list of cluster assignments. - * If assignments[i] == SIZE_MAX, then the point is considered "noise". - * - * @tparam MatType Type of matrix (arma::mat or arma::sp_mat). - * @param data Dataset to cluster. - * @param assignments Vector to store cluster assignments. - * @param centroids Matrix in which centroids are stored. - */ - template - size_t Cluster(const MatType& data, - arma::Row& assignments, - arma::mat& centroids); - - private: - //! Maximum distance between two points to be part of same cluster. - double epsilon; - - //! Minimum number of points to be in the epsilon-neighborhood (including - //! itself) for the point to be a core-point. - size_t minPoints; - - //! Whether or not to perform the search in batch mode. If false, single - bool batchMode; - - //! Instantiated range search policy. - RangeSearchType rangeSearch; - - //! Instantiated point selection policy. - PointSelectionPolicy pointSelector; - - /** - * Performs DBSCAN clustering on the data, returning the number of clusters and - * also the list of cluster assignments. This searches each point iteratively, - * and can save on RAM usage. It may be slower than the batch search with a - * dual-tree algorithm. - * - * @param data Dataset to cluster. - * @param assignments Assignments for each point. - * @param uf UnionFind structure that will be modified. - */ - template - void PointwiseCluster(const MatType& data, - emst::UnionFind& uf); - - /** - * Performs DBSCAN clustering on the data, returning number of clusters - * and also the list of cluster assignments. This can perform search in batch, - * so it is well suited for dual-tree or naive search. - * - * @param data Dataset to cluster. - * @param assignments Assignments for each point. - * @param uf UnionFind structure that will be modified. - */ - template - void BatchCluster(const MatType& data, - emst::UnionFind& uf); -}; - -} // namespace dbscan -} // namespace mlpack - -// Include implementation. -#include "dbscan_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/dbscan/dbscan_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/dbscan/dbscan_impl.hpp deleted file mode 100644 index a27784af1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/dbscan/dbscan_impl.hpp +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @file dbscan_impl.hpp - * @author Ryan Curtin - * - * Implementation of DBSCAN. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DBSCAN_DBSCAN_IMPL_HPP -#define MLPACK_METHODS_DBSCAN_DBSCAN_IMPL_HPP - -#include "dbscan.hpp" - -namespace mlpack { -namespace dbscan { - -/** - * Construct the DBSCAN object with the given parameters. - */ -template -DBSCAN::DBSCAN( - const double epsilon, - const size_t minPoints, - const bool batchMode, - RangeSearchType rangeSearch, - PointSelectionPolicy pointSelector) : - epsilon(epsilon), - minPoints(minPoints), - batchMode(batchMode), - rangeSearch(rangeSearch), - pointSelector(pointSelector) -{ - // Nothing to do. -} - -/** - * Performs DBSCAN clustering on the data, returning number of clusters - * and also the centroid of each cluster. - */ -template -template -size_t DBSCAN::Cluster( - const MatType& data, - arma::mat& centroids) -{ - // These assignments will be thrown away, but there is no way to avoid - // calculating them. - arma::Row assignments(data.n_cols); - assignments.fill(SIZE_MAX); - - return Cluster(data, assignments, centroids); -} - -/** - * Performs DBSCAN clustering on the data, returning number of clusters, - * the centroid of each cluster and also the list of cluster assignments. - */ -template -template -size_t DBSCAN::Cluster( - const MatType& data, - arma::Row& assignments, - arma::mat& centroids) -{ - const size_t numClusters = Cluster(data, assignments); - - // Now calculate the centroids. - centroids.zeros(data.n_rows, numClusters); - - // Calculate number of points in each cluster. - arma::Row counts; - counts.zeros(numClusters); - for (size_t i = 0; i < data.n_cols; ++i) - { - if (assignments[i] != SIZE_MAX) - { - centroids.col(assignments[i]) += data.col(i); - ++counts[assignments[i]]; - } - } - - // We should be guaranteed that the number of clusters is always greater than - // zero. - for (size_t i = 0; i < numClusters; ++i) - centroids.col(i) /= counts[i]; - - return numClusters; -} - -/** - * Performs DBSCAN clustering on the data, returning the number of clusters and - * also the list of cluster assignments. - */ -template -template -size_t DBSCAN::Cluster( - const MatType& data, - arma::Row& assignments) -{ - // Initialize the UnionFind object. - emst::UnionFind uf(data.n_cols); - rangeSearch.Train(data); - - if (batchMode) - BatchCluster(data, uf); - else - PointwiseCluster(data, uf); - - // Now set assignments. - assignments.set_size(data.n_cols); - for (size_t i = 0; i < data.n_cols; ++i) - assignments[i] = uf.Find(i); - - // Get a count of all clusters. - const size_t numClusters = arma::max(assignments) + 1; - arma::Col counts(numClusters, arma::fill::zeros); - for (size_t i = 0; i < assignments.n_elem; ++i) - counts[assignments[i]]++; - - // Now assign clusters to new indices. - size_t currentCluster = 0; - arma::Col newAssignments(numClusters); - for (size_t i = 0; i < counts.n_elem; ++i) - { - if (counts[i] >= minPoints) - newAssignments[i] = currentCluster++; - else - newAssignments[i] = SIZE_MAX; - } - - // Now reassign. - for (size_t i = 0; i < assignments.n_elem; ++i) - assignments[i] = newAssignments[assignments[i]]; - - Log::Info << currentCluster << " clusters found." << std::endl; - - return currentCluster; -} - -/** - * Performs DBSCAN clustering on the data, returning the number of clusters and - * also the list of cluster assignments. This searches each point iteratively, - * and can save on RAM usage. It may be slower than the batch search with a - * dual-tree algorithm. - */ -template -template -void DBSCAN::PointwiseCluster( - const MatType& data, - emst::UnionFind& uf) -{ - std::vector> neighbors; - std::vector> distances; - - for (size_t i = 0; i < data.n_cols; ++i) - { - if (i % 10000 == 0 && i > 0) - Log::Info << "DBSCAN clustering on point " << i << "..." << std::endl; - - // Do the range search for only this point. - rangeSearch.Search(data.col(i), math::Range(0.0, epsilon), neighbors, - distances); - - // Union to all neighbors. - for (size_t j = 0; j < neighbors[0].size(); ++j) - uf.Union(i, neighbors[0][j]); - } -} - -/** - * Performs DBSCAN clustering on the data, returning number of clusters - * and also the list of cluster assignments. This can perform search in batch, - * naive search). - */ -template -template -void DBSCAN::BatchCluster( - const MatType& data, - emst::UnionFind& uf) -{ - // For each point, find the points in epsilon-nighborhood and their distances. - std::vector> neighbors; - std::vector> distances; - Log::Info << "Performing range search." << std::endl; - rangeSearch.Train(data); - rangeSearch.Search(data, math::Range(0.0, epsilon), neighbors, distances); - Log::Info << "Range search complete." << std::endl; - - // Now loop over all points. - for (size_t i = 0; i < data.n_cols; ++i) - { - // Union to all neighbors. - for (size_t j = 0; j < neighbors[i].size(); ++j) - uf.Union(i, neighbors[i][j]); - } -} - -} // namespace dbscan -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/dbscan/random_point_selection.hpp b/src/sdk/mlpack/include/mlpack/methods/dbscan/random_point_selection.hpp deleted file mode 100644 index a55583076..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/dbscan/random_point_selection.hpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @file random_point_selection.hpp - * @author Ryan Curtin - * - * Randomly select the next point for DBSCAN. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DBSCAN_RANDOM_POINT_SELECTION_HPP -#define MLPACK_METHODS_DBSCAN_RANDOM_POINT_SELECTION_HPP - -#include -#include - -namespace mlpack { -namespace dbscan { - -/** - * This class can be used to randomly select the next point to use for DBSCAN. - */ -class RandomPointSelection -{ - public: - /** - * Select the next point to use, randomly. - * - * @param unvisited Bitset indicating which points are unvisited. - * @param data Unused data. - */ - template - static size_t Select(const boost::dynamic_bitset<>& unvisited, - const MatType& /* data */) - { - const size_t max = unvisited.count(); - const size_t index = math::RandInt(max); - - // Select the index'th unvisited point. - size_t found = 0; - for (size_t i = 0; i < unvisited.size(); ++i) - { - if (unvisited[i]) - ++found; - - if (found > index) - return i; - } - - return 0; // Not sure if it is possible to get here. - } -}; - -} // namespace dbscan -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_stump/decision_stump.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_stump/decision_stump.hpp deleted file mode 100644 index 4fcad64c3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_stump/decision_stump.hpp +++ /dev/null @@ -1,229 +0,0 @@ -/** - * @file decision_stump.hpp - * @author Udit Saxena - * - * Definition of decision stumps. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_HPP -#define MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_HPP - -#include - -namespace mlpack { -namespace decision_stump { - -/** - * This class implements a decision stump. It constructs a single level - * decision tree, i.e., a decision stump. It uses entropy to decide splitting - * ranges. - * - * The stump is parameterized by a splitting dimension (the dimension on which - * points are split), a vector of bin split values, and a vector of labels for - * each bin. Bin i is specified by the range [split[i], split[i + 1]). The - * last bin has range up to \infty (split[i + 1] does not exist in that case). - * Points that are below the first bin will take the label of the first bin. - * - * @tparam MatType Type of matrix that is being used (sparse or dense). - */ -template -class DecisionStump -{ - public: - /** - * Constructor. Train on the provided data. Generate a decision stump from - * data. - * - * @param data Input, training data. - * @param labels Labels of training data. - * @param numClasses Number of distinct classes in labels. - * @param bucketSize Minimum size of bucket when splitting. - */ - DecisionStump(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const size_t bucketSize = 10); - - /** - * Alternate constructor which copies the parameters bucketSize and classes - * from an already initiated decision stump, other. It appropriately sets the - * weight vector. - * - * @param other The other initiated Decision Stump object from - * which we copy the values. - * @param data The data on which to train this object on. - * @param labels The labels of data. - * @param weights Weight vector to use while training. For boosting purposes. - */ - DecisionStump(const DecisionStump<>& other, - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights); - - /** - * Create a decision stump without training. This stump will not be useful - * and will always return a class of 0 for anything that is to be classified, - * so it would be a prudent idea to call Train() after using this constructor. - */ - DecisionStump(); - - /** - * Train the decision stump on the given data. This completely overwrites any - * previous training data, so after training the stump may be completely - * different. - * - * @param data Dataset to train on. - * @param labels Labels for each point in the dataset. - * @param numClasses Number of classes in the dataset. - * @param bucketSize Minimum size of bucket when splitting. - */ - void Train(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const size_t bucketSize); - - /** - * Train the decision stump on the given data, with the given weights. This - * completely overwrites any previous training data, so after training the - * stump may be completely different. - * - * @param data Dataset to train on. - * @param labels Labels for each point in the dataset. - * @param weights Weights for each point in the dataset. - * @param numClasses Number of classes in the dataset. - * @param bucketSize Minimum size of bucket when splitting. - */ - void Train(const MatType& data, - const arma::Row& labels, - const arma::rowvec& weights, - const size_t numClasses, - const size_t bucketSize); - - /** - * Classification function. After training, classify test, and put the - * predicted classes in predictedLabels. - * - * @param test Testing data or data to classify. - * @param predictedLabels Vector to store the predicted classes after - * classifying test data. - */ - void Classify(const MatType& test, arma::Row& predictedLabels); - - //! Access the splitting dimension. - size_t SplitDimension() const { return splitDimension; } - //! Modify the splitting dimension (be careful!). - size_t& SplitDimension() { return splitDimension; } - - //! Access the splitting values. - const arma::vec& Split() const { return split; } - //! Modify the splitting values (be careful!). - arma::vec& Split() { return split; } - - //! Access the labels for each split bin. - const arma::Col BinLabels() const { return binLabels; } - //! Modify the labels for each split bin (be careful!). - arma::Col& BinLabels() { return binLabels; } - - //! Serialize the decision stump. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! The number of classes (we must store this for boosting). - size_t numClasses; - //! The minimum number of points in a bucket. - size_t bucketSize; - - //! Stores the value of the dimension on which to split. - size_t splitDimension; - //! Stores the splitting values after training. - arma::vec split; - //! Stores the labels for each splitting bin. - arma::Col binLabels; - - /** - * Sets up dimension as if it were splitting on it and finds entropy when - * splitting on dimension. - * - * @param dimension A row from the training data, which might be a - * candidate for the splitting dimension. - * @tparam UseWeights Whether we need to run a weighted Decision Stump. - */ - template - double SetupSplitDimension(const VecType& dimension, - const arma::Row& labels, - const arma::rowvec& weightD); - - /** - * After having decided the dimension on which to split, train on that - * dimension. - * - * @tparam dimension dimension is the dimension decided by the constructor - * on which we now train the decision stump. - */ - template - void TrainOnDim(const VecType& dimension, - const arma::Row& labels); - - /** - * After the "split" matrix has been set up, merge ranges with identical class - * labels. - */ - void MergeRanges(); - - /** - * Count the most frequently occurring element in subCols. - * - * @param subCols The vector in which to find the most frequently occurring - * element. - */ - template - double CountMostFreq(const VecType& subCols); - - /** - * Returns 1 if all the values of featureRow are not same. - * - * @param featureRow The dimension which is checked for identical values. - */ - template - int IsDistinct(const VecType& featureRow); - - /** - * Calculate the entropy of the given dimension. - * - * @param labels Corresponding labels of the dimension. - * @param classes Number of classes. - * @param weights Weights for this set of labels. - * @tparam UseWeights If true, the weights in the weight vector will be used - * (otherwise they are ignored). - */ - template - double CalculateEntropy(const VecType& labels, - const WeightVecType& weights); - - /** - * Train the decision stump on the given data and labels. - * - * @param data Dataset to train on. - * @param labels Labels for dataset. - * @param weights Weights for this set of labels. - * @tparam UseWeights If true, the weights in the weight vector will be used - * (otherwise they are ignored). - */ - template - void Train(const MatType& data, - const arma::Row& labels, - const arma::rowvec& weights); -}; - -} // namespace decision_stump -} // namespace mlpack - -#include "decision_stump_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_stump/decision_stump_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_stump/decision_stump_impl.hpp deleted file mode 100644 index ffbd94062..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_stump/decision_stump_impl.hpp +++ /dev/null @@ -1,517 +0,0 @@ -/** - * @file decision_stump_impl.hpp - * @author Udit Saxena - * - * Implementation of DecisionStump class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP -#define MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP - -// In case it hasn't been included yet. -#include "decision_stump.hpp" - -namespace mlpack { -namespace decision_stump { - -/** - * Constructor. Train on the provided data. Generate a decision stump from data. - * - * @param data Input, training data. - * @param labels Labels of data. - * @param numClasses Number of distinct classes in labels. - * @param bucketSize Minimum size of bucket when splitting. - */ -template -DecisionStump::DecisionStump(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const size_t bucketSize) : - numClasses(numClasses), - bucketSize(bucketSize) -{ - arma::rowvec weights; - Train(data, labels, weights); -} - -/** - * Empty constructor. - */ -template -DecisionStump::DecisionStump() : - numClasses(1), - bucketSize(0), - splitDimension(0), - split(1), - binLabels(1) -{ - split[0] = DBL_MAX; - binLabels[0] = 0; -} - -/** - * Train on the given data and labels. - */ -template -void DecisionStump::Train(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const size_t bucketSize) -{ - this->numClasses = numClasses; - this->bucketSize = bucketSize; - - // Pass to unweighted training function. - arma::rowvec weights; - Train(data, labels, weights); -} - -/** - * Train the decision stump on the given data, with the given weights. This - * completely overwrites any previous training data, so after training the - * stump may be completely different. - */ -template -void DecisionStump::Train(const MatType& data, - const arma::Row& labels, - const arma::rowvec& weights, - const size_t numClasses, - const size_t bucketSize) -{ - this->numClasses = numClasses; - this->bucketSize = bucketSize; - - // Pass to weighted training function. - Train(data, labels, weights); -} - -/** - * Train the decision stump on the given data and labels. - * - * @param data Dataset to train on. - * @param labels Labels for dataset. - * @param UseWeights Whether we need to run a weighted Decision Stump. - */ -template -template -void DecisionStump::Train(const MatType& data, - const arma::Row& labels, - const arma::rowvec& weights) -{ - // If classLabels are not all identical, proceed with training. - size_t bestDim = 0; - double entropy; - const double rootEntropy = CalculateEntropy(labels, weights); - - double gain, bestGain = 0.0; - for (size_t i = 0; i < data.n_rows; i++) - { - // Go through each dimension of the data. - if (IsDistinct(data.row(i))) - { - // For each dimension with non-identical values, treat it as a potential - // splitting dimension and calculate entropy if split on it. - entropy = SetupSplitDimension(data.row(i), labels, weights); - - gain = rootEntropy - entropy; - // Find the dimension with the best entropy so that the gain is - // maximized. - - // We are maximizing gain, which is what is returned from - // SetupSplitDimension(). - if (gain < bestGain) - { - bestDim = i; - bestGain = gain; - } - } - } - splitDimension = bestDim; - - // Once the splitting column/dimension has been decided, train on it. - TrainOnDim(data.row(splitDimension), labels); -} - -/** - * Classification function. After training, classify test, and put the predicted - * classes in predictedLabels. - * - * @param test Testing data or data to classify. - * @param predictedLabels Vector to store the predicted classes after - * classifying test - */ -template -void DecisionStump::Classify(const MatType& test, - arma::Row& predictedLabels) -{ - predictedLabels.set_size(test.n_cols); - for (size_t i = 0; i < test.n_cols; i++) - { - // Determine which bin the test point falls into. - // Assume first that it falls into the first bin, then proceed through the - // bins until it is known which bin it falls into. - size_t bin = 0; - const double val = test(splitDimension, i); - - while (bin < split.n_elem - 1) - { - if (val < split(bin + 1)) - break; - - ++bin; - } - - predictedLabels(i) = binLabels(bin); - } -} - -/** - * Alternate constructor which copies parameters bucketSize and numClasses - * from an already initiated decision stump, other. It appropriately - * sets the Weight vector. - * - * @param other The other initiated Decision Stump object from - * which we copy the values from. - * @param data The data on which to train this object on. - * @param D Weight vector to use while training. For boosting purposes. - * @param labels The labels of data. - * @param UseWeights Whether we need to run a weighted Decision Stump. - */ -template -DecisionStump::DecisionStump(const DecisionStump<>& other, - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights) : - numClasses(numClasses), - bucketSize(other.bucketSize) -{ - Train(data, labels, weights); -} - -/** - * Serialize the decision stump. - */ -template -template -void DecisionStump::serialize(Archive& ar, - const unsigned int /* version */) -{ - // This is straightforward; just serialize all of the members of the class. - // None need special handling. - ar & BOOST_SERIALIZATION_NVP(numClasses); - ar & BOOST_SERIALIZATION_NVP(bucketSize); - ar & BOOST_SERIALIZATION_NVP(splitDimension); - ar & BOOST_SERIALIZATION_NVP(split); - ar & BOOST_SERIALIZATION_NVP(binLabels); -} - -/** - * Sets up dimension as if it were splitting on it and finds entropy when - * splitting on dimension. - * - * @param dimension A row from the training data, which might be a candidate for - * the splitting dimension. - * @param UseWeights Whether we need to run a weighted Decision Stump. - */ -template -template -double DecisionStump::SetupSplitDimension( - const VecType& dimension, - const arma::Row& labels, - const arma::rowvec& weights) -{ - size_t i, count, begin, end; - double entropy = 0.0; - - // Store the indices of the sorted dimension to build a vector of sorted - // labels. This sort is stable. - arma::uvec sortedIndexDim = arma::stable_sort_index(dimension.t()); - - arma::Row sortedLabels(dimension.n_elem); - arma::rowvec sortedWeights(dimension.n_elem); - - for (i = 0; i < dimension.n_elem; i++) - { - sortedLabels(i) = labels(sortedIndexDim(i)); - - // Apply weights if necessary. - if (UseWeights) - sortedWeights(i) = weights(sortedIndexDim(i)); - } - - i = 0; - count = 0; - - // This splits the sorted data into buckets of size greater than or equal to - // bucketSize. - while (i < sortedLabels.n_elem) - { - count++; - if (i == sortedLabels.n_elem - 1) - { - // If we're at the end, then don't worry about the bucket size; just take - // this as the last bin. - begin = i - count + 1; - end = i; - - // Use ratioEl to calculate the ratio of elements in this split. - const double ratioEl = ((double) (end - begin + 1) / sortedLabels.n_elem); - - entropy += ratioEl * CalculateEntropy( - sortedLabels.subvec(begin, end), sortedWeights.subvec(begin, end)); - i++; - } - else if (sortedLabels(i) != sortedLabels(i + 1)) - { - // If we're not at the last element of sortedLabels, then check whether - // count is less than the current bucket size. - if (count < bucketSize) - { - // If it is, then take the minimum bucket size anyways. - // This is where the inpBucketSize comes into use. - // This makes sure there isn't a bucket for every change in labels. - begin = i - count + 1; - end = begin + bucketSize - 1; - - if (end > sortedLabels.n_elem - 1) - end = sortedLabels.n_elem - 1; - } - else - { - // If it is not, then take the bucket size as the value of count. - begin = i - count + 1; - end = i; - } - const double ratioEl = ((double) (end - begin + 1) / sortedLabels.n_elem); - - entropy += ratioEl * CalculateEntropy( - sortedLabels.subvec(begin, end), sortedWeights.subvec(begin, end)); - - i = end + 1; - count = 0; - } - else - i++; - } - return entropy; -} - -/** - * After having decided the dimension on which to split, train on that - * dimension. - * - * @param dimension Dimension is the dimension decided by the constructor on - * which we now train the decision stump. - */ -template -template -void DecisionStump::TrainOnDim(const VecType& dimension, - const arma::Row& labels) -{ - size_t i, count, begin, end; - - typename MatType::row_type sortedSplitDim = arma::sort(dimension); - arma::uvec sortedSplitIndexDim = arma::stable_sort_index(dimension.t()); - arma::Row sortedLabels(dimension.n_elem); - sortedLabels.fill(0); - - for (i = 0; i < dimension.n_elem; i++) - sortedLabels(i) = labels(sortedSplitIndexDim(i)); - - arma::rowvec subCols; - double mostFreq; - i = 0; - count = 0; - while (i < sortedLabels.n_elem) - { - count++; - if (i == sortedLabels.n_elem - 1) - { - begin = i - count + 1; - end = i; - - mostFreq = CountMostFreq(sortedLabels.cols(begin, end)); - - split.resize(split.n_elem + 1); - split(split.n_elem - 1) = sortedSplitDim(begin); - binLabels.resize(binLabels.n_elem + 1); - binLabels(binLabels.n_elem - 1) = mostFreq; - - i++; - } - else if (sortedLabels(i) != sortedLabels(i + 1)) - { - if (count < bucketSize) - { - // Test for different values of bucketSize, especially extreme cases. - begin = i - count + 1; - end = begin + bucketSize - 1; - - if (end > sortedLabels.n_elem - 1) - end = sortedLabels.n_elem - 1; - } - else - { - begin = i - count + 1; - end = i; - } - - // Find the most frequent element in subCols so as to assign a label to - // the bucket of subCols. - mostFreq = CountMostFreq(sortedLabels.cols(begin, end)); - - split.resize(split.n_elem + 1); - split(split.n_elem - 1) = sortedSplitDim(begin); - binLabels.resize(binLabels.n_elem + 1); - binLabels(binLabels.n_elem - 1) = mostFreq; - - i = end + 1; - count = 0; - } - else - i++; - } - - // Now trim the split matrix so that buckets one after the after which point - // to the same classLabel are merged as one big bucket. - MergeRanges(); -} - -/** - * After the "split" matrix has been set up, merge ranges with identical class - * labels. - */ -template -void DecisionStump::MergeRanges() -{ - for (size_t i = 1; i < split.n_rows; i++) - { - if (binLabels(i) == binLabels(i - 1)) - { - // Remove this row, as it has the same label as the previous bucket. - binLabels.shed_row(i); - split.shed_row(i); - // Go back to previous row. - i--; - } - } -} - -template -template -double DecisionStump::CountMostFreq(const VecType& subCols) -{ - // We'll create a map of elements and the number of times that each element is - // seen. - std::map countMap; - - for (size_t i = 0; i < subCols.n_elem; ++i) - { - if (countMap.count(subCols[i]) == 0) - countMap[subCols[i]] = 1; - else - ++countMap[subCols[i]]; - } - - // Now find the maximum value. - typename std::map::iterator it = countMap.begin(); - double mostFreq = it->first; - size_t mostFreqCount = it->second; - while (it != countMap.end()) - { - if (it->second >= mostFreqCount) - { - mostFreq = it->first; - mostFreqCount = it->second; - } - - ++it; - } - - return mostFreq; -} - -/** - * Returns 1 if all the values of featureRow are not the same. - * - * @param featureRow The dimension which is checked for identical values. - */ -template -template -int DecisionStump::IsDistinct(const VecType& featureRow) -{ - typename VecType::elem_type val = featureRow(0); - for (size_t i = 1; i < featureRow.n_elem; ++i) - if (val != featureRow(i)) - return 1; - return 0; -} - -/** - * Calculate entropy of dimension. - * - * @param labels Corresponding labels of the dimension. - * @param UseWeights Whether we need to run a weighted Decision Stump. - */ -template -template -double DecisionStump::CalculateEntropy( - const VecType& labels, - const WeightVecType& weights) -{ - double entropy = 0.0; - size_t j; - - arma::rowvec numElem(numClasses); - numElem.fill(0); - - // Variable to accumulate the weight in this subview_row. - double accWeight = 0.0; - // Populate numElem; they are used as helpers to calculate entropy. - - if (UseWeights) - { - for (j = 0; j < labels.n_elem; j++) - { - numElem(labels(j)) += weights(j); - accWeight += weights(j); - } - - for (j = 0; j < numClasses; j++) - { - const double p1 = ((double) numElem(j) / accWeight); - - // Instead of using log2(), which is C99 and may not exist on some - // compilers, use std::log(), then use the change-of-base formula to make - // the result correct. - entropy += (p1 == 0) ? 0 : p1 * std::log(p1); - } - } - else - { - for (j = 0; j < labels.n_elem; j++) - numElem(labels(j))++; - - for (j = 0; j < numClasses; j++) - { - const double p1 = ((double) numElem(j) / labels.n_elem); - - // Instead of using log2(), which is C99 and may not exist on some - // compilers, use std::log(), then use the change-of-base formula to make - // the result correct. - entropy += (p1 == 0) ? 0 : p1 * std::log(p1); - } - } - - return entropy / std::log(2.0); -} - -} // namespace decision_stump -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_categorical_split.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_categorical_split.hpp deleted file mode 100644 index 2823fa9bb..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_categorical_split.hpp +++ /dev/null @@ -1,98 +0,0 @@ -/** - * @file all_categorical_split.hpp - * @author Ryan Curtin - * - * This file defines a tree splitter that split a categorical feature into all - * of the possible categories. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_ALL_CATEGORICAL_SPLIT_HPP -#define MLPACK_METHODS_DECISION_TREE_ALL_CATEGORICAL_SPLIT_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * The AllCategoricalSplit is a splitting function that will split categorical - * features into many children: one child for each category. - * - * @tparam FitnessFunction Fitness function to evaluate gain with. - */ -template -class AllCategoricalSplit -{ - public: - // No extra info needed for split. - template - class AuxiliarySplitInfo { }; - - /** - * Check if we can split a node. If we can split a node in a way that - * improves on 'bestGain', then we return the improved gain. Otherwise we - * return the value 'bestGain'. If a split is made, then classProbabilities - * and aux may be modified. For this particular split type, aux will be empty - * and classProbabilities will hold one element---the number of children. - * - * @param bestGain Best gain seen so far (we'll only split if we find gain - * better than this). - * @param data The dimension of data points to check for a split in. - * @param numCategories Number of categories in the categorical data. - * @param labels Labels for each point. - * @param numClasses Number of classes in the dataset. - * @param minimumLeafSize Minimum number of points in a leaf node for - * splitting. - * @param classProbabilities Class probabilities vector, which may be filled - * with split information a successful split. - * @param aux Auxiliary split information, which may be modified on a - * successful split. - */ - template - static double SplitIfBetter( - const double bestGain, - const VecType& data, - const size_t numCategories, - const arma::Row& labels, - const size_t numClasses, - const WeightVecType& weights, - const size_t minimumLeafSize, - const double minimumGainSplit, - arma::Col& classProbabilities, - AuxiliarySplitInfo& aux); - - /** - * Return the number of children in the split. - * - * @param classProbabilities Auxiliary information for the split. - * @param aux (Unused) auxiliary information for the split. - */ - template - static size_t NumChildren(const arma::Col& classProbabilities, - const AuxiliarySplitInfo& /* aux */); - - /** - * Calculate the direction a point should percolate to. - * - * @param classProbabilities Auxiliary information for the split. - * @param aux (Unused) auxiliary information for the split. - */ - template - static size_t CalculateDirection( - const ElemType& point, - const arma::Col& classProbabilities, - const AuxiliarySplitInfo& /* aux */); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "all_categorical_split_impl.hpp" - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_categorical_split_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_categorical_split_impl.hpp deleted file mode 100644 index 115a9afb7..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_categorical_split_impl.hpp +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @file all_categorical_split_impl.hpp - * @author Ryan Curtin - * - * Implementation of the AllCategoricalSplit categorical split class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_ALL_CATEGORICAL_SPLIT_IMPL_HPP -#define MLPACK_METHODS_DECISION_TREE_ALL_CATEGORICAL_SPLIT_IMPL_HPP - -namespace mlpack { -namespace tree { - -template -template -double AllCategoricalSplit::SplitIfBetter( - const double bestGain, - const VecType& data, - const size_t numCategories, - const arma::Row& labels, - const size_t numClasses, - const WeightVecType& weights, - const size_t minimumLeafSize, - const double minimumGainSplit, - arma::Col& classProbabilities, - AuxiliarySplitInfo& /* aux */) -{ - // Count the number of elements in each potential child. - const double epsilon = 1e-7; // Tolerance for floating-point errors. - arma::Col counts(numCategories, arma::fill::zeros); - - // If we are using weighted training, learn the weights for each child too. - arma::vec childWeightSums; - double sumWeight = 0.0; - if (UseWeights) - childWeightSums.zeros(numCategories); - - for (size_t i = 0; i < data.n_elem; ++i) - { - counts[(size_t) data[i]]++; - - if (UseWeights) - { - childWeightSums[(size_t) data[i]] += weights[i]; - sumWeight += weights[i]; - } - } - - // If each child will have the minimum number of points in it, we can split. - // Otherwise we can't. - if (arma::min(counts) < minimumLeafSize) - return bestGain; - - // Calculate the gain of the split. First we have to calculate the labels - // that would be assigned to each child. - arma::uvec childPositions(numCategories, arma::fill::zeros); - std::vector> childLabels(numCategories); - std::vector> childWeights(numCategories); - for (size_t i = 0; i < numCategories; ++i) - { - // Labels and weights should have same length. - childLabels[i].zeros(counts[i]); - if (UseWeights) - childWeights[i].zeros(counts[i]); - } - - // Extract labels for each child. - for (size_t i = 0; i < data.n_elem; ++i) - { - const size_t category = (size_t) data[i]; - - if (UseWeights) - { - childLabels[category][childPositions[category]] = labels[i]; - childWeights[category][childPositions[category]++] = weights[i]; - } - else - { - childLabels[category][childPositions[category]++] = labels[i]; - } - } - - double overallGain = 0.0; - for (size_t i = 0; i < counts.n_elem; ++i) - { - // Calculate the gain of this child. - const double childPct = UseWeights ? - double(childWeightSums[i]) / sumWeight : - double(counts[i]) / double(data.n_elem); - const double childGain = FitnessFunction::template Evaluate( - childLabels[i], numClasses, childWeights[i]); - - overallGain += childPct * childGain; - } - - if (overallGain > bestGain + minimumGainSplit + epsilon) - { - // This is better, so set up the class probabilities vector and return. - classProbabilities.set_size(1); - classProbabilities[0] = numCategories; - return overallGain; - } - - // Otherwise there was no improvement. - return bestGain; -} - -template -template -size_t AllCategoricalSplit::NumChildren( - const arma::Col& classProbabilities, - const AuxiliarySplitInfo& /* aux */) -{ - return classProbabilities[0]; -} - -template -template -size_t AllCategoricalSplit::CalculateDirection( - const ElemType& point, - const arma::Col& /* classProbabilities */, - const AuxiliarySplitInfo& /* aux */) -{ - return (size_t) point; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_dimension_select.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_dimension_select.hpp deleted file mode 100644 index b41c81094..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/all_dimension_select.hpp +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @file all_dimension_select.hpp - * @author Ryan Curtin - * - * Selects all dimensions for a split. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_ALL_DIMENSION_SELECT_HPP -#define MLPACK_METHODS_DECISION_TREE_ALL_DIMENSION_SELECT_HPP - -namespace mlpack { -namespace tree { - -/** - * This dimension selection policy allows any dimension to be selected for - * splitting. - */ -class AllDimensionSelect -{ - public: - /** - * Construct the AllDimensionSelect object for the given number of dimensions. - */ - AllDimensionSelect(const size_t dimensions) : i(0), dimensions(dimensions) { } - - /** - * Get the first dimension to select from. - */ - size_t Begin() - { - i = 0; - return 0; - } - - /** - * Get the last dimension to select from. - */ - size_t End() const { return dimensions; } - - /** - * Get the next dimension. - */ - size_t Next() { return ++i; } - - private: - //! The current dimension we are looking at. - size_t i; - //! The number of dimensions to select from. - const size_t dimensions; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/best_binary_numeric_split.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/best_binary_numeric_split.hpp deleted file mode 100644 index c187e5f08..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/best_binary_numeric_split.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @file best_binary_numeric_split.hpp - * @author Ryan Curtin - * - * A tree splitter that finds the best binary numeric split. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_BEST_BINARY_NUMERIC_SPLIT_HPP -#define MLPACK_METHODS_DECISION_TREE_BEST_BINARY_NUMERIC_SPLIT_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * The BestBinaryNumericSplit is a splitting function for decision trees that - * will exhaustively search a numeric dimension for the best binary split. - * - * @tparam FitnessFunction Fitness function to use to calculate gain. - */ -template -class BestBinaryNumericSplit -{ - public: - // No extra info needed for split. - template - class AuxiliarySplitInfo { }; - - /** - * Check if we can split a node. If we can split a node in a way that - * improves on 'bestGain', then we return the improved gain. Otherwise we - * return the value 'bestGain'. If a split is made, then classProbabilities - * and aux may be modified. - * - * @param bestGain Best gain seen so far (we'll only split if we find gain - * better than this). - * @param data The dimension of data points to check for a split in. - * @param numCategories Number of categories in the categorical data. - * @param labels Labels for each point. - * @param numClasses Number of classes in the dataset. - * @param minimumLeafSize Minimum number of points in a leaf node for - * splitting. - * @param classProbabilities Class probabilities vector, which may be filled - * with split information a successful split. - * @param aux Auxiliary split information, which may be modified on a - * successful split. - */ - template - static double SplitIfBetter( - const double bestGain, - const VecType& data, - const arma::Row& labels, - const size_t numClasses, - const WeightVecType& weights, - const size_t minimumLeafSize, - const double minimumGainSplit, - arma::Col& classProbabilities, - AuxiliarySplitInfo& aux); - - /** - * Returns 2, since the binary split always has two children. - */ - template - static size_t NumChildren(const arma::Col& /* classProbabilities */, - const AuxiliarySplitInfo& /* aux */) - { - return 2; - } - - /** - * Given a point, calculate which child it should go to (left or right). - * - * @param point Point to calculate direction of. - * @param classProbabilities Auxiliary information for the split. - * @param aux (Unused) auxiliary information for the split. - */ - template - static size_t CalculateDirection( - const ElemType& point, - const arma::Col& classProbabilities, - const AuxiliarySplitInfo& /* aux */); -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "best_binary_numeric_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/best_binary_numeric_split_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/best_binary_numeric_split_impl.hpp deleted file mode 100644 index 8641f1bf0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/best_binary_numeric_split_impl.hpp +++ /dev/null @@ -1,137 +0,0 @@ -/** - * @file best_binary_numeric_split_impl.hpl - * @author Ryan Curtin - * - * Implementation of strategy that finds the best binary numeric split. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_BEST_BINARY_NUMERIC_SPLIT_IMPL_HPP -#define MLPACK_METHODS_DECISION_TREE_BEST_BINARY_NUMERIC_SPLIT_IMPL_HPP - -namespace mlpack { -namespace tree { - -template -template -double BestBinaryNumericSplit::SplitIfBetter( - const double bestGain, - const VecType& data, - const arma::Row& labels, - const size_t numClasses, - const WeightVecType& weights, - const size_t minimumLeafSize, - const double minimumGainSplit, - arma::Col& classProbabilities, - AuxiliarySplitInfo& /* aux */) -{ - // First sanity check: if we don't have enough points, we can't split. - if (data.n_elem < (minimumLeafSize * 2)) - return bestGain; - - // Next, sort the data. - arma::uvec sortedIndices = arma::sort_index(data); - arma::Row sortedLabels(labels.n_elem); - arma::rowvec sortedWeights; - for (size_t i = 0; i < sortedLabels.n_elem; ++i) - sortedLabels[i] = labels[sortedIndices[i]]; - - // Only initialize if we are using weights. - if (UseWeights) - { - sortedWeights.set_size(sortedLabels.n_elem); - // The weights must keep the same order as the labels. - for (size_t i = 0; i < sortedLabels.n_elem; ++i) - sortedWeights[i] = weights[sortedIndices[i]]; - } - - // Loop through all possible split points, choosing the best one. Also, force - // a minimum leaf size of 1 (empty children don't make sense). - double bestFoundGain = bestGain; - const size_t minimum = std::max(minimumLeafSize, (size_t) 1); - for (size_t index = minimum; index < data.n_elem - (minimum - 1); ++index) - { - // Make sure that the value has changed. - if (data[sortedIndices[index]] == data[sortedIndices[index - 1]]) - continue; - - // Calculate the gain for the left and right child. Only use weights if - // needed. - const double leftGain = UseWeights ? - FitnessFunction::template Evaluate(sortedLabels.subvec(0, - index - 1), numClasses, sortedWeights.subvec(0, index - 1)) : - FitnessFunction::template Evaluate(sortedLabels.subvec(0, - index - 1), numClasses, sortedWeights /* ignored */); - const double rightGain = UseWeights ? - FitnessFunction::template Evaluate(sortedLabels.subvec(index, - sortedLabels.n_elem - 1), numClasses, sortedWeights.subvec(index, - sortedLabels.n_elem - 1)) : - FitnessFunction::template Evaluate(sortedLabels.subvec(index, - sortedLabels.n_elem - 1), numClasses, sortedWeights /* ignored */); - - double gain; - if (UseWeights) - { - const double leftWeights = arma::accu(sortedWeights.subvec(0, index - 1)); - const double rightWeights = arma::accu(sortedWeights.subvec(index, - sortedWeights.n_elem - 1)); - const double fullWeight = leftWeights + rightWeights; - - gain = (leftWeights / fullWeight) * leftGain + - (rightWeights / fullWeight) * rightGain; - } - else - { - // Calculate the fraction of points in the left and right children. - const double leftRatio = double(index) / double(sortedLabels.n_elem); - const double rightRatio = 1.0 - leftRatio; - - // Calculate the gain at this split point. - gain = leftRatio * leftGain + rightRatio * rightGain; - } - - // Corner case: is this the best possible split? - if (gain >= 0.0) - { - // We can take a shortcut: no split will be better than this, so just take - // this one. - classProbabilities.set_size(1); - // The actual split value will be halfway between the value at index - 1 - // and index. - classProbabilities[0] = (data[sortedIndices[index - 1]] + - data[sortedIndices[index]]) / 2.0; - return gain; - } - else if (gain > bestFoundGain + minimumGainSplit) - { - // We still have a better split. - bestFoundGain = gain; - classProbabilities.set_size(1); - classProbabilities[0] = (data[sortedIndices[index - 1]] + - data[sortedIndices[index]]) / 2.0; - } - } - - return bestFoundGain; -} - -template -template -size_t BestBinaryNumericSplit::CalculateDirection( - const ElemType& point, - const arma::Col& classProbabilities, - const AuxiliarySplitInfo& /* aux */) -{ - if (point <= classProbabilities[0]) - return 0; // Go left. - else - return 1; // Go right. -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/decision_tree.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/decision_tree.hpp deleted file mode 100644 index b20b33ac2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/decision_tree.hpp +++ /dev/null @@ -1,482 +0,0 @@ -/** - * @file decision_tree.hpp - * @author Ryan Curtin - * - * A generic decision tree learner. Its behavior can be controlled via template - * arguments. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_DECISION_TREE_HPP -#define MLPACK_METHODS_DECISION_TREE_DECISION_TREE_HPP - -#include -#include "gini_gain.hpp" -#include "best_binary_numeric_split.hpp" -#include "all_categorical_split.hpp" -#include "all_dimension_select.hpp" -#include - -namespace mlpack { -namespace tree { - -/** - * This class implements a generic decision tree learner. Its behavior can be - * controlled via its template arguments. - * - * The class inherits from the auxiliary split information in order to prevent - * an empty auxiliary split information struct from taking any extra size. - */ -template class NumericSplitType = BestBinaryNumericSplit, - template class CategoricalSplitType = AllCategoricalSplit, - typename DimensionSelectionType = AllDimensionSelect, - typename ElemType = double, - bool NoRecursion = false> -class DecisionTree : - public NumericSplitType::template - AuxiliarySplitInfo, - public CategoricalSplitType::template - AuxiliarySplitInfo -{ - public: - //! Allow access to the numeric split type. - typedef NumericSplitType NumericSplit; - //! Allow access to the categorical split type. - typedef CategoricalSplitType CategoricalSplit; - //! Allow access to the dimension selection type. - typedef DimensionSelectionType DimensionSelection; - - /** - * Construct the decision tree on the given data and labels, where the data - * can be both numeric and categorical. Setting minimumLeafSize and - * minimumGainSplit too small may cause the tree to overfit, but setting them - * too large may cause it to underfit. - * - * Use std::move if data or labels are no longer needed to avoid copies. - * - * @param data Dataset to train on. - * @param datasetInfo Type information for each dimension of the dataset. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - DecisionTree(MatType data, - const data::DatasetInfo& datasetInfo, - LabelsType labels, - const size_t numClasses, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7); - - /** - * Construct the decision tree on the given data and labels, assuming that the - * data is all of the numeric type. Setting minimumLeafSize and - * minimumGainSplit too small may cause the tree to overfit, but setting them - * too large may cause it to underfit. - * - * Use std::move if data or labels are no longer needed to avoid copies. - * - * @param data Dataset to train on. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - DecisionTree(MatType data, - LabelsType labels, - const size_t numClasses, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7); - - /** - * Construct the decision tree on the given data and labels with weights, - * where the data can be both numeric and categorical. Setting minimumLeafSize - * and minimumGainSplit too small may cause the tree to overfit, but setting - * them too large may cause it to underfit. - * - * Use std::move if data, labels or weights are no longer needed to avoid - * copies. - * - * @param data Dataset to train on. - * @param datasetInfo Type information for each dimension of the dataset. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param weights The weight list of given label. - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - DecisionTree(MatType data, - const data::DatasetInfo& datasetInfo, - LabelsType labels, - const size_t numClasses, - WeightsType weights, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7, - const std::enable_if_t::type>::value>* - = 0); - - /** - * Construct the decision tree on the given data and labels with weights, - * assuming that the data is all of the numeric type. Setting minimumLeafSize - * and minimumGainSplit too small may cause the tree to overfit, but setting - * them too large may cause it to underfit. - * - * Use std::move if data, labels or weights are no longer needed to avoid - * copies. - * - * @param data Dataset to train on. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param weights The Weight list of given labels. - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - DecisionTree(MatType data, - LabelsType labels, - const size_t numClasses, - WeightsType weights, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7, - const std::enable_if_t::type>::value>* - = 0); - - - /** - * Construct a decision tree without training it. It will be a leaf node with - * equal probabilities for each class. - * - * @param numClasses Number of classes in the dataset. - */ - DecisionTree(const size_t numClasses = 1); - - /** - * Copy another tree. This may use a lot of memory---be sure that it's what - * you want to do. - * - * @param other Tree to copy. - */ - DecisionTree(const DecisionTree& other); - - /** - * Take ownership of another tree. - * - * @param other Tree to take ownership of. - */ - DecisionTree(DecisionTree&& other); - - /** - * Copy another tree. This may use a lot of memory---be sure that it's what - * you want to do. - * - * @param other Tree to copy. - */ - DecisionTree& operator=(const DecisionTree& other); - - /** - * Take ownership of another tree. - * - * @param other Tree to take ownership of. - */ - DecisionTree& operator=(DecisionTree&& other); - - /** - * Clean up memory. - */ - ~DecisionTree(); - - /** - * Train the decision tree on the given data. This will overwrite the - * existing model. The data may have numeric and categorical types, specified - * by the datasetInfo parameter. Setting minimumLeafSize and - * minimumGainSplit too small may cause the tree to overfit, but setting them - * too large may cause it to underfit. - * - * Use std::move if data or labels are no longer needed to avoid copies. - * - * @param data Dataset to train on. - * @param datasetInfo Type information for each dimension. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param weights Weights of all the labels - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - void Train(MatType data, - const data::DatasetInfo& datasetInfo, - LabelsType labels, - const size_t numClasses, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7); - - /** - * Train the decision tree on the given data, assuming that all dimensions are - * numeric. This will overwrite the given model. Setting minimumLeafSize and - * minimumGainSplit too small may cause the tree to overfit, but setting them - * too large may cause it to underfit. - * - * Use std::move if data or labels are no longer needed to avoid copies. - * - * @param data Dataset to train on. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param weights Weights of all the labels - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - void Train(MatType data, - LabelsType labels, - const size_t numClasses, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7); - - /** - * Train the decision tree on the given weighted data. This will overwrite - * the existing model. The data may have numeric and categorical types, - * specified by the datasetInfo parameter. Setting minimumLeafSize and - * minimumGainSplit too small may cause the tree to overfit, but setting them - * too large may cause it to underfit. - * - * Use std::move if data, labels or weights are no longer needed to avoid - * copies. - * - * @param data Dataset to train on. - * @param datasetInfo Type information for each dimension. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param weights Weights of all the labels - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - void Train(MatType data, - const data::DatasetInfo& datasetInfo, - LabelsType labels, - const size_t numClasses, - WeightsType weights, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7, - const std::enable_if_t::type>::value>* = 0); - - /** - * Train the decision tree on the given weighted data, assuming that all - * dimensions are numeric. This will overwrite the given model. Setting - * minimumLeafSize and minimumGainSplit too small may cause the tree to - * overfit, but setting them too large may cause it to underfit. - * - * Use std::move if data, labels or weights are no longer needed to avoid - * copies. - * - * @param data Dataset to train on. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param weights Weights of all the labels - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - void Train(MatType data, - LabelsType labels, - const size_t numClasses, - WeightsType weights, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7, - const std::enable_if_t::type>::value>* = 0); - - /** - * Classify the given point, using the entire tree. The predicted label is - * returned. - * - * @param point Point to classify. - */ - template - size_t Classify(const VecType& point) const; - - /** - * Classify the given point and also return estimates of the probability for - * each class in the given vector. - * - * @param point Point to classify. - * @param prediction This will be set to the predicted class of the point. - * @param probabilities This will be filled with class probabilities for the - * point. - */ - template - void Classify(const VecType& point, - size_t& prediction, - arma::vec& probabilities) const; - - /** - * Classify the given points, using the entire tree. The predicted labels for - * each point are stored in the given vector. - * - * @param data Set of points to classify. - * @param predictions This will be filled with predictions for each point. - */ - template - void Classify(const MatType& data, - arma::Row& predictions) const; - - /** - * Classify the given points and also return estimates of the probabilities - * for each class in the given matrix. The predicted labels for each point - * are stored in the given vector. - * - * @param data Set of points to classify. - * @param predictions This will be filled with predictions for each point. - * @param probabilities This will be filled with class probabilities for each - * point. - */ - template - void Classify(const MatType& data, - arma::Row& predictions, - arma::mat& probabilities) const; - - /** - * Serialize the tree. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - //! Get the number of children. - size_t NumChildren() const { return children.size(); } - - //! Get the child of the given index. - const DecisionTree& Child(const size_t i) const { return *children[i]; } - //! Modify the child of the given index (be careful!). - DecisionTree& Child(const size_t i) { return *children[i]; } - - /** - * Given a point and that this node is not a leaf, calculate the index of the - * child node this point would go towards. This method is primarily used by - * the Classify() function, but it can be used in a standalone sense too. - * - * @param point Point to classify. - */ - template - size_t CalculateDirection(const VecType& point) const; - - /** - * Get the number of classes in the tree. - */ - size_t NumClasses() const; - - private: - //! The vector of children. - std::vector children; - //! The dimension this node splits on. - size_t splitDimension; - //! The type of the dimension that we have split on (if we are not a leaf). - //! If we are a leaf, then this is the index of the majority class. - size_t dimensionTypeOrMajorityClass; - /** - * This vector may hold different things. If the node has no children, then - * it is guaranteed to hold the probabilities of each class. If the node has - * children, then it may be used arbitrarily by the split type's - * CalculateDirection() function and may not necessarily hold class - * probabilities. - */ - arma::vec classProbabilities; - - //! Note that this class will also hold the members of the NumericSplit and - //! CategoricalSplit AuxiliarySplitInfo classes, since it inherits from them. - //! We'll define some convenience typedefs here. - typedef typename NumericSplit::template AuxiliarySplitInfo - NumericAuxiliarySplitInfo; - typedef typename CategoricalSplit::template AuxiliarySplitInfo - CategoricalAuxiliarySplitInfo; - - /** - * Calculate the class probabilities of the given labels. - */ - template - void CalculateClassProbabilities(const RowType& labels, - const size_t numClasses, - const WeightsRowType& weights); - - /** - * Corresponding to the public Train() method, this method is designed for - * avoiding unnecessary copies during training. This function is called to - * train children. - * - * @param data Dataset to train on. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param datasetInfo Type information for each dimension. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - void Train(MatType& data, - const size_t begin, - const size_t count, - const data::DatasetInfo& datasetInfo, - arma::Row& labels, - const size_t numClasses, - arma::rowvec& weights, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7); - - /** - * Corresponding to the public Train() method, this method is designed for - * avoiding unnecessary copies during training. This method is called for - * training children. - * - * @param data Dataset to train on. - * @param begin Index of the starting point in the dataset that belongs to - * this node. - * @param count Number of points in this node. - * @param labels Labels for each training point. - * @param numClasses Number of classes in the dataset. - * @param minimumLeafSize Minimum number of points in each leaf node. - * @param minimumGainSplit Minimum gain for the node to split. - */ - template - void Train(MatType& data, - const size_t begin, - const size_t count, - arma::Row& labels, - const size_t numClasses, - arma::rowvec& weights, - const size_t minimumLeafSize = 10, - const double minimumGainSplit = 1e-7); -}; - -/** - * Convenience typedef for decision stumps (single level decision trees). - */ -template class NumericSplitType = BestBinaryNumericSplit, - template class CategoricalSplitType = AllCategoricalSplit, - typename DimensionSelectType = AllDimensionSelect, - typename ElemType = double> -using DecisionStump = DecisionTree; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "decision_tree_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/decision_tree_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/decision_tree_impl.hpp deleted file mode 100644 index 51471c058..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/decision_tree_impl.hpp +++ /dev/null @@ -1,1055 +0,0 @@ -/** - * @file decision_tree_impl.hpp - * @author Ryan Curtin - * - * Implementation of generic decision tree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_DECISION_TREE_IMPL_HPP -#define MLPACK_METHODS_DECISION_TREE_DECISION_TREE_IMPL_HPP - -namespace mlpack { -namespace tree { - -//! Construct and train without weight. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -DecisionTree::DecisionTree(MatType data, - const data::DatasetInfo& datasetInfo, - LabelsType labels, - const size_t numClasses, - const size_t minimumLeafSize, - const double minimumGainSplit) -{ - using TrueMatType = typename std::decay::type; - using TrueLabelsType = typename std::decay::type; - - // Copy or move data. - TrueMatType tmpData(std::move(data)); - TrueLabelsType tmpLabels(std::move(labels)); - - // Pass off work to the Train() method. - arma::rowvec weights; // Fake weights, not used. - Train(tmpData, 0, tmpData.n_cols, datasetInfo, tmpLabels, numClasses, - weights, minimumLeafSize, minimumGainSplit); -} - -//! Construct and train. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -DecisionTree::DecisionTree(MatType data, - LabelsType labels, - const size_t numClasses, - const size_t minimumLeafSize, - const double minimumGainSplit) -{ - using TrueMatType = typename std::decay::type; - using TrueLabelsType = typename std::decay::type; - - // Copy or move data. - TrueMatType tmpData(std::move(data)); - TrueLabelsType tmpLabels(std::move(labels)); - - // Pass off work to the Train() method. - arma::rowvec weights; // Fake weights, not used. - Train(tmpData, 0, tmpData.n_cols, tmpLabels, numClasses, weights, - minimumLeafSize, minimumGainSplit); -} - -//! Construct and train with weights. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -DecisionTree::DecisionTree(MatType data, - const data::DatasetInfo& datasetInfo, - LabelsType labels, - const size_t numClasses, - WeightsType weights, - const size_t minimumLeafSize, - const double minimumGainSplit, - const std::enable_if_t< - arma::is_arma_type< - typename std::remove_reference< - WeightsType>::type>::value>*) -{ - using TrueMatType = typename std::decay::type; - using TrueLabelsType = typename std::decay::type; - using TrueWeightsType = typename std::decay::type; - - // Copy or move data. - TrueMatType tmpData(std::move(data)); - TrueLabelsType tmpLabels(std::move(labels)); - TrueWeightsType tmpWeights(std::move(weights)); - - // Pass off work to the weighted Train() method. - Train(tmpData, 0, tmpData.n_cols, datasetInfo, tmpLabels, numClasses, - tmpWeights, minimumLeafSize, minimumGainSplit); -} - -//! Construct and train with weights. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -DecisionTree::DecisionTree(MatType data, - LabelsType labels, - const size_t numClasses, - WeightsType weights, - const size_t minimumLeafSize, - const double minimumGainSplit, - const std::enable_if_t< - arma::is_arma_type< - typename std::remove_reference< - WeightsType>::type>::value>*) -{ - using TrueMatType = typename std::decay::type; - using TrueLabelsType = typename std::decay::type; - using TrueWeightsType = typename std::decay::type; - - // Copy or move data. - TrueMatType tmpData(std::move(data)); - TrueLabelsType tmpLabels(std::move(labels)); - TrueWeightsType tmpWeights(std::move(weights)); - - // Pass off work to the weighted Train() method. - Train(tmpData, 0, tmpData.n_cols, tmpLabels, numClasses, tmpWeights, - minimumLeafSize, minimumGainSplit); -} - -//! Construct, don't train. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -DecisionTree::DecisionTree(const size_t numClasses) : - splitDimension(0), - dimensionTypeOrMajorityClass(0), - classProbabilities(numClasses) -{ - // Initialize utility vector. - classProbabilities.fill(1.0 / (double) numClasses); -} - -//! Copy another tree. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -DecisionTree::DecisionTree(const DecisionTree& other) : - NumericAuxiliarySplitInfo(other), - CategoricalAuxiliarySplitInfo(other), - splitDimension(other.splitDimension), - dimensionTypeOrMajorityClass(other.dimensionTypeOrMajorityClass), - classProbabilities(other.classProbabilities) -{ - // Copy each child. - for (size_t i = 0; i < other.children.size(); ++i) - children.push_back(new DecisionTree(*other.children[i])); -} - -//! Take ownership of another tree. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -DecisionTree::DecisionTree(DecisionTree&& other) : - NumericAuxiliarySplitInfo(std::move(other)), - CategoricalAuxiliarySplitInfo(std::move(other)), - children(std::move(other.children)), - splitDimension(other.splitDimension), - dimensionTypeOrMajorityClass(other.dimensionTypeOrMajorityClass), - classProbabilities(std::move(other.classProbabilities)) -{ - // Reset the other object. - other.classProbabilities.ones(1); // One class, P(1) = 1. -} - -//! Copy another tree. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -DecisionTree& -DecisionTree::operator=(const DecisionTree& other) -{ - if (this == &other) - return *this; // Nothing to copy. - - // Clean memory if needed. - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); - - // Copy everything from the other tree. - splitDimension = other.splitDimension; - dimensionTypeOrMajorityClass = other.dimensionTypeOrMajorityClass; - classProbabilities = other.classProbabilities; - - // Copy the children. - for (size_t i = 0; i < other.children.size(); ++i) - children.push_back(new DecisionTree(*other.children[i])); - - // Copy the auxiliary info. - NumericAuxiliarySplitInfo::operator=(other); - CategoricalAuxiliarySplitInfo::operator=(other); - - return *this; -} - -//! Take ownership of another tree. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -DecisionTree& -DecisionTree::operator=(DecisionTree&& other) -{ - if (this == &other) - return *this; // Nothing to move. - - // Clean memory if needed. - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); - - // Take ownership of the other tree's components. - children = std::move(other.children); - splitDimension = other.splitDimension; - dimensionTypeOrMajorityClass = other.dimensionTypeOrMajorityClass; - classProbabilities = std::move(other.classProbabilities); - - // Reset the class probabilities of the other object. - other.classProbabilities.ones(1); // One class, P(1) = 1. - - // Take ownership of the auxiliary info. - NumericAuxiliarySplitInfo::operator=(std::move(other)); - CategoricalAuxiliarySplitInfo::operator=(std::move(other)); - - return *this; -} - -//! Clean up memory. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -DecisionTree::~DecisionTree() -{ - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; -} - -//! Train on the given data. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Train(MatType data, - const data::DatasetInfo& datasetInfo, - LabelsType labels, - const size_t numClasses, - const size_t minimumLeafSize, - const double minimumGainSplit) -{ - // Sanity check on data. - if (data.n_cols != labels.n_elem) - { - std::ostringstream oss; - oss << "DecisionTree::Train(): number of points (" << data.n_cols << ") " - << "does not match number of labels (" << labels.n_elem << ")!" - << std::endl; - throw std::invalid_argument(oss.str()); - } - - using TrueMatType = typename std::decay::type; - using TrueLabelsType = typename std::decay::type; - - // Copy or move data. - TrueMatType tmpData(std::move(data)); - TrueLabelsType tmpLabels(std::move(labels)); - - // Pass off work to the Train() method. - arma::rowvec weights; // Fake weights, not used. - Train(tmpData, 0, tmpData.n_cols, datasetInfo, tmpLabels, numClasses, - weights, minimumLeafSize, minimumGainSplit); -} - -//! Train on the given data, assuming all dimensions are numeric. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Train(MatType data, - LabelsType labels, - const size_t numClasses, - const size_t minimumLeafSize, - const double minimumGainSplit) -{ - // Sanity check on data. - if (data.n_cols != labels.n_elem) - { - std::ostringstream oss; - oss << "DecisionTree::Train(): number of points (" << data.n_cols << ") " - << "does not match number of labels (" << labels.n_elem << ")!" - << std::endl; - throw std::invalid_argument(oss.str()); - } - - using TrueMatType = typename std::decay::type; - using TrueLabelsType = typename std::decay::type; - - // Copy or move data. - TrueMatType tmpData(std::move(data)); - TrueLabelsType tmpLabels(std::move(labels)); - - // Pass off work to the Train() method. - arma::rowvec weights; // Fake weights, not used. - Train(tmpData, 0, tmpData.n_cols, tmpLabels, numClasses, weights, - minimumLeafSize, minimumGainSplit); -} - -//! Train on the given weighted data. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Train(MatType data, - const data::DatasetInfo& datasetInfo, - LabelsType labels, - const size_t numClasses, - WeightsType weights, - const size_t minimumLeafSize, - const double minimumGainSplit, - const std::enable_if_t::type>::value>*) -{ - // Sanity check on data. - if (data.n_cols != labels.n_elem) - { - std::ostringstream oss; - oss << "DecisionTree::Train(): number of points (" << data.n_cols << ") " - << "does not match number of labels (" << labels.n_elem << ")!" - << std::endl; - throw std::invalid_argument(oss.str()); - } - - using TrueMatType = typename std::decay::type; - using TrueLabelsType = typename std::decay::type; - using TrueWeightsType = typename std::decay::type; - - // Copy or move data. - TrueMatType tmpData(std::move(data)); - TrueLabelsType tmpLabels(std::move(labels)); - TrueWeightsType tmpWeights(std::move(weights)); - - // Pass off work to the Train() method. - Train(tmpData, 0, tmpData.n_cols, datasetInfo, tmpLabels, numClasses, - tmpWeights, minimumLeafSize, minimumGainSplit); -} - -//! Train on the given weighted data. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Train(MatType data, - LabelsType labels, - const size_t numClasses, - WeightsType weights, - const size_t minimumLeafSize, - const double minimumGainSplit, - const std::enable_if_t::type>::value>*) -{ - // Sanity check on data. - if (data.n_cols != labels.n_elem) - { - std::ostringstream oss; - oss << "DecisionTree::Train(): number of points (" << data.n_cols << ") " - << "does not match number of labels (" << labels.n_elem << ")!" - << std::endl; - throw std::invalid_argument(oss.str()); - } - - using TrueMatType = typename std::decay::type; - using TrueLabelsType = typename std::decay::type; - using TrueWeightsType = typename std::decay::type; - - // Copy or move data. - TrueMatType tmpData(std::move(data)); - TrueLabelsType tmpLabels(std::move(labels)); - TrueWeightsType tmpWeights(std::move(weights)); - - // Pass off work to the Train() method. - Train(tmpData, 0, tmpData.n_cols, tmpLabels, numClasses, tmpWeights, - minimumLeafSize, minimumGainSplit); -} - -//! Train on the given data. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Train(MatType& data, - const size_t begin, - const size_t count, - const data::DatasetInfo& datasetInfo, - arma::Row& labels, - const size_t numClasses, - arma::rowvec& weights, - const size_t minimumLeafSize, - const double minimumGainSplit) -{ - // Clear children if needed. - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); - - // Look through the list of dimensions and obtain the gain of the best split. - // We'll cache the best numeric and categorical split auxiliary information in - // numericAux and categoricalAux (and clear them later if we make no split), - // and use classProbabilities as auxiliary information. Later we'll overwrite - // classProbabilities to the empirical class probabilities if we do not split. - double bestGain = FitnessFunction::template Evaluate( - labels.subvec(begin, begin + count - 1), - numClasses, - UseWeights ? weights.subvec(begin, begin + count - 1) : weights); - size_t bestDim = datasetInfo.Dimensionality(); // This means "no split". - DimensionSelectionType dimensions(datasetInfo.Dimensionality()); - for (size_t i = dimensions.Begin(); i != dimensions.End(); - i = dimensions.Next()) - { - double dimGain = -DBL_MAX; - if (datasetInfo.Type(i) == data::Datatype::categorical) - { - dimGain = CategoricalSplit::template SplitIfBetter(bestGain, - data.cols(begin, begin + count - 1).row(i), - datasetInfo.NumMappings(i), - labels.subvec(begin, begin + count - 1), - numClasses, - UseWeights ? weights.subvec(begin, begin + count - 1) : weights, - minimumLeafSize, - minimumGainSplit, - classProbabilities, - *this); - } - else if (datasetInfo.Type(i) == data::Datatype::numeric) - { - dimGain = NumericSplit::template SplitIfBetter(bestGain, - data.cols(begin, begin + count - 1).row(i), - labels.subvec(begin, begin + count - 1), - numClasses, - UseWeights ? weights.subvec(begin, begin + count - 1) : weights, - minimumLeafSize, - minimumGainSplit, - classProbabilities, - *this); - } - - // Was there an improvement? If so mark that it's the new best dimension. - if (dimGain > bestGain) - { - bestDim = i; - bestGain = dimGain; - } - - // If the gain is the best possible, no need to keep looking. - if (bestGain >= 0.0) - break; - } - - // Did we split or not? If so, then split the data and create the children. - if (bestDim != datasetInfo.Dimensionality()) - { - dimensionTypeOrMajorityClass = (size_t) datasetInfo.Type(bestDim); - splitDimension = bestDim; - - // Get the number of children we will have. - size_t numChildren = 0; - if (datasetInfo.Type(bestDim) == data::Datatype::categorical) - numChildren = CategoricalSplit::NumChildren(classProbabilities, *this); - else - numChildren = NumericSplit::NumChildren(classProbabilities, *this); - - // Calculate all child assignments. - arma::Row childAssignments(count); - if (datasetInfo.Type(bestDim) == data::Datatype::categorical) - { - for (size_t j = begin; j < begin + count; ++j) - childAssignments[j - begin] = CategoricalSplit::CalculateDirection( - data(bestDim, j), classProbabilities, *this); - } - else - { - for (size_t j = begin; j < begin + count; ++j) - { - childAssignments[j - begin] = NumericSplit::CalculateDirection( - data(bestDim, j), classProbabilities, *this); - } - } - - // Figure out counts of children. - arma::Row childCounts(numClasses, arma::fill::zeros); - for (size_t i = begin; i < begin + count; ++i) - childCounts[childAssignments[i - begin]]++; - - // Split into children. - size_t currentCol = begin; - for (size_t i = 0; i < numChildren; ++i) - { - size_t currentChildBegin = currentCol; - for (size_t j = currentChildBegin; j < begin + count; ++j) - { - if (childAssignments[j - begin] == i) - { - childAssignments.swap_cols(currentCol - begin, j - begin); - data.swap_cols(currentCol, j); - labels.swap_cols(currentCol, j); - if (UseWeights) - weights.swap_cols(currentCol, j); - ++currentCol; - } - } - - // Now build the child recursively. - DecisionTree* child = new DecisionTree(); - if (NoRecursion) - { - child->Train(data, currentChildBegin, - currentCol - currentChildBegin, datasetInfo, labels, numClasses, - weights, currentCol - currentChildBegin, minimumGainSplit); - } - else - { - child->Train(data, currentChildBegin, - currentCol - currentChildBegin, datasetInfo, labels, numClasses, - weights, minimumLeafSize, minimumGainSplit); - } - children.push_back(child); - } - } - else - { - // Clear auxiliary info objects. - NumericAuxiliarySplitInfo::operator=(NumericAuxiliarySplitInfo()); - CategoricalAuxiliarySplitInfo::operator=(CategoricalAuxiliarySplitInfo()); - - // Calculate class probabilities because we are a leaf. - CalculateClassProbabilities( - labels.subvec(begin, begin + count - 1), - numClasses, - UseWeights ? weights.subvec(begin, begin + count - 1) : weights); - } -} - -//! Train on the given data, assuming all dimensions are numeric. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Train(MatType& data, - const size_t begin, - const size_t count, - arma::Row& labels, - const size_t numClasses, - arma::rowvec& weights, - const size_t minimumLeafSize, - const double minimumGainSplit) -{ - // Clear children if needed. - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); - - // We won't be using these members, so reset them. - CategoricalAuxiliarySplitInfo::operator=(CategoricalAuxiliarySplitInfo()); - - // Look through the list of dimensions and obtain the best split. We'll cache - // the best numeric split auxiliary information in numericAux (and clear it - // later if we don't make a split), and use classProbabilities as auxiliary - // information. Later we'll overwrite classProbabilities to the empirical - // class probabilities if we do not split. - double bestGain = FitnessFunction::template Evaluate( - labels.subvec(begin, begin + count - 1), - numClasses, - UseWeights ? weights.subvec(begin, begin + count - 1) : weights); - size_t bestDim = data.n_rows; // This means "no split". - for (size_t i = 0; i < data.n_rows; ++i) - { - const double dimGain = NumericSplitType::template - SplitIfBetter(bestGain, - data.cols(begin, begin + count - 1).row(i), - labels.cols(begin, begin + count - 1), - numClasses, - UseWeights ? - weights.cols(begin, begin + count - 1) : - weights, - minimumLeafSize, - minimumGainSplit, - classProbabilities, - *this); - - if (dimGain > bestGain) - { - bestDim = i; - bestGain = dimGain; - } - - // If the gain is the best possible, no need to keep looking. - if (bestGain >= 0.0) - break; - } - - // Did we split or not? If so, then split the data and create the children. - if (bestDim != data.n_rows) - { - // We know that the split is numeric. - size_t numChildren = NumericSplit::NumChildren(classProbabilities, *this); - splitDimension = bestDim; - dimensionTypeOrMajorityClass = (size_t) data::Datatype::numeric; - - // Calculate all child assignments. - arma::Row childAssignments(count); - - for (size_t j = begin; j < begin + count; ++j) - { - childAssignments[j - begin] = NumericSplit::CalculateDirection( - data(bestDim, j), classProbabilities, *this); - } - - // Calculate counts of children in each node. - arma::Row childCounts(numChildren); - childCounts.zeros(); - for (size_t j = begin; j < begin + count; ++j) - childCounts[childAssignments[j - begin]]++; - - size_t currentCol = begin; - for (size_t i = 0; i < numChildren; ++i) - { - size_t currentChildBegin = currentCol; - for (size_t j = currentChildBegin; j < begin + count; ++j) - { - if (childAssignments[j - begin] == i) - { - childAssignments.swap_cols(currentCol - begin, j - begin); - data.swap_cols(currentCol, j); - labels.swap_cols(currentCol, j); - if (UseWeights) - weights.swap_cols(currentCol, j); - ++currentCol; - } - } - - // Now build the child recursively. - DecisionTree* child = new DecisionTree(); - if (NoRecursion) - { - child->Train(data, currentChildBegin, - currentCol - currentChildBegin, labels, numClasses, weights, - currentCol - currentChildBegin, minimumGainSplit); - } - else - { - child->Train(data, currentChildBegin, - currentCol - currentChildBegin, labels, numClasses, weights, - minimumLeafSize, minimumGainSplit); - } - children.push_back(child); - } - } - else - { - // We won't be needing these members, so reset them. - NumericAuxiliarySplitInfo::operator=(NumericAuxiliarySplitInfo()); - - // Calculate class probabilities because we are a leaf. - CalculateClassProbabilities( - labels.subvec(begin, begin + count - 1), - numClasses, - UseWeights ? weights.subvec(begin, begin + count - 1) : weights); - } -} - -//! Return the class. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -size_t DecisionTree::Classify(const VecType& point) const -{ - if (children.size() == 0) - { - // Return cached max of probabilities. - return dimensionTypeOrMajorityClass; - } - - return children[CalculateDirection(point)]->Classify(point); -} - -//! Return class probabilities for a given point. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Classify(const VecType& point, - size_t& prediction, - arma::vec& probabilities) const -{ - if (children.size() == 0) - { - prediction = dimensionTypeOrMajorityClass; - probabilities = classProbabilities; - return; - } - - children[CalculateDirection(point)]->Classify(point, prediction, - probabilities); -} - -//! Return the class for a set of points. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Classify(const MatType& data, - arma::Row& predictions) const -{ - predictions.set_size(data.n_cols); - if (children.size() == 0) - { - predictions.fill(dimensionTypeOrMajorityClass); - return; - } - - // Loop over each point. - for (size_t i = 0; i < data.n_cols; ++i) - predictions[i] = Classify(data.col(i)); -} - -//! Return the class probabilities for a set of points. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::Classify(const MatType& data, - arma::Row& predictions, - arma::mat& probabilities) const -{ - predictions.set_size(data.n_cols); - if (children.size() == 0) - { - predictions.fill(dimensionTypeOrMajorityClass); - probabilities = arma::repmat(classProbabilities, 1, data.n_cols); - return; - } - - // Otherwise we have to find the right size to set the predictions matrix to - // be. - DecisionTree* node = children[0]; - while (node->NumChildren() != 0) - node = &node->Child(0); - probabilities.set_size(node->classProbabilities.n_elem, data.n_cols); - - for (size_t i = 0; i < data.n_cols; ++i) - { - arma::vec v = probabilities.unsafe_col(i); // Alias of column. - Classify(data.col(i), predictions[i], v); - } -} - -//! Serialize the tree. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::serialize(Archive& ar, - const unsigned int /* version */) -{ - // Clean memory if needed. - if (Archive::is_loading::value) - { - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); - } - - // Serialize the children first. - ar & BOOST_SERIALIZATION_NVP(children); - - // Now serialize the rest of the object. - ar & BOOST_SERIALIZATION_NVP(splitDimension); - ar & BOOST_SERIALIZATION_NVP(dimensionTypeOrMajorityClass); - ar & BOOST_SERIALIZATION_NVP(classProbabilities); -} - -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -size_t DecisionTree::CalculateDirection(const VecType& point) const -{ - if ((data::Datatype) dimensionTypeOrMajorityClass == - data::Datatype::categorical) - return CategoricalSplit::CalculateDirection(point[splitDimension], - classProbabilities, *this); - else - return NumericSplit::CalculateDirection(point[splitDimension], - classProbabilities, *this); -} - -// Get the number of classes in the tree. -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -size_t DecisionTree::NumClasses() const -{ - // Recurse to the nearest child and return the number of elements in the - // probability vector. - if (children.size() == 0) - return classProbabilities.n_elem; - else - return children[0]->NumClasses(); -} - -template class NumericSplitType, - template class CategoricalSplitType, - typename DimensionSelectionType, - typename ElemType, - bool NoRecursion> -template -void DecisionTree::CalculateClassProbabilities( - const RowType& labels, - const size_t numClasses, - const WeightsRowType& weights) -{ - classProbabilities.zeros(numClasses); - double sumWeights = 0.0; - for (size_t i = 0; i < labels.n_elem; ++i) - { - if (UseWeights) - { - classProbabilities[labels[i]] += weights[i]; - sumWeights += weights[i]; - } - else - { - classProbabilities[labels[i]]++; - } - } - - // Now normalize into probabilities. - classProbabilities /= UseWeights ? sumWeights : labels.n_elem; - arma::uword maxIndex = 0; - classProbabilities.max(maxIndex); - dimensionTypeOrMajorityClass = (size_t) maxIndex; -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/gini_gain.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/gini_gain.hpp deleted file mode 100644 index c15541046..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/gini_gain.hpp +++ /dev/null @@ -1,197 +0,0 @@ -/** - * @file gini_gain.hpp - * @author Ryan Curtin - * - * The GiniGain class, which is a fitness function (FitnessFunction) for - * decision trees. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_GINI_GAIN_HPP -#define MLPACK_METHODS_DECISION_TREE_GINI_GAIN_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * The Gini gain, a measure of set purity usable as a fitness function - * (FitnessFunction) for decision trees. This is the exact same thing as the - * well-known Gini impurity, but negated---since the decision tree will be - * trying to maximize gain (and the Gini impurity would need to be minimized). - */ -class GiniGain -{ - public: - /** - * Evaluate the Gini impurity on the given set of labels. RowType should be - * an Armadillo vector that holds size_t objects. - * - * Note that it is possible that due to floating-point representation issues, - * it is possible that the gain returned can be very slightly greater than 0! - * Thus, if you are checking for a perfect fit, be sure to use 'gain >= 0.0' - * not 'gain == 0.0'. - * - * @param labels Set of labels to evaluate Gini impurity on. - * @param numClasses Number of classes in the dataset. - * @param weights Weight of labels. - */ - template - static double Evaluate(const RowType& labels, - const size_t numClasses, - const WeightVecType& weights) - { - // Corner case: if there are no elements, the impurity is zero. - if (labels.n_elem == 0) - return 0.0; - - // Count the number of elements in each class. Use four auxiliary vectors - // to exploit SIMD instructions if possible. - arma::vec countSpace(4 * numClasses, arma::fill::zeros); - arma::vec counts(countSpace.memptr(), numClasses, false, true); - arma::vec counts2(countSpace.memptr() + numClasses, numClasses, false, - true); - arma::vec counts3(countSpace.memptr() + 2 * numClasses, numClasses, false, - true); - arma::vec counts4(countSpace.memptr() + 3 * numClasses, numClasses, false, - true); - - // Calculate the Gini impurity of the un-split node. - double impurity = 0.0; - - if (UseWeights) - { - // Sum all the weights up. - double accWeights[4] = { 0.0, 0.0, 0.0, 0.0 }; - - // SIMD loop: add counts for four elements simultaneously (if the compiler - // manages to vectorize the loop). - for (size_t i = 3; i < labels.n_elem; i += 4) - { - const double weight1 = weights[i - 3]; - const double weight2 = weights[i - 2]; - const double weight3 = weights[i - 1]; - const double weight4 = weights[i]; - - counts[labels[i - 3]] += weight1; - counts2[labels[i - 2]] += weight2; - counts3[labels[i - 1]] += weight3; - counts4[labels[i]] += weight4; - - accWeights[0] += weight1; - accWeights[1] += weight2; - accWeights[2] += weight3; - accWeights[3] += weight4; - } - - // Handle leftovers. - if (labels.n_elem % 4 == 1) - { - const double weight1 = weights[labels.n_elem - 1]; - counts[labels[labels.n_elem - 1]] += weight1; - accWeights[0] += weight1; - } - else if (labels.n_elem % 4 == 2) - { - const double weight1 = weights[labels.n_elem - 2]; - const double weight2 = weights[labels.n_elem - 1]; - - counts[labels[labels.n_elem - 2]] += weight1; - counts2[labels[labels.n_elem - 1]] += weight2; - - accWeights[0] += weight1; - accWeights[1] += weight2; - } - else if (labels.n_elem % 4 == 3) - { - const double weight1 = weights[labels.n_elem - 3]; - const double weight2 = weights[labels.n_elem - 2]; - const double weight3 = weights[labels.n_elem - 1]; - - counts[labels[labels.n_elem - 3]] += weight1; - counts2[labels[labels.n_elem - 2]] += weight2; - counts3[labels[labels.n_elem - 1]] += weight3; - - accWeights[0] += weight1; - accWeights[1] += weight2; - accWeights[2] += weight3; - } - - accWeights[0] += accWeights[1] + accWeights[2] + accWeights[3]; - counts += counts2 + counts3 + counts4; - - // Catch edge case: if there are no weights, the impurity is zero. - if (accWeights[0] == 0.0) - return 0.0; - - for (size_t i = 0; i < numClasses; ++i) - { - const double f = ((double) counts[i] / (double) accWeights[0]); - impurity += f * (1.0 - f); - } - } - else - { - // SIMD loop: add counts for four elements simultaneously (if the compiler - // manages to vectorize the loop). - for (size_t i = 3; i < labels.n_elem; i += 4) - { - counts[labels[i - 3]]++; - counts2[labels[i - 2]]++; - counts3[labels[i - 1]]++; - counts4[labels[i]]++; - } - - // Handle leftovers. - if (labels.n_elem % 4 == 1) - { - counts[labels[labels.n_elem - 1]]++; - } - else if (labels.n_elem % 4 == 2) - { - counts[labels[labels.n_elem - 2]]++; - counts2[labels[labels.n_elem - 1]]++; - } - else if (labels.n_elem % 4 == 3) - { - counts[labels[labels.n_elem - 3]]++; - counts2[labels[labels.n_elem - 2]]++; - counts3[labels[labels.n_elem - 1]]++; - } - - counts += counts2 + counts3 + counts4; - - for (size_t i = 0; i < numClasses; ++i) - { - const double f = ((double) counts[i] / (double) labels.n_elem); - impurity += f * (1.0 - f); - } - } - - return -impurity; - } - - /** - * Return the range of the Gini impurity for the given number of classes. - * (That is, the difference between the maximum possible value and the minimum - * possible value.) - * - * @param numClasses Number of classes in the dataset. - */ - static double Range(const size_t numClasses) - { - // The best possible case is that only one class exists, which gives a Gini - // impurity of 0. The worst possible case is that the classes are evenly - // distributed, which gives n * (1/n * (1 - 1/n)) = 1 - 1/n. - return 1.0 - (1.0 / double(numClasses)); - } -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/information_gain.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/information_gain.hpp deleted file mode 100644 index 08ba0402e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/information_gain.hpp +++ /dev/null @@ -1,194 +0,0 @@ -/** - * @file information_gain.hpp - * @author Ryan Curtin - * - * An implementation of information gain, which can be used in place of Gini - * gain. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_INFORMATION_GAIN_HPP -#define MLPACK_METHODS_DECISION_TREE_INFORMATION_GAIN_HPP - -#include - -namespace mlpack { -namespace tree { - -/** - * The standard information gain criterion, used for calculating gain in - * decision trees. - */ -class InformationGain -{ - public: - /** - * Given a set of labels, calculate the information gain of those labels. - * Note that it is possible that due to floating-point representation issues, - * it is possible that the gain returned can be very slightly greater than 0! - * Thus, if you are checking for a perfect fit, be sure to use 'gain >= 0.0' - * not 'gain == 0.0'. - * - * @param labels Labels of the dataset. - * @param numClasses Number of classes in the dataset. - */ - template - static double Evaluate(const arma::Row& labels, - const size_t numClasses, - const arma::Row& weights) - { - // Edge case: if there are no elements, the gain is zero. - if (labels.n_elem == 0) - return 0.0; - - // Calculate the information gain. - double gain = 0.0; - - // Count the number of elements in each class. Use four auxiliary vectors - // to exploit SIMD instructions if possible. - arma::vec countSpace(4 * numClasses, arma::fill::zeros); - arma::vec counts(countSpace.memptr(), numClasses, false, true); - arma::vec counts2(countSpace.memptr() + numClasses, numClasses, false, - true); - arma::vec counts3(countSpace.memptr() + 2 * numClasses, numClasses, false, - true); - arma::vec counts4(countSpace.memptr() + 3 * numClasses, numClasses, false, - true); - - if (UseWeights) - { - // Sum all the weights up. - double accWeights[4] = { 0.0, 0.0, 0.0, 0.0 }; - - // SIMD loop: add counts for four elements simultaneously (if the compiler - // manages to vectorize the loop). - for (size_t i = 3; i < labels.n_elem; i += 4) - { - const double weight1 = weights[i - 3]; - const double weight2 = weights[i - 2]; - const double weight3 = weights[i - 1]; - const double weight4 = weights[i]; - - counts[labels[i - 3]] += weight1; - counts2[labels[i - 2]] += weight2; - counts3[labels[i - 1]] += weight3; - counts4[labels[i]] += weight4; - - accWeights[0] += weight1; - accWeights[1] += weight2; - accWeights[2] += weight3; - accWeights[3] += weight4; - } - - // Handle leftovers. - if (labels.n_elem % 4 == 1) - { - const double weight1 = weights[labels.n_elem - 1]; - counts[labels[labels.n_elem - 1]] += weight1; - accWeights[0] += weight1; - } - else if (labels.n_elem % 4 == 2) - { - const double weight1 = weights[labels.n_elem - 2]; - const double weight2 = weights[labels.n_elem - 1]; - - counts[labels[labels.n_elem - 2]] += weight1; - counts2[labels[labels.n_elem - 1]] += weight2; - - accWeights[0] += weight1; - accWeights[1] += weight2; - } - else if (labels.n_elem % 4 == 3) - { - const double weight1 = weights[labels.n_elem - 3]; - const double weight2 = weights[labels.n_elem - 2]; - const double weight3 = weights[labels.n_elem - 1]; - - counts[labels[labels.n_elem - 3]] += weight1; - counts2[labels[labels.n_elem - 2]] += weight2; - counts3[labels[labels.n_elem - 1]] += weight3; - - accWeights[0] += weight1; - accWeights[1] += weight2; - accWeights[2] += weight3; - } - - accWeights[0] += accWeights[1] + accWeights[2] + accWeights[3]; - counts += counts2 + counts3 + counts4; - - // Corner case: return 0 if no weight. - if (accWeights[0] == 0.0) - return 0.0; - - for (size_t i = 0; i < numClasses; ++i) - { - const double f = ((double) counts[i] / (double) accWeights[0]); - if (f > 0.0) - gain += f * std::log2(f); - } - } - else - { - // SIMD loop: add counts for four elements simultaneously (if the compiler - // manages to vectorize the loop). - for (size_t i = 3; i < labels.n_elem; i += 4) - { - counts[labels[i - 3]]++; - counts2[labels[i - 2]]++; - counts3[labels[i - 1]]++; - counts4[labels[i]]++; - } - - // Handle leftovers. - if (labels.n_elem % 4 == 1) - { - counts[labels[labels.n_elem - 1]]++; - } - else if (labels.n_elem % 4 == 2) - { - counts[labels[labels.n_elem - 2]]++; - counts2[labels[labels.n_elem - 1]]++; - } - else if (labels.n_elem % 4 == 3) - { - counts[labels[labels.n_elem - 3]]++; - counts2[labels[labels.n_elem - 2]]++; - counts3[labels[labels.n_elem - 1]]++; - } - - counts += counts2 + counts3 + counts4; - - for (size_t i = 0; i < numClasses; ++i) - { - const double f = ((double) counts[i] / (double) labels.n_elem); - if (f > 0.0) - gain += f * std::log2(f); - } - } - - return gain; - } - - /** - * Return the range of the information gain for the given number of classes. - * (That is, the difference between the maximum possible value and the minimum - * possible value.) - * - * @param numClasses Number of classes in the dataset. - */ - static double Range(const size_t numClasses) - { - // The best possible case gives an information gain of 0. The worst - // possible case is even distribution, which gives n * (1/n * log2(1/n)) = - // log2(1/n) = -log2(n). So, the range is log2(n). - return std::log2(numClasses); - } -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/multiple_random_dimension_select.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/multiple_random_dimension_select.hpp deleted file mode 100644 index 6d41db788..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/multiple_random_dimension_select.hpp +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @file multiple_random_dimension_select.hpp - * @author Ryan Curtin - * - * Select a number of random dimensions to pick from. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_MULTIPLE_RANDOM_DIMENSION_SPLIT_HPP -#define MLPACK_METHODS_DECISION_TREE_MULTIPLE_RANDOM_DIMENSION_SPLIT_HPP - -namespace mlpack { -namespace tree { - -/** - * This dimension selection policy allows the selection from a few random - * dimensions. The number of random dimensions to use is specified by the - * NumDimensions template parameter. - * - * @tparam NumDimensions Number of random dimensions to select. - */ -template -class MultipleRandomDimensionSelect -{ - public: - /** - * Instantiate the MultipleRandomDimensionSelect object. - */ - MultipleRandomDimensionSelect(const size_t dimensions) - { - for (size_t i = 0; i < NumDimensions; ++i) - { - // Generate random different numbers. - bool unique = false; - size_t value; - while (!unique) - { - value = math::RandInt(dimensions); - - // Check if we already have the value. - unique = true; - for (size_t j = 0; j < i; ++j) - { - if (values[j] == value) - { - unique = false; - break; - } - } - } - - values[i] = value; - } - - values[NumDimensions] = std::numeric_limits::max(); - } - - /** - * Get the first random value. - */ - size_t Begin() - { - i = 0; - return values[0]; - } - - /** - * Get the last random value. - */ - size_t End() const { return size_t(-1); } - - /** - * Get the next index. - */ - size_t Next() - { - return values[++i]; - } - - private: - //! The values we select from. - size_t values[NumDimensions + 1]; - //! The current value we are looking at. - size_t i; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/decision_tree/random_dimension_select.hpp b/src/sdk/mlpack/include/mlpack/methods/decision_tree/random_dimension_select.hpp deleted file mode 100644 index 90f583380..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/decision_tree/random_dimension_select.hpp +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @file random_dimension_select.hpp - * @author Ryan Curtin - * - * Selects one single random dimension to split on. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DECISION_TREE_RANDOM_DIMENSION_SELECT_HPP -#define MLPACK_METHODS_DECISION_TREE_RANDOM_DIMENSION_SELECT_HPP - -namespace mlpack { -namespace tree { - -/** - * This dimension selection policy only selects one single random dimension. - */ -class RandomDimensionSelect -{ - public: - /** - * Construct the RandomDimensionSelect object with the given number of - * dimensions. - */ - RandomDimensionSelect(const size_t dimensions) : dimensions(dimensions) { } - - /** - * Get the first dimension to select from. - */ - size_t Begin() const { return math::RandInt(dimensions); } - - /** - * Get the last dimension to select from. - */ - size_t End() const { return dimensions; } - - /** - * Get the next (last) dimensions. We only allow one dimension, so any 'next' - * dimension is past our bounds. - */ - size_t Next() const { return dimensions; } - - private: - //! The number of dimensions to select from. - const size_t dimensions; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/det/dt_utils.hpp b/src/sdk/mlpack/include/mlpack/methods/det/dt_utils.hpp deleted file mode 100644 index 4fb602fd4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/det/dt_utils.hpp +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @file dt_utils.hpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * - * This file implements functions to perform different tasks with the Density - * Tree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DET_DT_UTILS_HPP -#define MLPACK_METHODS_DET_DT_UTILS_HPP - -#include -#include "dtree.hpp" - -namespace mlpack { -namespace det { - -/** - * Print the membership of leaves of a density estimation tree given the labels - * and number of classes. Optionally, pass the name of a file to print this - * information to (otherwise stdout is used). - * - * @param dtree Tree to print membership of. - * @param data Dataset tree is built upon. - * @param labels Class labels of dataset. - * @param numClasses Number of classes in dataset. - * @param leafClassMembershipFile Name of file to print to (optional). - */ -template -void PrintLeafMembership(DTree* dtree, - const MatType& data, - const arma::Mat& labels, - const size_t numClasses, - const std::string& leafClassMembershipFile = ""); - -/** - * Print the variable importance of each dimension of a density estimation tree. - * Optionally, pass the name of a file to print this information to (otherwise - * stdout is used). - * - * @param dtree Density tree to use. - * @param viFile Name of file to print to (optional). - */ -template -void PrintVariableImportance(const DTree* dtree, - const std::string viFile = ""); - -/** - * Train the optimal decision tree using cross-validation with the given number - * of folds. Optionally, give a filename to print the unpruned tree to. This - * initializes a tree on the heap, so you are responsible for deleting it. - * - * @param dataset Dataset for the tree to use. - * @param folds Number of folds to use for cross-validation. - * @param useVolumeReg If true, use volume regularization. - * @param maxLeafSize Maximum number of points allowed in a leaf. - * @param minLeafSize Minimum number of points allowed in a leaf. - * @param unprunedTreeOutput Filename to print unpruned tree to (optional). - */ -template -DTree* Trainer(MatType& dataset, - const size_t folds, - const bool useVolumeReg = false, - const size_t maxLeafSize = 10, - const size_t minLeafSize = 5, - const std::string unprunedTreeOutput = "", - const bool skipPruning = false); - -/** - * This class is responsible for caching the path to each node of the tree. Its - * instance is provided to EnumerateTree() utility ONCE and it caches the paths - * to all the leafs and then easily (and quickly) retrieves these paths for each - * test entry. - */ -class PathCacher -{ - public: - /** - * Possible formats to use for output. - */ - enum PathFormat - { - //! Print only whether we went left or right. - FormatLR, - //! Print the direction, then the tag of the node. - FormatLR_ID, - //! Print the tag of the node, then the direction. - FormatID_LR - }; - - /** - * Construct a PathCacher object on the given tree with the given format. - * - * @param fmt Format to use for output. - * @param tree Tree to cache paths in. - */ - template - PathCacher(PathFormat fmt, DTree* tree); - - /** - * Enter a given node. - */ - template - void Enter(const DTree* node, - const DTree* parent); - - /** - * Leave the given node. - */ - template - void Leave(const DTree* node, - const DTree* parent); - - /** - * Return the constructed path for a given tag. - */ - inline const std::string& PathFor(int tag) const; - - /** - * Get the parent tag of a given tag. - */ - inline int ParentOf(int tag) const; - - /** - * Get the number of nodes in the path cache. - */ - size_t NumNodes() const { return pathCache.size(); } - - protected: - typedef std::list> PathType; - typedef std::vector> PathCacheType; - - PathType path; - PathFormat format; - PathCacheType pathCache; - - inline std::string BuildString(); -}; - -} // namespace det -} // namespace mlpack - -#include "dt_utils_impl.hpp" - -#endif // MLPACK_METHODS_DET_DT_UTILS_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/det/dt_utils_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/det/dt_utils_impl.hpp deleted file mode 100644 index 866413245..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/det/dt_utils_impl.hpp +++ /dev/null @@ -1,392 +0,0 @@ -/** - * @file dt_utils.cpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * - * This file implements functions to perform different tasks with the Density - * Tree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_DET_DT_UTILS_IMPL_HPP -#define MLPACK_METHODS_DET_DT_UTILS_IMPL_HPP - -#include "dt_utils.hpp" -#include - -namespace mlpack { -namespace det { - -template -void PrintLeafMembership(DTree* dtree, - const MatType& data, - const arma::Mat& labels, - const size_t numClasses, - const std::string& leafClassMembershipFile) -{ - // Tag the leaves with numbers. - int numLeaves = dtree->TagTree(); - - arma::Mat table(numLeaves, (numClasses + 1)); - table.zeros(); - - for (size_t i = 0; i < data.n_cols; i++) - { - const typename MatType::vec_type testPoint = data.unsafe_col(i); - const int leafTag = dtree->FindBucket(testPoint); - const size_t label = labels[i]; - table(leafTag, label) += 1; - } - - if (leafClassMembershipFile == "") - { - Log::Info << "Leaf membership; row represents leaf id, column represents " - << "class id; value represents number of points in leaf in class." - << std::endl << table; - } - else - { - // Create a stream for the file. - std::ofstream outfile(leafClassMembershipFile.c_str()); - if (outfile.good()) - { - outfile << table; - Log::Info << "Leaf membership printed to '" << leafClassMembershipFile - << "'." << std::endl; - } - else - { - Log::Warn << "Can't open '" << leafClassMembershipFile << "' to write " - << "leaf membership to." << std::endl; - } - outfile.close(); - } - - return; -} - -template -void PrintVariableImportance(const DTree* dtree, - const std::string viFile) -{ - arma::vec imps; - dtree->ComputeVariableImportance(imps); - - double max = 0.0; - for (size_t i = 0; i < imps.n_elem; ++i) - if (imps[i] > max) - max = imps[i]; - - Log::Info << "Maximum variable importance: " << max << "." << std::endl; - - if (viFile == "") - { - Log::Info << "Variable importance: " << std::endl << imps.t() << std::endl; - } - else - { - std::ofstream outfile(viFile.c_str()); - if (outfile.good()) - { - outfile << imps; - Log::Info << "Variable importance printed to '" << viFile << "'." - << std::endl; - } - else - { - Log::Warn << "Can't open '" << viFile << "' to write variable importance " - << "to." << std::endl; - } - outfile.close(); - } -} - - -// This function trains the optimal decision tree using the given number of -// folds. -template -DTree* Trainer(MatType& dataset, - const size_t folds, - const bool useVolumeReg, - const size_t maxLeafSize, - const size_t minLeafSize, - const bool skipPruning) -{ - // Initialize the tree. - DTree* dtree = new DTree(dataset); - - Timer::Start("tree_growing"); - // Prepare to grow the tree... - arma::Col oldFromNew(dataset.n_cols); - for (size_t i = 0; i < oldFromNew.n_elem; i++) - oldFromNew[i] = i; - - // Save the dataset since it would be modified while growing the tree. - MatType newDataset(dataset); - - // Growing the tree - double oldAlpha = 0.0; - double alpha = dtree->Grow(newDataset, oldFromNew, useVolumeReg, maxLeafSize, - minLeafSize); - - Timer::Stop("tree_growing"); - Log::Info << dtree->SubtreeLeaves() << " leaf nodes in the tree using full " - << "dataset; minimum alpha: " << alpha << "." << std::endl; - - if (skipPruning) - return dtree; - - if (folds == dataset.n_cols) - Log::Info << "Performing leave-one-out cross validation." << std::endl; - else - Log::Info << "Performing " << folds << "-fold cross validation." << - std::endl; - - Timer::Start("pruning_sequence"); - - // Sequentially prune and save the alpha values and the values of c_t^2 * r_t. - std::vector > prunedSequence; - while (dtree->SubtreeLeaves() > 1) - { - std::pair treeSeq(oldAlpha, - dtree->SubtreeLeavesLogNegError()); - prunedSequence.push_back(treeSeq); - oldAlpha = alpha; - alpha = dtree->PruneAndUpdate(oldAlpha, dataset.n_cols, useVolumeReg); - - // Some sanity checks. It seems that on some datasets, the error does not - // increase as the tree is pruned but instead stays the same---hence the - // "<=" in the final assert. - Log::Assert((alpha < std::numeric_limits::max()) - || (dtree->SubtreeLeaves() == 1)); - Log::Assert(alpha > oldAlpha); - Log::Assert(dtree->SubtreeLeavesLogNegError() <= treeSeq.second); - } - - std::pair treeSeq(oldAlpha, - dtree->SubtreeLeavesLogNegError()); - prunedSequence.push_back(treeSeq); - - Timer::Stop("pruning_sequence"); - Log::Info << prunedSequence.size() << " trees in the sequence; maximum alpha:" - << " " << oldAlpha << "." << std::endl; - - const MatType cvData(dataset); - const size_t testSize = dataset.n_cols / folds; - - arma::vec regularizationConstants(prunedSequence.size()); - regularizationConstants.fill(0.0); - - Timer::Start("cross_validation"); - // Go through each fold. On the Visual Studio compiler, we have to use - // intmax_t because size_t is not yet supported by their OpenMP - // implementation. omp_size_t is the appropriate type according to the - // platform. - #pragma omp parallel for default(none) \ - shared(prunedSequence, regularizationConstants) - for (omp_size_t fold = 0; fold < (omp_size_t) folds; fold++) - { - // Break up data into train and test sets. - const size_t start = fold * testSize; - const size_t end = std::min((size_t) (fold + 1) - * testSize, (size_t) cvData.n_cols); - - MatType test = cvData.cols(start, end - 1); - MatType train(cvData.n_rows, cvData.n_cols - test.n_cols); - - if (start == 0 && end < cvData.n_cols) - { - train.cols(0, train.n_cols - 1) = cvData.cols(end, cvData.n_cols - 1); - } - else if (start > 0 && end == cvData.n_cols) - { - train.cols(0, train.n_cols - 1) = cvData.cols(0, start - 1); - } - else - { - train.cols(0, start - 1) = cvData.cols(0, start - 1); - train.cols(start, train.n_cols - 1) = cvData.cols(end, cvData.n_cols - 1); - } - - // Initialize the tree. - DTree cvDTree(train); - - // Getting ready to grow the tree... - arma::Col cvOldFromNew(train.n_cols); - for (size_t i = 0; i < cvOldFromNew.n_elem; i++) - cvOldFromNew[i] = i; - - // Grow the tree. - cvDTree.Grow(train, cvOldFromNew, useVolumeReg, maxLeafSize, - minLeafSize); - - // Sequentially prune with all the values of available alphas and adding - // values for test values. Don't enter this loop if there are less than two - // trees in the pruned sequence. - arma::vec cvRegularizationConstants(prunedSequence.size()); - cvRegularizationConstants.fill(0.0); - for (size_t i = 0; - i < ((prunedSequence.size() < 2) ? 0 : prunedSequence.size() - 2); ++i) - { - // Compute test values for this state of the tree. - double cvVal = 0.0; - for (size_t j = 0; j < test.n_cols; j++) - { - arma::vec testPoint = test.unsafe_col(j); - cvVal += cvDTree.ComputeValue(testPoint); - } - - // Update the cv regularization constant. - cvRegularizationConstants[i] += 2.0 * cvVal / (double) cvData.n_cols; - - // Determine the new alpha value and prune accordingly. - double cvOldAlpha = 0.5 * (prunedSequence[i + 1].first - + prunedSequence[i + 2].first); - cvDTree.PruneAndUpdate(cvOldAlpha, train.n_cols, useVolumeReg); - } - - // Compute test values for this state of the tree. - double cvVal = 0.0; - for (size_t i = 0; i < test.n_cols; ++i) - { - typename MatType::vec_type testPoint = test.unsafe_col(i); - cvVal += cvDTree.ComputeValue(testPoint); - } - - if (prunedSequence.size() > 2) - cvRegularizationConstants[prunedSequence.size() - 2] += 2.0 * cvVal - / (double) cvData.n_cols; - - #pragma omp critical(DTreeCVUpdate) - regularizationConstants += cvRegularizationConstants; - } - Timer::Stop("cross_validation"); - - double optimalAlpha = -1.0; - long double cvBestError = -std::numeric_limits::max(); - - for (size_t i = 0; i < prunedSequence.size() - 1; ++i) - { - // We can no longer work in the log-space for this because we have no - // guarantee the quantity will be positive. - long double thisError = -std::exp((long double) prunedSequence[i].second) + - (long double) regularizationConstants[i]; - - if (thisError > cvBestError) - { - cvBestError = thisError; - optimalAlpha = prunedSequence[i].first; - } - } - - Log::Info << "Optimal alpha: " << optimalAlpha << "." << std::endl; - - // Re-Initialize the tree. - delete dtree; - dtree = new DTree(dataset); - - // Getting ready to grow the tree... - for (size_t i = 0; i < oldFromNew.n_elem; i++) - oldFromNew[i] = i; - - // Save the dataset since it would be modified while growing the tree. - newDataset = dataset; - - // Grow the tree. - oldAlpha = -DBL_MAX; - alpha = dtree->Grow(newDataset, - oldFromNew, - useVolumeReg, - maxLeafSize, - minLeafSize); - - // Prune with optimal alpha. - while ((oldAlpha < optimalAlpha) && (dtree->SubtreeLeaves() > 1)) - { - oldAlpha = alpha; - alpha = dtree->PruneAndUpdate(oldAlpha, newDataset.n_cols, useVolumeReg); - - // Some sanity checks. - Log::Assert((alpha < std::numeric_limits::max()) || - (dtree->SubtreeLeaves() == 1)); - Log::Assert(alpha > oldAlpha); - } - - Log::Info << dtree->SubtreeLeaves() << " leaf nodes in the optimally " - << "pruned tree; optimal alpha: " << oldAlpha << "." << std::endl; - - return dtree; -} - -template -PathCacher::PathCacher(PathCacher::PathFormat fmt, DTree* dtree) : - format(fmt) -{ - // Here we use TagTree()'s output to determine the - // number of _nodes_ in the tree. - pathCache.resize(dtree->TagTree(0, true)); - pathCache[0] = PathCacheType::value_type(-1, ""); - tree::EnumerateTree(dtree, *this); -} - -template -void PathCacher::Enter(const DTree* node, - const DTree* parent) -{ - if (parent == nullptr) - return; - - int tag = node->BucketTag(); - - path.push_back(PathType::value_type(parent->Left() == node, tag)); - pathCache[tag] = PathCacheType::value_type(parent->BucketTag(), - (node->SubtreeLeaves() > 1) ? - "" : BuildString()); -} - -template -void PathCacher::Leave(const DTree* /* node */, - const DTree* parent) -{ - if (parent != nullptr) - path.pop_back(); -} - -std::string PathCacher::BuildString() -{ - std::string str(""); - for (PathType::iterator it = path.begin(); it != path.end(); it++) - { - switch (format) - { - case FormatLR: - str += it->first ? "L" : "R"; - break; - case FormatLR_ID: - str += (it->first ? "L" : "R") + std::to_string(it->second); - break; - case FormatID_LR: - str += std::to_string(it->second) + (it->first ? "L" : "R"); - break; - } - } - - return str; -} - -int PathCacher::ParentOf(int tag) const -{ - return pathCache[tag].first; -} - -const std::string& PathCacher::PathFor(int tag) const -{ - return pathCache[tag].second; -} - -} // namespace det -} // namespace mlpack - -#endif // MLPACK_METHODS_DET_DT_UTILS_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/det/dtree.hpp b/src/sdk/mlpack/include/mlpack/methods/det/dtree.hpp deleted file mode 100644 index 012e02d67..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/det/dtree.hpp +++ /dev/null @@ -1,364 +0,0 @@ -/** - * @file dtree.hpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * - * Density Estimation Tree class - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_DET_DTREE_HPP -#define MLPACK_METHODS_DET_DTREE_HPP - -#include - -namespace mlpack { -namespace det /** Density Estimation Trees */ { - -/** - * A density estimation tree is similar to both a decision tree and a space - * partitioning tree (like a kd-tree). Each leaf represents a constant-density - * hyper-rectangle. The tree is constructed in such a way as to minimize the - * integrated square error between the probability distribution of the tree and - * the observed probability distribution of the data. Because the tree is - * similar to a decision tree, the density estimation tree can provide very fast - * density estimates for a given point. - * - * For more information, see the following paper: - * - * @code - * @incollection{ram2011, - * author = {Ram, Parikshit and Gray, Alexander G.}, - * title = {Density estimation trees}, - * booktitle = {{Proceedings of the 17th ACM SIGKDD International Conference - * on Knowledge Discovery and Data Mining}}, - * series = {KDD '11}, - * year = {2011}, - * pages = {627--635} - * } - * @endcode - */ -template -class DTree -{ - public: - //! The actual, underlying type we're working with. - typedef typename MatType::elem_type ElemType; - //! The type of vector we are using. - typedef typename MatType::vec_type VecType; - //! The statistic type we are holding. - typedef typename arma::Col StatType; - - /** - * Create an empty density estimation tree. - */ - DTree(); - - /** - * Create a tree that is the copy of the given tree. - * - * @param obj Tree to copy. - */ - DTree(const DTree& obj); - - /** - * Copy the given tree. - * - * @param obj Tree to copy. - */ - DTree& operator=(const DTree& obj); - - /** - * Create a tree by taking ownership of another tree (move constructor). - * - * @param obj Tree to take ownership of. - */ - DTree(DTree&& obj); - - /** - * Take ownership of the given tree (move operator). - * - * @param obj Tree to take ownership of. - */ - DTree& operator=(DTree&& obj); - - /** - * Create a density estimation tree with the given bounds and the given number - * of total points. Children will not be created. - * - * @param maxVals Maximum values of the bounding box. - * @param minVals Minimum values of the bounding box. - * @param totalPoints Total number of points in the dataset. - */ - DTree(const StatType& maxVals, - const StatType& minVals, - const size_t totalPoints); - - /** - * Create a density estimation tree on the given data. Children will be - * created following the procedure outlined in the paper. The data will be - * modified; it will be reordered similar to the way BinarySpaceTree modifies - * datasets. - * - * @param data Dataset to build tree on. - */ - DTree(MatType& data); - - /** - * Create a child node of a density estimation tree given the bounding box - * specified by maxVals and minVals, using the size given in start and end and - * the specified error. Children of this node will not be created - * recursively. - * - * @param maxVals Upper bound of bounding box. - * @param minVals Lower bound of bounding box. - * @param start Start of points represented by this node in the data matrix. - * @param end End of points represented by this node in the data matrix. - * @param error log-negative error of this node. - */ - DTree(const StatType& maxVals, - const StatType& minVals, - const size_t start, - const size_t end, - const double logNegError); - - /** - * Create a child node of a density estimation tree given the bounding box - * specified by maxVals and minVals, using the size given in start and end, - * and calculating the error with the total number of points given. Children - * of this node will not be created recursively. - * - * @param maxVals Upper bound of bounding box. - * @param minVals Lower bound of bounding box. - * @param start Start of points represented by this node in the data matrix. - * @param end End of points represented by this node in the data matrix. - */ - DTree(const StatType& maxVals, - const StatType& minVals, - const size_t totalPoints, - const size_t start, - const size_t end); - - //! Clean up memory allocated by the tree. - ~DTree(); - - /** - * Greedily expand the tree. The points in the dataset will be reordered - * during tree growth. - * - * @param data Dataset to build tree on. - * @param oldFromNew Mappings from old points to new points. - * @param useVolReg If true, volume regularization is used. - * @param maxLeafSize Maximum size of a leaf. - * @param minLeafSize Minimum size of a leaf. - */ - double Grow(MatType& data, - arma::Col& oldFromNew, - const bool useVolReg = false, - const size_t maxLeafSize = 10, - const size_t minLeafSize = 5); - - /** - * Perform alpha pruning on a tree. Returns the new value of alpha. - * - * @param oldAlpha Old value of alpha. - * @param points Total number of points in dataset. - * @param useVolReg If true, volume regularization is used. - * @return New value of alpha. - */ - double PruneAndUpdate(const double oldAlpha, - const size_t points, - const bool useVolReg = false); - - /** - * Compute the logarithm of the density estimate of a given query point. - * - * @param query Point to estimate density of. - */ - double ComputeValue(const VecType& query) const; - - /** - * Index the buckets for possible usage later; this results in every leaf in - * the tree having a specific tag (accessible with BucketTag()). This - * function calls itself recursively. The tag is incremented with - * `operator++()`, so any `TagType` overriding it will do. - * - * @param tag Tag for the next leaf; leave at 0 for the initial call. - * @param everyNodde Whether to increment on every node, not just leaves. - */ - TagType TagTree(const TagType& tag = 0, bool everyNode = false); - - - /** - * Return the tag of the leaf containing the query. This is useful for - * generating class memberships. - * - * @param query Query to search for. - */ - TagType FindBucket(const VecType& query) const; - - - /** - * Compute the variable importance of each dimension in the learned tree. - * - * @param importances Vector to store the calculated importances in. - */ - void ComputeVariableImportance(arma::vec& importances) const; - - /** - * Compute the log-negative-error for this point, given the total number of - * points in the dataset. - * - * @param totalPoints Total number of points in the dataset. - */ - double LogNegativeError(const size_t totalPoints) const; - - /** - * Return whether a query point is within the range of this node. - */ - bool WithinRange(const VecType& query) const; - - private: - // The indices in the complete set of points - // (after all forms of swapping in the original data - // matrix to align all the points in a node - // consecutively in the matrix. The 'old_from_new' array - // maps the points back to their original indices. - - //! The index of the first point in the dataset contained in this node (and - //! its children). - size_t start; - //! The index of the last point in the dataset contained in this node (and its - //! children). - size_t end; - - //! Upper half of bounding box for this node. - StatType maxVals; - //! Lower half of bounding box for this node. - StatType minVals; - - //! The splitting dimension for this node. - size_t splitDim; - - //! The split value on the splitting dimension for this node. - ElemType splitValue; - - //! log-negative-L2-error of the node. - double logNegError; - - //! Sum of the error of the leaves of the subtree. - double subtreeLeavesLogNegError; - - //! Number of leaves of the subtree. - size_t subtreeLeaves; - - //! If true, this node is the root of the tree. - bool root; - - //! Ratio of the number of points in the node to the total number of points. - double ratio; - - //! The logarithm of the volume of the node. - double logVolume; - - //! The tag for the leaf, used for hashing points. - TagType bucketTag; - - //! Upper part of alpha sum; used for pruning. - double alphaUpper; - - //! The left child. - DTree* left; - //! The right child. - DTree* right; - - public: - //! Return the starting index of points contained in this node. - size_t Start() const { return start; } - //! Return the first index of a point not contained in this node. - size_t End() const { return end; } - //! Return the split dimension of this node. - size_t SplitDim() const { return splitDim; } - //! Return the split value of this node. - ElemType SplitValue() const { return splitValue; } - //! Return the log negative error of this node. - double LogNegError() const { return logNegError; } - //! Return the log negative error of all descendants of this node. - double SubtreeLeavesLogNegError() const { return subtreeLeavesLogNegError; } - //! Return the number of leaves which are descendants of this node. - size_t SubtreeLeaves() const { return subtreeLeaves; } - //! Return the ratio of points in this node to the points in the whole - //! dataset. - double Ratio() const { return ratio; } - //! Return the inverse of the volume of this node. - double LogVolume() const { return logVolume; } - //! Return the left child. - DTree* Left() const { return left; } - //! Return the right child. - DTree* Right() const { return right; } - //! Return whether or not this is the root of the tree. - bool Root() const { return root; } - //! Return the upper part of the alpha sum. - double AlphaUpper() const { return alphaUpper; } - //! Return the current bucket's ID, if leaf, or -1 otherwise - TagType BucketTag() const { return bucketTag; } - //! Return the number of children in this node. - size_t NumChildren() const { return !left ? 0 : 2; } - - /** - * Return the specified child (0 will be left, 1 will be right). If the index - * is greater than 1, this will return the right child. - * - * @param child Index of child to return. - */ - DTree& Child(const size_t child) const { return !child ? *left : *right; } - - DTree*& ChildPtr(const size_t child) { return (!child) ? left : right; } - - //! Return the maximum values. - const StatType& MaxVals() const { return maxVals; } - - //! Return the minimum values. - const StatType& MinVals() const { return minVals; } - - /** - * Serialize the density estimation tree. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - // Utility methods. - - /** - * Find the dimension to split on. - */ - bool FindSplit(const MatType& data, - size_t& splitDim, - ElemType& splitValue, - double& leftError, - double& rightError, - const size_t minLeafSize = 5) const; - - /** - * Split the data, returning the number of points left of the split. - */ - size_t SplitData(MatType& data, - const size_t splitDim, - const ElemType splitValue, - arma::Col& oldFromNew) const; - - void FillMinMax(const StatType& mins, - const StatType& maxs); -}; - -} // namespace det -} // namespace mlpack - -#include "dtree_impl.hpp" - -#endif // MLPACK_METHODS_DET_DTREE_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/det/dtree_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/det/dtree_impl.hpp deleted file mode 100644 index 46cc5a1c0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/det/dtree_impl.hpp +++ /dev/null @@ -1,1044 +0,0 @@ -/** - * @file dtree.cpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * @author Ivan Georgiev (ivan@jonan.info) (sparsification and optimizations) - * - * Implementations of some declared functions in - * the Density Estimation Tree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#include "dtree.hpp" -#include -#include - -using namespace mlpack; -using namespace det; - -namespace details -{ - -/** - * This one sorts and scand the given per-dimension extract and puts all splits - * in a vector, that can easily be iterated afterwards. General implementation. - */ -template -void ExtractSplits(std::vector>& splitVec, - const MatType& data, - size_t dim, - const size_t start, - const size_t end, - const size_t minLeafSize) -{ - static_assert( - std::is_same::value == true, - "The ElemType does not correspond to the matrix's element type."); - - typedef std::pair SplitItem; - const typename MatType::row_type dimVec = - arma::sort(data(dim, arma::span(start, end - 1))); - - // Ensure the minimum leaf size on both sides. We need to figure out why there - // are spikes if this minLeafSize is enforced here... - for (size_t i = minLeafSize - 1; i < dimVec.n_elem - minLeafSize; ++i) - { - // This makes sense for real continuous data. This kinda corrupts the data - // and estimation if the data is ordinal. Potentially we can fix that by - // taking into account ordinality later in the min/max update, but then we - // can end-up with a zero-volumed dimension. No good. - const ElemType split = (dimVec[i] + dimVec[i + 1]) / 2.0; - - // Check if we can split here (two points are different) - if (split != dimVec[i]) - splitVec.push_back(SplitItem(split, i + 1)); - } -} - -// Now the custom arma::Mat implementation. -template -void ExtractSplits(std::vector>& splitVec, - const arma::Mat& data, - size_t dim, - const size_t start, - const size_t end, - const size_t minLeafSize) -{ - typedef std::pair SplitItem; - arma::rowvec dimVec = data(dim, arma::span(start, end - 1)); - - // We sort these, in-place (it's a copy of the data, anyways). - std::sort(dimVec.begin(), dimVec.end()); - - for (size_t i = minLeafSize - 1; i < dimVec.n_elem - minLeafSize; ++i) - { - // This makes sense for real continuous data. This kinda corrupts the data - // and estimation if the data is ordinal. Potentially we can fix that by - // taking into account ordinality later in the min/max update, but then we - // can end-up with a zero-volumed dimension. No good. - const ElemType split = (dimVec[i] + dimVec[i + 1]) / 2.0; - - if (split != dimVec[i]) - splitVec.push_back(SplitItem(split, i + 1)); - } -} - -// This the custom, sparse optimized implementation of the same routine. -template -void ExtractSplits(std::vector>& splitVec, - const arma::SpMat& data, - size_t dim, - const size_t start, - const size_t end, - const size_t minLeafSize) -{ - // It's common sense, but we also use it in a check later. - Log::Assert(minLeafSize > 0); - - typedef std::pair SplitItem; - const size_t n_elem = end - start; - - // Construct a vector of values. - const arma::SpRow row = data(dim, arma::span(start, end - 1)); - std::vector valsVec(row.begin(), row.end()); - - // ... and sort it! - std::sort(valsVec.begin(), valsVec.end()); - - // Now iterate over the values, taking account for the over-the-zeroes jump - // and construct the splits vector. - const size_t zeroes = n_elem - valsVec.size(); - ElemType lastVal = -std::numeric_limits::max(); - size_t padding = 0; - - for (size_t i = 0; i < valsVec.size(); ++i) - { - const ElemType newVal = valsVec[i]; - if (lastVal < ElemType(0) && newVal > ElemType(0) && zeroes > 0) - { - Log::Assert(padding == 0); // We should arrive here once! - - // The minLeafSize > 0 also guarantees we're not entering right at the - // start. - if (i >= minLeafSize && i <= n_elem - minLeafSize) - splitVec.push_back(SplitItem(lastVal / 2.0, i)); - - padding = zeroes; - lastVal = ElemType(0); - } - - // This is the normal case. - if (i + padding >= minLeafSize && i + padding <= n_elem - minLeafSize) - { - // This makes sense for real continuous data. This kinda corrupts the - // data and estimation if the data is ordinal. Potentially we can fix that - // by taking into account ordinality later in the min/max update, but then - // we can end-up with a zero-volumed dimension. No good. - const ElemType split = (lastVal + newVal) / 2.0; - - // Check if we can split here (two points are different) - if (split != newVal) - splitVec.push_back(SplitItem(split, i + padding)); - } - - lastVal = newVal; - } -} - -} // namespace details - -template -DTree::DTree() : - start(0), - end(0), - splitDim(size_t(-1)), - splitValue(std::numeric_limits::max()), - logNegError(-DBL_MAX), - subtreeLeavesLogNegError(-DBL_MAX), - subtreeLeaves(0), - root(true), - ratio(1.0), - logVolume(-DBL_MAX), - bucketTag(-1), - alphaUpper(0.0), - left(NULL), - right(NULL) -{ /* Nothing to do. */ } - -template -DTree::DTree(const DTree& obj) : - start(obj.start), - end(obj.end), - maxVals(obj.maxVals), - minVals(obj.minVals), - splitDim(obj.splitDim), - splitValue(obj.splitValue), - logNegError(obj.logNegError), - subtreeLeavesLogNegError(obj.subtreeLeavesLogNegError), - subtreeLeaves(obj.subtreeLeaves), - root(obj.root), - ratio(obj.ratio), - logVolume(obj.logVolume), - bucketTag(obj.bucketTag), - alphaUpper(obj.alphaUpper), - left((obj.left == NULL) ? NULL : new DTree(*obj.left)), - right((obj.right == NULL) ? NULL : new DTree(*obj.right)) -{ - /* Nothing to do. */ -} - -template -DTree& DTree::operator=( - const DTree& obj) -{ - if (this == &obj) - return *this; - - // Copy the values from the other tree. - start = obj.start; - end = obj.end; - maxVals = obj.maxVals; - minVals = obj.minVals; - splitDim = obj.splitDim; - splitValue = obj.splitValue; - logNegError = obj.logNegError; - subtreeLeavesLogNegError = obj.subtreeLeavesLogNegError; - subtreeLeaves = obj.subtreeLeaves; - root = obj.root; - ratio = obj.ratio; - logVolume = obj.logVolume; - bucketTag = obj.bucketTag; - alphaUpper = obj.alphaUpper; - - // Free the space allocated. - delete left; - delete right; - - // Copy the children. - left = ((obj.left == NULL) ? NULL : new DTree(*obj.left)); - right = ((obj.right == NULL) ? NULL : new DTree(*obj.right)); - - return *this; -} - -template -DTree::DTree(DTree&& obj): - start(obj.start), - end(obj.end), - maxVals(std::move(obj.maxVals)), - minVals(std::move(obj.minVals)), - splitDim(obj.splitDim), - splitValue(std::move(obj.splitValue)), - logNegError(obj.logNegError), - subtreeLeavesLogNegError(obj.subtreeLeavesLogNegError), - subtreeLeaves(obj.subtreeLeaves), - root(obj.root), - ratio(obj.ratio), - logVolume(obj.logVolume), - bucketTag(std::move(obj.bucketTag)), - alphaUpper(obj.alphaUpper), - left(obj.left), - right(obj.right) -{ - // Set obj to default values. - obj.start = 0; - obj.end = 0; - obj.splitDim = size_t(-1); - obj.splitValue = std::numeric_limits::max(); - obj.logNegError = -DBL_MAX; - obj.subtreeLeavesLogNegError = -DBL_MAX; - obj.subtreeLeaves = 0; - obj.root = true; - obj.ratio = 1.0; - obj.logVolume = -DBL_MAX; - obj.bucketTag = -1; - obj.alphaUpper = 0.0; - obj.left = NULL; - obj.right = NULL; -} - -template -DTree& DTree::operator=( - DTree&& obj) -{ - if (this == &obj) - return *this; - - // Move the values from the other tree. - start = obj.start; - end = obj.end; - splitDim = obj.splitDim; - logNegError = obj.logNegError; - subtreeLeavesLogNegError = obj.subtreeLeavesLogNegError; - subtreeLeaves = obj.subtreeLeaves; - root = obj.root; - ratio = obj.ratio; - logVolume = obj.logVolume; - alphaUpper = obj.alphaUpper; - maxVals = std::move(obj.maxVals); - minVals = std::move(obj.minVals); - splitValue = std::move(obj.splitValue); - bucketTag = std::move(obj.bucketTag); - - // Free the space allocated. - delete left; - delete right; - - // Move children. - left = obj.left; - right = obj.right; - - // Set obj to default values. - obj.start = 0; - obj.end = 0; - obj.splitDim = size_t(-1); - obj.splitValue = std::numeric_limits::max(); - obj.logNegError = -DBL_MAX; - obj.subtreeLeavesLogNegError = -DBL_MAX; - obj.subtreeLeaves = 0; - obj.root = true; - obj.ratio = 1.0; - obj.logVolume = -DBL_MAX; - obj.bucketTag = -1; - obj.alphaUpper = 0.0; - obj.left = NULL; - obj.right = NULL; - - return *this; -} - - -// Root node initializers. -template -DTree::DTree(const StatType& maxVals, - const StatType& minVals, - const size_t totalPoints) : - start(0), - end(totalPoints), - maxVals(maxVals), - minVals(minVals), - splitDim(size_t(-1)), - splitValue(std::numeric_limits::max()), - logNegError(LogNegativeError(totalPoints)), - subtreeLeavesLogNegError(-DBL_MAX), - subtreeLeaves(0), - root(true), - ratio(1.0), - logVolume(-DBL_MAX), - bucketTag(-1), - alphaUpper(0.0), - left(NULL), - right(NULL) -{ /* Nothing to do. */ } - -template -DTree::DTree(MatType & data) : - start(0), - end(data.n_cols), - maxVals(arma::max(data, 1)), - minVals(arma::min(data, 1)), - splitDim(size_t(-1)), - splitValue(std::numeric_limits::max()), - subtreeLeavesLogNegError(-DBL_MAX), - subtreeLeaves(0), - root(true), - ratio(1.0), - logVolume(-DBL_MAX), - bucketTag(-1), - alphaUpper(0.0), - left(NULL), - right(NULL) -{ - logNegError = LogNegativeError(data.n_cols); -} - -// Non-root node initializers. -template -DTree::DTree(const StatType& maxVals, - const StatType& minVals, - const size_t start, - const size_t end, - const double logNegError) : - start(start), - end(end), - maxVals(maxVals), - minVals(minVals), - splitDim(size_t(-1)), - splitValue(std::numeric_limits::max()), - logNegError(logNegError), - subtreeLeavesLogNegError(-DBL_MAX), - subtreeLeaves(0), - root(false), - ratio(1.0), - logVolume(-DBL_MAX), - bucketTag(-1), - alphaUpper(0.0), - left(NULL), - right(NULL) -{ /* Nothing to do. */ } - -template -DTree::DTree(const StatType& maxVals, - const StatType& minVals, - const size_t totalPoints, - const size_t start, - const size_t end) : - start(start), - end(end), - maxVals(maxVals), - minVals(minVals), - splitDim(size_t(-1)), - splitValue(std::numeric_limits::max()), - logNegError(LogNegativeError(totalPoints)), - subtreeLeavesLogNegError(-DBL_MAX), - subtreeLeaves(0), - root(false), - ratio(1.0), - logVolume(-DBL_MAX), - bucketTag(-1), - alphaUpper(0.0), - left(NULL), - right(NULL) -{ /* Nothing to do. */ } - -template -DTree::~DTree() -{ - delete left; - delete right; -} - -// This function computes the log-l2-negative-error of a given node from the -// formula R(t) = log(|t|^2 / (N^2 V_t)). -template -double DTree::LogNegativeError(const size_t totalPoints) const -{ - // log(-|t|^2 / (N^2 V_t)) = log(-1) + 2 log(|t|) - 2 log(N) - log(V_t). - double err = 2 * std::log((double) (end - start)) - - 2 * std::log((double) totalPoints); - - StatType valDiffs = maxVals - minVals; - for (size_t i = 0; i < valDiffs.n_elem; ++i) - { - // Ignore very small dimensions to prevent overflow. - if (valDiffs[i] > 1e-50) - err -= std::log(valDiffs[i]); - } - - return err; -} - -// This function finds the best split with respect to the L2-error, by trying -// all possible splits. The dataset is the full data set but the start and -// end are used to obtain the point in this node. -template -bool DTree::FindSplit(const MatType& data, - size_t& splitDim, - ElemType& splitValue, - double& leftError, - double& rightError, - const size_t minLeafSize) const -{ - typedef std::pair SplitItem; - - // Ensure the dimensionality of the data is the same as the dimensionality of - // the bounding rectangle. - Log::Assert(data.n_rows == maxVals.n_elem); - Log::Assert(data.n_rows == minVals.n_elem); - - const size_t points = end - start; - - double minError = logNegError; - bool splitFound = false; - - // Loop through each dimension. -#ifdef _WIN32 - #pragma omp parallel for default(shared) - for (intmax_t dim = 0; dim < (intmax_t) maxVals.n_elem; ++dim) -#else - #pragma omp parallel for default(shared) - for (size_t dim = 0; dim < maxVals.n_elem; ++dim) -#endif - { - const ElemType min = minVals[dim]; - const ElemType max = maxVals[dim]; - - // If there is nothing to split in this dimension, move on. - if (max - min == 0.0) - continue; // Skip to next dimension. - - // Find the log volume of all the other dimensions. - const double volumeWithoutDim = logVolume - std::log(max - min); - - // Initializing all other stuff for this dimension. - bool dimSplitFound = false; - // Take an error estimate for this dimension. - double minDimError = std::pow(points, 2.0) / (max - min); - double dimLeftError = 0.0; // For -Wuninitialized. These variables will - double dimRightError = 0.0; // always be set to something else before use. - ElemType dimSplitValue = 0.0; - - // Get the values for splitting. The old implementation: - // dimVec = data.row(dim).subvec(start, end - 1); - // dimVec = arma::sort(dimVec); - // could be quite inefficient for sparse matrices, due to - // copy operations (3). This one has custom implementation for dense and - // sparse matrices. - - std::vector splitVec; - details::ExtractSplits(splitVec, data, dim, start, end, - minLeafSize); - - // Iterate on all the splits for this dimension - for (typename std::vector::iterator i = splitVec.begin(); - i != splitVec.end(); - ++i) - { - const ElemType split = i->first; - const size_t position = i->second; - - // Another way of picking split is using this: - // split = leftsplit; - if ((split - min > 0.0) && (max - split > 0.0)) - { - // Ensure that the right node will have at least the minimum number of - // points. - Log::Assert((points - position) >= minLeafSize); - - // Now we have to see if the error will be reduced. Simple manipulation - // of the error function gives us the condition we must satisfy: - // |t_l|^2 / V_l + |t_r|^2 / V_r >= |t|^2 / (V_l + V_r) - // and because the volume is only dependent on the dimension we are - // splitting, we can assume V_l is just the range of the left and V_r is - // just the range of the right. - double negLeftError = std::pow(position, 2.0) / (split - min); - double negRightError = std::pow(points - position, 2.0) / (max - split); - - // If this is better, take it. - if ((negLeftError + negRightError) >= minDimError) - { - minDimError = negLeftError + negRightError; - dimLeftError = negLeftError; - dimRightError = negRightError; - dimSplitValue = split; - dimSplitFound = true; - } - } - } - - const double actualMinDimError = std::log(minDimError) - - 2 * std::log((double) data.n_cols) - - volumeWithoutDim; - -#pragma omp critical(DTreeFindUpdate) - if ((actualMinDimError > minError) && dimSplitFound) - { - // Calculate actual error (in logspace) by adding terms back to our - // estimate. - minError = actualMinDimError; - splitDim = dim; - splitValue = dimSplitValue; - leftError = std::log(dimLeftError) - 2 * std::log((double) data.n_cols) - - volumeWithoutDim; - rightError = std::log(dimRightError) - 2 * std::log((double) data.n_cols) - - volumeWithoutDim; - splitFound = true; - } // end if better split found in this dimension. - } - - return splitFound; -} - -template -size_t DTree::SplitData(MatType& data, - const size_t splitDim, - const ElemType splitValue, - arma::Col& oldFromNew) const -{ - // Swap all columns such that any columns with value in dimension splitDim - // less than or equal to splitValue are on the left side, and all others are - // on the right side. A similar sort to this is also performed in - // BinarySpaceTree construction (its comments are more detailed). - size_t left = start; - size_t right = end - 1; - for (;;) - { - while (data(splitDim, left) <= splitValue) - ++left; - while (data(splitDim, right) > splitValue) - --right; - - if (left > right) - break; - - data.swap_cols(left, right); - - // Store the mapping from old to new. Do not put std::swap here... - const size_t tmp = oldFromNew[left]; - oldFromNew[left] = oldFromNew[right]; - oldFromNew[right] = tmp; - } - - // This now refers to the first index of the "right" side. - return left; -} - -// Greedily expand the tree. -template -double DTree::Grow(MatType& data, - arma::Col& oldFromNew, - const bool useVolReg, - const size_t maxLeafSize, - const size_t minLeafSize) -{ - Log::Assert(data.n_rows == maxVals.n_elem); - Log::Assert(data.n_rows == minVals.n_elem); - - double leftG, rightG; - - // Compute points ratio. - ratio = (double) (end - start) / (double) oldFromNew.n_elem; - - // Compute the log of the volume of the node. - logVolume = 0; - for (size_t i = 0; i < maxVals.n_elem; ++i) - if (maxVals[i] - minVals[i] > 0.0) - logVolume += std::log(maxVals[i] - minVals[i]); - - // Check if node is large enough to split. - if ((size_t) (end - start) > maxLeafSize) - { - // Find the split. - size_t dim; - double splitValueTmp; - double leftError, rightError; - if (FindSplit(data, dim, splitValueTmp, leftError, rightError, minLeafSize)) - { - // Move the data around for the children to have points in a node lie - // contiguously (to increase efficiency during the training). - const size_t splitIndex = SplitData(data, dim, splitValueTmp, oldFromNew); - - // Make max and min vals for the children. - StatType maxValsL(maxVals); - StatType maxValsR(maxVals); - StatType minValsL(minVals); - StatType minValsR(minVals); - - maxValsL[dim] = splitValueTmp; - minValsR[dim] = splitValueTmp; - - // Store split dim and split val in the node. - splitValue = splitValueTmp; - splitDim = dim; - - // Recursively grow the children. - left = new DTree(maxValsL, minValsL, start, splitIndex, leftError); - right = new DTree(maxValsR, minValsR, splitIndex, end, rightError); - - leftG = left->Grow(data, oldFromNew, useVolReg, maxLeafSize, - minLeafSize); - rightG = right->Grow(data, oldFromNew, useVolReg, maxLeafSize, - minLeafSize); - - // Store values of R(T~) and |T~|. - subtreeLeaves = left->SubtreeLeaves() + right->SubtreeLeaves(); - - // Find the log negative error of the subtree leaves. This is kind of an - // odd one because we don't want to represent the error in non-log-space, - // but we have to calculate log(E_l + E_r). So we multiply E_l and E_r by - // V_t (remember E_l has an inverse relationship to the volume of the - // nodes) and then subtract log(V_t) at the end of the whole expression. - // As a result we do leave log-space, but the largest quantity we - // represent is on the order of (V_t / V_i) where V_i is the smallest leaf - // node below this node, which depends heavily on the depth of the tree. - subtreeLeavesLogNegError = std::log( - std::exp(logVolume + left->SubtreeLeavesLogNegError()) + - std::exp(logVolume + right->SubtreeLeavesLogNegError())) - - logVolume; - } - else - { - // No split found so make a leaf out of it. - subtreeLeaves = 1; - subtreeLeavesLogNegError = logNegError; - } - } - else - { - // We can make this a leaf node. - Log::Assert((size_t) (end - start) >= minLeafSize); - subtreeLeaves = 1; - subtreeLeavesLogNegError = logNegError; - } - - // If this is a leaf, do not compute g_k(t); otherwise compute, store, and - // propagate min(g_k(t_L), g_k(t_R), g_k(t)), unless t_L and/or t_R are - // leaves. - if (subtreeLeaves == 1) - { - return std::numeric_limits::max(); - } - else - { - const double range = maxVals[splitDim] - minVals[splitDim]; - const double leftRatio = (splitValue - minVals[splitDim]) / range; - const double rightRatio = (maxVals[splitDim] - splitValue) / range; - - const size_t leftPow = std::pow((double) (left->End() - left->Start()), 2); - const size_t rightPow = std::pow((double) (right->End() - right->Start()), - 2); - const size_t thisPow = std::pow((double) (end - start), 2); - - double tmpAlphaSum = leftPow / leftRatio + rightPow / rightRatio - thisPow; - - if (left->SubtreeLeaves() > 1) - { - const double exponent = 2 * std::log((double) data.n_cols) + logVolume + - left->AlphaUpper(); - - // Whether or not this will overflow is highly dependent on the depth of - // the tree. - tmpAlphaSum += std::exp(exponent); - } - - if (right->SubtreeLeaves() > 1) - { - const double exponent = 2 * std::log((double) data.n_cols) - + logVolume - + right->AlphaUpper(); - - tmpAlphaSum += std::exp(exponent); - } - - alphaUpper = std::log(tmpAlphaSum) - 2 * std::log((double) data.n_cols) - - logVolume; - - double gT; - if (useVolReg) - { - // This is wrong for now! - gT = alphaUpper; // / (subtreeLeavesVTInv - vTInv); - } - else - { - gT = alphaUpper - std::log((double) (subtreeLeaves - 1)); - } - - return std::min(gT, std::min(leftG, rightG)); - } - - // We need to compute (c_t^2) * r_t for all subtree leaves; this is equal to - // n_t ^ 2 / r_t * n ^ 2 = -error. Therefore the value we need is actually - // -1.0 * subtreeLeavesError. -} - - -template -double DTree::PruneAndUpdate(const double oldAlpha, - const size_t points, - const bool useVolReg) -{ - // Compute gT. - if (subtreeLeaves == 1) // If we are a leaf... - { - return std::numeric_limits::max(); - } - else - { - // Compute gT value for node t. - volatile double gT; - if (useVolReg) - gT = alphaUpper; // - std::log(subtreeLeavesVTInv - vTInv); - else - gT = alphaUpper - std::log((double) (subtreeLeaves - 1)); - - if (gT > oldAlpha) - { - // Go down the tree and update accordingly. Traverse the children. - double leftG = left->PruneAndUpdate(oldAlpha, points, useVolReg); - double rightG = right->PruneAndUpdate(oldAlpha, points, useVolReg); - - // Update values. - subtreeLeaves = left->SubtreeLeaves() + right->SubtreeLeaves(); - - // Find the log negative error of the subtree leaves. This is kind of an - // odd one because we don't want to represent the error in non-log-space, - // but we have to calculate log(E_l + E_r). So we multiply E_l and E_r by - // V_t (remember E_l has an inverse relationship to the volume of the - // nodes) and then subtract log(V_t) at the end of the whole expression. - // As a result we do leave log-space, but the largest quantity we - // represent is on the order of (V_t / V_i) where V_i is the smallest leaf - // node below this node, which depends heavily on the depth of the tree. - subtreeLeavesLogNegError = std::log( - std::exp(logVolume + left->SubtreeLeavesLogNegError()) + - std::exp(logVolume + right->SubtreeLeavesLogNegError())) - - logVolume; - - // Recalculate upper alpha. - const double range = maxVals[splitDim] - minVals[splitDim]; - const double leftRatio = (splitValue - minVals[splitDim]) / range; - const double rightRatio = (maxVals[splitDim] - splitValue) / range; - - const size_t leftPow = std::pow((double) (left->End() - left->Start()), - 2); - const size_t rightPow = std::pow((double) (right->End() - right->Start()), - 2); - const size_t thisPow = std::pow((double) (end - start), 2); - - double tmpAlphaSum = leftPow / leftRatio + rightPow / rightRatio - - thisPow; - - if (left->SubtreeLeaves() > 1) - { - const double exponent = 2 * std::log((double) points) + logVolume + - left->AlphaUpper(); - - // Whether or not this will overflow is highly dependent on the depth of - // the tree. - tmpAlphaSum += std::exp(exponent); - } - - if (right->SubtreeLeaves() > 1) - { - const double exponent = 2 * std::log((double) points) + logVolume + - right->AlphaUpper(); - - tmpAlphaSum += std::exp(exponent); - } - - alphaUpper = std::log(tmpAlphaSum) - 2 * std::log((double) points) - - logVolume; - - // Update gT value. - if (useVolReg) - { - // This is incorrect. - gT = alphaUpper; // / (subtreeLeavesVTInv - vTInv); - } - else - { - gT = alphaUpper - std::log((double) (subtreeLeaves - 1)); - } - - Log::Assert(gT < std::numeric_limits::max()); - - return std::min((double) gT, std::min(leftG, rightG)); - } - else - { - // Prune this subtree. - // First, make this node a leaf node. - subtreeLeaves = 1; - subtreeLeavesLogNegError = logNegError; - - delete left; - delete right; - - left = NULL; - right = NULL; - - // Pass information upward. - return std::numeric_limits::max(); - } - } -} - -// Check whether a given point is within the bounding box of this node (check -// generally done at the root, so its the bounding box of the data). -// -// Future improvement: Open up the range with epsilons on both sides where -// epsilon depends on the density near the boundary. -template -bool DTree::WithinRange(const VecType& query) const -{ - for (size_t i = 0; i < query.n_elem; ++i) - if ((query[i] < minVals[i]) || (query[i] > maxVals[i])) - return false; - - return true; -} - - -template -double DTree::ComputeValue(const VecType& query) const -{ - Log::Assert(query.n_elem == maxVals.n_elem); - - if (root == 1) // If we are the root... - { - // Check if the query is within range. - if (!WithinRange(query)) - return 0.0; - } - - if (subtreeLeaves == 1) // If we are a leaf... - { - return std::exp(std::log(ratio) - logVolume); - } - else - { - // Return either of the two children - left or right, depending on the - // splitValue - return (query[splitDim] <= splitValue) ? - left->ComputeValue(query) : - right->ComputeValue(query); - } - - return 0.0; -} - -// Index the buckets for possible usage later. -template -TagType DTree::TagTree(const TagType& tag, bool every) -{ - if (subtreeLeaves == 1) - { - // Only label leaves. - bucketTag = tag; - return (tag + 1); - } - - TagType nextTag; - if (every) - { - bucketTag = tag; - nextTag = (tag + 1); - } - else - nextTag = tag; - - return right->TagTree(left->TagTree(nextTag, every), every); -} - -template -TagType DTree::FindBucket(const VecType& query) const -{ - Log::Assert(query.n_elem == maxVals.n_elem); - - if (root == 1) // If we are the root... - { - // Check if the query is within range. - if (!WithinRange(query)) - return -1; - } - - // If we are a leaf... - if (subtreeLeaves == 1) - { - return bucketTag; - } - else - { - // Return the tag from either of the two children - left or right. - return (query[splitDim] <= splitValue) ? - left->FindBucket(query) : - right->FindBucket(query); - } -} - -template -void DTree::ComputeVariableImportance(arma::vec& importances) - const -{ - // Clear and set to right size. - importances.zeros(maxVals.n_elem); - - std::stack nodes; - nodes.push(this); - - while (!nodes.empty()) - { - const DTree& curNode = *nodes.top(); - nodes.pop(); - - if (curNode.subtreeLeaves == 1) - continue; // Do nothing for leaves. - - // The way to do this entirely in log-space is (at this time) somewhat - // unclear. So this risks overflow. - importances[curNode.SplitDim()] += (-std::exp(curNode.LogNegError()) - - (-std::exp(curNode.Left()->LogNegError()) + - -std::exp(curNode.Right()->LogNegError()))); - - nodes.push(curNode.Left()); - nodes.push(curNode.Right()); - } -} - -template -void DTree::FillMinMax(const StatType& mins, - const StatType& maxs) -{ - if (!root) - { - minVals = mins; - maxVals = maxs; - } - - if (left && right) - { - StatType maxValsL(maxs); - StatType maxValsR(maxs); - StatType minValsL(mins); - StatType minValsR(mins); - - maxValsL[splitDim] = minValsR[splitDim] = splitValue; - left->FillMinMax(minValsL, maxValsL); - right->FillMinMax(minValsR, maxValsR); - } -} - -template -template -void DTree::serialize(Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(start); - ar & BOOST_SERIALIZATION_NVP(end); - ar & BOOST_SERIALIZATION_NVP(maxVals); - ar & BOOST_SERIALIZATION_NVP(minVals); - ar & BOOST_SERIALIZATION_NVP(splitDim); - ar & BOOST_SERIALIZATION_NVP(splitValue); - ar & BOOST_SERIALIZATION_NVP(logNegError); - ar & BOOST_SERIALIZATION_NVP(subtreeLeavesLogNegError); - ar & BOOST_SERIALIZATION_NVP(subtreeLeaves); - ar & BOOST_SERIALIZATION_NVP(root); - ar & BOOST_SERIALIZATION_NVP(ratio); - ar & BOOST_SERIALIZATION_NVP(logVolume); - ar & BOOST_SERIALIZATION_NVP(bucketTag); - ar & BOOST_SERIALIZATION_NVP(alphaUpper); - - if (Archive::is_loading::value) - { - if (left) - delete left; - if (right) - delete right; - - left = NULL; - right = NULL; - } - - bool hasLeft = (left != NULL); - bool hasRight = (right != NULL); - - ar & BOOST_SERIALIZATION_NVP(hasLeft); - ar & BOOST_SERIALIZATION_NVP(hasRight); - - if (hasLeft) - ar & BOOST_SERIALIZATION_NVP(left); - if (hasRight) - ar & BOOST_SERIALIZATION_NVP(right); - - if (root) - { - ar & BOOST_SERIALIZATION_NVP(maxVals); - ar & BOOST_SERIALIZATION_NVP(minVals); - - // This is added in order to reduce (dramatically!) the model file size. - if (Archive::is_loading::value && left && right) - FillMinMax(minVals, maxVals); - } -} diff --git a/src/sdk/mlpack/include/mlpack/methods/emst/dtb.hpp b/src/sdk/mlpack/include/mlpack/methods/emst/dtb.hpp deleted file mode 100644 index 4b05bb4ca..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/emst/dtb.hpp +++ /dev/null @@ -1,212 +0,0 @@ -/** - * @file dtb.hpp - * @author Bill March (march@gatech.edu) - * - * Contains an implementation of the DualTreeBoruvka algorithm for finding a - * Euclidean Minimum Spanning Tree using the kd-tree data structure. - * - * @code - * @inproceedings{ - * author = {March, W.B., Ram, P., and Gray, A.G.}, - * title = {{Fast Euclidean Minimum Spanning Tree: Algorithm, Analysis, - * Applications.}}, - * booktitle = {Proceedings of the 16th ACM SIGKDD International Conference - * on Knowledge Discovery and Data Mining} - * series = {KDD 2010}, - * year = {2010} - * } - * @endcode - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_EMST_DTB_HPP -#define MLPACK_METHODS_EMST_DTB_HPP - -#include "dtb_stat.hpp" -#include "edge_pair.hpp" - -#include -#include - -#include - -namespace mlpack { -namespace emst /** Euclidean Minimum Spanning Trees. */ { - -/** - * Performs the MST calculation using the Dual-Tree Boruvka algorithm, using any - * type of tree. - * - * For more information on the algorithm, see the following citation: - * - * @code - * @inproceedings{ - * author = {March, W.B., Ram, P., and Gray, A.G.}, - * title = {{Fast Euclidean Minimum Spanning Tree: Algorithm, Analysis, - * Applications.}}, - * booktitle = {Proceedings of the 16th ACM SIGKDD International Conference - * on Knowledge Discovery and Data Mining} - * series = {KDD 2010}, - * year = {2010} - * } - * @endcode - * - * General usage of this class might be like this: - * - * @code - * extern arma::mat data; // We want to find the MST of this dataset. - * DualTreeBoruvka<> dtb(data); // Create the tree with default options. - * - * // Find the MST. - * arma::mat mstResults; - * dtb.ComputeMST(mstResults); - * @endcode - * - * More advanced usage of the class can use different types of trees, pass in an - * already-built tree, or compute the MST using the O(n^2) naive algorithm. - * - * @tparam MetricType The metric to use. - * @tparam MatType The type of data matrix to use. - * @tparam TreeType Type of tree to use. This should follow the TreeType policy - * API. - */ -template< - typename MetricType = metric::EuclideanDistance, - typename MatType = arma::mat, - template class TreeType = tree::KDTree -> -class DualTreeBoruvka -{ - public: - //! Convenience typedef. - typedef TreeType Tree; - - private: - //! Permutations of points during tree building. - std::vector oldFromNew; - //! Pointer to the root of the tree. - Tree* tree; - //! Reference to the data (this is what should be used for accessing data). - const MatType& data; - //! Indicates whether or not we "own" the tree. - bool ownTree; - - //! Indicates whether or not O(n^2) naive mode will be used. - bool naive; - - //! Edges. - std::vector edges; // We must use vector with non-numerical types. - - //! Connections. - UnionFind connections; - - //! List of edge nodes. - arma::Col neighborsInComponent; - //! List of edge nodes. - arma::Col neighborsOutComponent; - //! List of edge distances. - arma::vec neighborsDistances; - - //! Total distance of the tree. - double totalDist; - - //! The instantiated metric. - MetricType metric; - - //! For sorting the edge list after the computation. - struct SortEdgesHelper - { - bool operator()(const EdgePair& pairA, const EdgePair& pairB) - { - return (pairA.Distance() < pairB.Distance()); - } - } SortFun; - - public: - /** - * Create the tree from the given dataset. This copies the dataset to an - * internal copy, because tree-building modifies the dataset. - * - * @param data Dataset to build a tree for. - * @param naive Whether the computation should be done in O(n^2) naive mode. - * @param metric An optional instantiated metric to use. - */ - DualTreeBoruvka(const MatType& dataset, - const bool naive = false, - const MetricType metric = MetricType()); - - /** - * Create the DualTreeBoruvka object with an already initialized tree. This - * will not copy the dataset, and can save a little processing power. Naive - * mode is not available as an option for this constructor; instead, to run - * naive computation, construct a tree with all the points in one leaf (i.e. - * leafSize = number of points). - * - * @note - * Because tree-building (at least with BinarySpaceTree) modifies the ordering - * of a matrix, be sure you pass the modified matrix to this object! In - * addition, mapping the points of the matrix back to their original indices - * is not done when this constructor is used. - * @endnote - * - * @param tree Pre-built tree. - * @param metric An optional instantiated metric to use. - */ - DualTreeBoruvka(Tree* tree, - const MetricType metric = MetricType()); - - /** - * Delete the tree, if it was created inside the object. - */ - ~DualTreeBoruvka(); - - /** - * Iteratively find the nearest neighbor of each component until the MST is - * complete. The results will be a 3xN matrix (with N equal to the number of - * edges in the minimum spanning tree). The first row will contain the lesser - * index of the edge; the second row will contain the greater index of the - * edge; and the third row will contain the distance between the two edges. - * - * @param results Matrix which results will be stored in. - */ - void ComputeMST(arma::mat& results); - - private: - /** - * Adds a single edge to the edge list - */ - void AddEdge(const size_t e1, const size_t e2, const double distance); - - /** - * Adds all the edges found in one iteration to the list of neighbors. - */ - void AddAllEdges(); - - /** - * Unpermute the edge list and output it to results. - */ - void EmitResults(arma::mat& results); - - /** - * This function resets the values in the nodes of the tree nearest neighbor - * distance, and checks for fully connected nodes. - */ - void CleanupHelper(Tree* tree); - - /** - * The values stored in the tree must be reset on each iteration. - */ - void Cleanup(); -}; // class DualTreeBoruvka - -} // namespace emst -} // namespace mlpack - -#include "dtb_impl.hpp" - -#endif // MLPACK_METHODS_EMST_DTB_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/emst/dtb_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/emst/dtb_impl.hpp deleted file mode 100644 index a5ba58a31..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/emst/dtb_impl.hpp +++ /dev/null @@ -1,331 +0,0 @@ -/** - * @file dtb_impl.hpp - * @author Bill March (march@gatech.edu) - * - * Implementation of DTB. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_EMST_DTB_IMPL_HPP -#define MLPACK_METHODS_EMST_DTB_IMPL_HPP - -#include "dtb_rules.hpp" - -namespace mlpack { -namespace emst { - -//! Call the tree constructor that does mapping. -template -TreeType* BuildTree( - MatType&& dataset, - std::vector& oldFromNew, - const typename std::enable_if< - tree::TreeTraits::RearrangesDataset>::type* = 0) -{ - return new TreeType(std::forward(dataset), oldFromNew); -} - -//! Call the tree constructor that does not do mapping. -template -TreeType* BuildTree( - MatType&& dataset, - const std::vector& /* oldFromNew */, - const typename std::enable_if< - !tree::TreeTraits::RearrangesDataset>::type* = 0) -{ - return new TreeType(std::forward(dataset)); -} - -/** - * Takes in a reference to the data set. Copies the data, builds the tree, - * and initializes all of the member variables. - */ -template< - typename MetricType, - typename MatType, - template class TreeType> -DualTreeBoruvka::DualTreeBoruvka( - const MatType& dataset, - const bool naive, - const MetricType metric) : - tree(naive ? NULL : BuildTree(dataset, oldFromNew)), - data(naive ? dataset : tree->Dataset()), - ownTree(!naive), - naive(naive), - connections(dataset.n_cols), - totalDist(0.0), - metric(metric) -{ - edges.reserve(data.n_cols - 1); // Set size. - - neighborsInComponent.set_size(data.n_cols); - neighborsOutComponent.set_size(data.n_cols); - neighborsDistances.set_size(data.n_cols); - neighborsDistances.fill(DBL_MAX); -} - -template< - typename MetricType, - typename MatType, - template class TreeType> -DualTreeBoruvka::DualTreeBoruvka( - Tree* tree, - const MetricType metric) : - tree(tree), - data(tree->Dataset()), - ownTree(false), - naive(false), - connections(data.n_cols), - totalDist(0.0), - metric(metric) -{ - edges.reserve(data.n_cols - 1); // Fill with EdgePairs. - - neighborsInComponent.set_size(data.n_cols); - neighborsOutComponent.set_size(data.n_cols); - neighborsDistances.set_size(data.n_cols); - neighborsDistances.fill(DBL_MAX); -} - -template< - typename MetricType, - typename MatType, - template class TreeType> -DualTreeBoruvka::~DualTreeBoruvka() -{ - if (ownTree) - delete tree; -} - -/** - * Iteratively find the nearest neighbor of each component until the MST is - * complete. - */ -template< - typename MetricType, - typename MatType, - template class TreeType> -void DualTreeBoruvka::ComputeMST( - arma::mat& results) -{ - Timer::Start("emst/mst_computation"); - - totalDist = 0; // Reset distance. - - typedef DTBRules RuleType; - RuleType rules(data, connections, neighborsDistances, neighborsInComponent, - neighborsOutComponent, metric); - while (edges.size() < (data.n_cols - 1)) - { - if (naive) - { - // Full O(N^2) traversal. - for (size_t i = 0; i < data.n_cols; ++i) - for (size_t j = 0; j < data.n_cols; ++j) - rules.BaseCase(i, j); - } - else - { - typename Tree::template DualTreeTraverser traverser(rules); - traverser.Traverse(*tree, *tree); - } - - AddAllEdges(); - - Cleanup(); - - Log::Info << edges.size() << " edges found so far." << std::endl; - if (!naive) - { - Log::Info << rules.BaseCases() << " cumulative base cases." << std::endl; - Log::Info << rules.Scores() << " cumulative node combinations scored." - << std::endl; - } - } - - Timer::Stop("emst/mst_computation"); - - EmitResults(results); - - Log::Info << "Total spanning tree length: " << totalDist << std::endl; -} - -/** - * Adds a single edge to the edge list - */ -template< - typename MetricType, - typename MatType, - template class TreeType> -void DualTreeBoruvka::AddEdge( - const size_t e1, - const size_t e2, - const double distance) -{ - Log::Assert((distance >= 0.0), - "DualTreeBoruvka::AddEdge(): distance cannot be negative."); - - if (e1 < e2) - edges.push_back(EdgePair(e1, e2, distance)); - else - edges.push_back(EdgePair(e2, e1, distance)); -} - -/** - * Adds all the edges found in one iteration to the list of neighbors. - */ -template< - typename MetricType, - typename MatType, - template class TreeType> -void DualTreeBoruvka::AddAllEdges() -{ - for (size_t i = 0; i < data.n_cols; i++) - { - size_t component = connections.Find(i); - size_t inEdge = neighborsInComponent[component]; - size_t outEdge = neighborsOutComponent[component]; - if (connections.Find(inEdge) != connections.Find(outEdge)) - { - // totalDist = totalDist + dist; - // changed to make this agree with the cover tree code - totalDist += neighborsDistances[component]; - AddEdge(inEdge, outEdge, neighborsDistances[component]); - connections.Union(inEdge, outEdge); - } - } -} - -/** - * Unpermute the edge list (if necessary) and output it to results. - */ -template< - typename MetricType, - typename MatType, - template class TreeType> -void DualTreeBoruvka::EmitResults( - arma::mat& results) -{ - // Sort the edges. - std::sort(edges.begin(), edges.end(), SortFun); - - Log::Assert(edges.size() == data.n_cols - 1); - results.set_size(3, edges.size()); - - // Need to unpermute the point labels. - if (!naive && ownTree && tree::TreeTraits::RearrangesDataset) - { - for (size_t i = 0; i < (data.n_cols - 1); i++) - { - // Make sure the edge list stores the smaller index first to - // make checking correctness easier - size_t ind1 = oldFromNew[edges[i].Lesser()]; - size_t ind2 = oldFromNew[edges[i].Greater()]; - - if (ind1 < ind2) - { - edges[i].Lesser() = ind1; - edges[i].Greater() = ind2; - } - else - { - edges[i].Lesser() = ind2; - edges[i].Greater() = ind1; - } - - results(0, i) = edges[i].Lesser(); - results(1, i) = edges[i].Greater(); - results(2, i) = edges[i].Distance(); - } - } - else - { - for (size_t i = 0; i < edges.size(); i++) - { - results(0, i) = edges[i].Lesser(); - results(1, i) = edges[i].Greater(); - results(2, i) = edges[i].Distance(); - } - } -} - -/** - * This function resets the values in the nodes of the tree nearest neighbor - * distance and checks for fully connected nodes. - */ -template< - typename MetricType, - typename MatType, - template class TreeType> -void DualTreeBoruvka::CleanupHelper(Tree* tree) -{ - // Reset the statistic information. - tree->Stat().MaxNeighborDistance() = DBL_MAX; - tree->Stat().MinNeighborDistance() = DBL_MAX; - tree->Stat().Bound() = DBL_MAX; - - // Recurse into all children. - for (size_t i = 0; i < tree->NumChildren(); ++i) - CleanupHelper(&tree->Child(i)); - - // Get the component of the first child or point. Then we will check to see - // if all other components of children and points are the same. - const int component = (tree->NumChildren() != 0) ? - tree->Child(0).Stat().ComponentMembership() : - connections.Find(tree->Point(0)); - - // Check components of children. - for (size_t i = 0; i < tree->NumChildren(); ++i) - if (tree->Child(i).Stat().ComponentMembership() != component) - return; - - // Check components of points. - for (size_t i = 0; i < tree->NumPoints(); ++i) - if (connections.Find(tree->Point(i)) != size_t(component)) - return; - - // If we made it this far, all components are the same. - tree->Stat().ComponentMembership() = component; -} - -/** - * The values stored in the tree must be reset on each iteration. - */ -template< - typename MetricType, - typename MatType, - template class TreeType> -void DualTreeBoruvka::Cleanup() -{ - for (size_t i = 0; i < data.n_cols; i++) - neighborsDistances[i] = DBL_MAX; - - if (!naive) - CleanupHelper(tree); -} - -} // namespace emst -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/emst/dtb_rules.hpp b/src/sdk/mlpack/include/mlpack/methods/emst/dtb_rules.hpp deleted file mode 100644 index b89c5b475..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/emst/dtb_rules.hpp +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @file dtb.hpp - * @author Bill March (march@gatech.edu) - * - * Tree traverser rules for the DualTreeBoruvka algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_EMST_DTB_RULES_HPP -#define MLPACK_METHODS_EMST_DTB_RULES_HPP - -#include - -#include - -namespace mlpack { -namespace emst { - -template -class DTBRules -{ - public: - DTBRules(const arma::mat& dataSet, - UnionFind& connections, - arma::vec& neighborsDistances, - arma::Col& neighborsInComponent, - arma::Col& neighborsOutComponent, - MetricType& metric); - - double BaseCase(const size_t queryIndex, const size_t referenceIndex); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - */ - double Score(const size_t queryIndex, TreeType& referenceNode); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). This is used when the score has already - * been calculated, but another recursion may have modified the bounds for - * pruning. So the old score is checked against the new pruning bound. - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - * @param oldScore Old score produced by Score() (or Rescore()). - */ - double Rescore(const size_t queryIndex, - TreeType& referenceNode, - const double oldScore); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursionm while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - */ - double Score(TreeType& queryNode, TreeType& referenceNode); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). This is used when the score has already - * been calculated, but another recursion may have modified the bounds for - * pruning. So the old score is checked against the new pruning bound. - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - * @param oldScore Old score produced by Socre() (or Rescore()). - */ - double Rescore(TreeType& queryNode, - TreeType& referenceNode, - const double oldScore) const; - - typedef typename tree::TraversalInfo TraversalInfoType; - - const TraversalInfoType& TraversalInfo() const { return traversalInfo; } - TraversalInfoType& TraversalInfo() { return traversalInfo; } - - //! Get the number of base cases performed. - size_t BaseCases() const { return baseCases; } - //! Modify the number of base cases performed. - size_t& BaseCases() { return baseCases; } - - //! Get the number of node combinations that have been scored. - size_t Scores() const { return scores; } - //! Modify the number of node combinations that have been scored. - size_t& Scores() { return scores; } - - private: - //! The data points. - const arma::mat& dataSet; - - //! Stores the tree structure so far - UnionFind& connections; - - //! The distance to the candidate nearest neighbor for each component. - arma::vec& neighborsDistances; - - //! The index of the point in the component that is an endpoint of the - //! candidate edge. - arma::Col& neighborsInComponent; - - //! The index of the point outside of the component that is an endpoint - //! of the candidate edge. - arma::Col& neighborsOutComponent; - - //! The instantiated metric. - MetricType& metric; - - /** - * Update the bound for the given query node. - */ - inline double CalculateBound(TreeType& queryNode) const; - - TraversalInfoType traversalInfo; - - //! The number of base cases calculated. - size_t baseCases; - //! The number of node combinations that have been scored. - size_t scores; -}; // class DTBRules - -} // namespace emst -} // namespace mlpack - -#include "dtb_rules_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/emst/dtb_rules_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/emst/dtb_rules_impl.hpp deleted file mode 100644 index 7bd070711..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/emst/dtb_rules_impl.hpp +++ /dev/null @@ -1,197 +0,0 @@ -/** - * @file dtb_impl.hpp - * @author Bill March (march@gatech.edu) - * - * Tree traverser rules for the DualTreeBoruvka algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_EMST_DTB_RULES_IMPL_HPP -#define MLPACK_METHODS_EMST_DTB_RULES_IMPL_HPP - -namespace mlpack { -namespace emst { - -template -DTBRules:: -DTBRules(const arma::mat& dataSet, - UnionFind& connections, - arma::vec& neighborsDistances, - arma::Col& neighborsInComponent, - arma::Col& neighborsOutComponent, - MetricType& metric) -: - dataSet(dataSet), - connections(connections), - neighborsDistances(neighborsDistances), - neighborsInComponent(neighborsInComponent), - neighborsOutComponent(neighborsOutComponent), - metric(metric), - baseCases(0), - scores(0) -{ - // Nothing else to do. -} - -template -inline force_inline -double DTBRules::BaseCase(const size_t queryIndex, - const size_t referenceIndex) -{ - // Check if the points are in the same component at this iteration. - // If not, return the distance between them. Also, store a better result as - // the current neighbor, if necessary. - double newUpperBound = -1.0; - - // Find the index of the component the query is in. - size_t queryComponentIndex = connections.Find(queryIndex); - - size_t referenceComponentIndex = connections.Find(referenceIndex); - - if (queryComponentIndex != referenceComponentIndex) - { - ++baseCases; - double distance = metric.Evaluate(dataSet.col(queryIndex), - dataSet.col(referenceIndex)); - - if (distance < neighborsDistances[queryComponentIndex]) - { - Log::Assert(queryIndex != referenceIndex); - - neighborsDistances[queryComponentIndex] = distance; - neighborsInComponent[queryComponentIndex] = queryIndex; - neighborsOutComponent[queryComponentIndex] = referenceIndex; - } - } - - if (newUpperBound < neighborsDistances[queryComponentIndex]) - newUpperBound = neighborsDistances[queryComponentIndex]; - - Log::Assert(newUpperBound >= 0.0); - - return newUpperBound; -} - -template -double DTBRules::Score(const size_t queryIndex, - TreeType& referenceNode) -{ - size_t queryComponentIndex = connections.Find(queryIndex); - - // If the query belongs to the same component as all of the references, - // then prune. The cast is to stop a warning about comparing unsigned to - // signed values. - if (queryComponentIndex == - (size_t) referenceNode.Stat().ComponentMembership()) - return DBL_MAX; - - const arma::vec queryPoint = dataSet.unsafe_col(queryIndex); - const double distance = referenceNode.MinDistance(queryPoint); - - // If all the points in the reference node are farther than the candidate - // nearest neighbor for the query's component, we prune. - return neighborsDistances[queryComponentIndex] < distance - ? DBL_MAX : distance; -} - -template -double DTBRules::Rescore(const size_t queryIndex, - TreeType& /* referenceNode */, - const double oldScore) -{ - // We don't need to check component membership again, because it can't - // change inside a single iteration. - return (oldScore > neighborsDistances[connections.Find(queryIndex)]) - ? DBL_MAX : oldScore; -} - -template -double DTBRules::Score(TreeType& queryNode, - TreeType& referenceNode) -{ - // If all the queries belong to the same component as all the references - // then we prune. - if ((queryNode.Stat().ComponentMembership() >= 0) && - (queryNode.Stat().ComponentMembership() == - referenceNode.Stat().ComponentMembership())) - return DBL_MAX; - - ++scores; - const double distance = queryNode.MinDistance(referenceNode); - const double bound = CalculateBound(queryNode); - - // If all the points in the reference node are farther than the candidate - // nearest neighbor for all queries in the node, we prune. - return (bound < distance) ? DBL_MAX : distance; -} - -template -double DTBRules::Rescore(TreeType& queryNode, - TreeType& /* referenceNode */, - const double oldScore) const -{ - const double bound = CalculateBound(queryNode); - return (oldScore > bound) ? DBL_MAX : oldScore; -} - -// Calculate the bound for a given query node in its current state and update -// it. -template -inline double DTBRules::CalculateBound( - TreeType& queryNode) const -{ - double worstPointBound = -DBL_MAX; - double bestPointBound = DBL_MAX; - - double worstChildBound = -DBL_MAX; - double bestChildBound = DBL_MAX; - - // Now, find the best and worst point bounds. - for (size_t i = 0; i < queryNode.NumPoints(); ++i) - { - const size_t pointComponent = connections.Find(queryNode.Point(i)); - const double bound = neighborsDistances[pointComponent]; - - if (bound > worstPointBound) - worstPointBound = bound; - if (bound < bestPointBound) - bestPointBound = bound; - } - - // Find the best and worst child bounds. - for (size_t i = 0; i < queryNode.NumChildren(); ++i) - { - const double maxBound = queryNode.Child(i).Stat().MaxNeighborDistance(); - if (maxBound > worstChildBound) - worstChildBound = maxBound; - - const double minBound = queryNode.Child(i).Stat().MinNeighborDistance(); - if (minBound < bestChildBound) - bestChildBound = minBound; - } - - // Now calculate the actual bounds. - const double worstBound = std::max(worstPointBound, worstChildBound); - const double bestBound = std::min(bestPointBound, bestChildBound); - // We must check that bestBound != DBL_MAX; otherwise, we risk overflow. - const double bestAdjustedBound = (bestBound == DBL_MAX) ? DBL_MAX : - bestBound + 2 * queryNode.FurthestDescendantDistance(); - - // Update the relevant quantities in the node. - queryNode.Stat().MaxNeighborDistance() = worstBound; - queryNode.Stat().MinNeighborDistance() = bestBound; - queryNode.Stat().Bound() = std::min(worstBound, bestAdjustedBound); - - return queryNode.Stat().Bound(); -} - -} // namespace emst -} // namespace mlpack - - - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/emst/dtb_stat.hpp b/src/sdk/mlpack/include/mlpack/methods/emst/dtb_stat.hpp deleted file mode 100644 index 020a953a8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/emst/dtb_stat.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @file dtb.hpp - * @author Bill March (march@gatech.edu) - * - * DTBStat is the StatisticType used by trees when performing EMST. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_EMST_DTB_STAT_HPP -#define MLPACK_METHODS_EMST_DTB_STAT_HPP - -#include - -namespace mlpack { -namespace emst { - -/** - * A statistic for use with mlpack trees, which stores the upper bound on - * distance to nearest neighbors and the component which this node belongs to. - */ -class DTBStat -{ - private: - //! Upper bound on the distance to the nearest neighbor of any point in this - //! node. - double maxNeighborDistance; - - //! Lower bound on the distance to the nearest neighbor of any point in this - //! node. - double minNeighborDistance; - - //! Total bound for pruning. - double bound; - - //! The index of the component that all points in this node belong to. This - //! is the same index returned by UnionFind for all points in this node. If - //! points in this node are in different components, this value will be - //! negative. - int componentMembership; - - public: - /** - * A generic initializer. Sets the maximum neighbor distance to its default, - * and the component membership to -1 (no component). - */ - DTBStat() : - maxNeighborDistance(DBL_MAX), - minNeighborDistance(DBL_MAX), - bound(DBL_MAX), - componentMembership(-1) { } - - /** - * This is called when a node is finished initializing. We set the maximum - * neighbor distance to its default, and if possible, we set the component - * membership of the node (if it has only one point and no children). - * - * @param node Node that has been finished. - */ - template - DTBStat(const TreeType& node) : - maxNeighborDistance(DBL_MAX), - minNeighborDistance(DBL_MAX), - bound(DBL_MAX), - componentMembership( - ((node.NumPoints() == 1) && (node.NumChildren() == 0)) ? - node.Point(0) : -1) { } - - //! Get the maximum neighbor distance. - double MaxNeighborDistance() const { return maxNeighborDistance; } - //! Modify the maximum neighbor distance. - double& MaxNeighborDistance() { return maxNeighborDistance; } - - //! Get the minimum neighbor distance. - double MinNeighborDistance() const { return minNeighborDistance; } - //! Modify the minimum neighbor distance. - double& MinNeighborDistance() { return minNeighborDistance; } - - //! Get the total bound for pruning. - double Bound() const { return bound; } - //! Modify the total bound for pruning. - double& Bound() { return bound; } - - //! Get the component membership of this node. - int ComponentMembership() const { return componentMembership; } - //! Modify the component membership of this node. - int& ComponentMembership() { return componentMembership; } -}; // class DTBStat - -} // namespace emst -} // namespace mlpack - -#endif // MLPACK_METHODS_EMST_DTB_STAT_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/emst/edge_pair.hpp b/src/sdk/mlpack/include/mlpack/methods/emst/edge_pair.hpp deleted file mode 100644 index dae44b6a4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/emst/edge_pair.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @file edge_pair.hpp - * - * @author Bill March (march@gatech.edu) - * - * This file contains utilities necessary for all of the minimum spanning tree - * algorithms. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_EMST_EDGE_PAIR_HPP -#define MLPACK_METHODS_EMST_EDGE_PAIR_HPP - -#include - -#include "union_find.hpp" - -namespace mlpack { -namespace emst { - -/** - * An edge pair is simply two indices and a distance. It is used as the - * basic element of an edge list when computing a minimum spanning tree. - */ -class EdgePair -{ - private: - //! Lesser index. - size_t lesser; - //! Greater index. - size_t greater; - //! Distance between two indices. - double distance; - - public: - /** - * Initialize an EdgePair with two indices and a distance. The indices are - * called lesser and greater, implying that they be sorted before calling - * Init. However, this is not necessary for functionality; it is just a way - * to keep the edge list organized in other code. - */ - EdgePair(const size_t lesser, const size_t greater, const double dist) : - lesser(lesser), greater(greater), distance(dist) - { - Log::Assert(lesser != greater, - "EdgePair::EdgePair(): indices cannot be equal."); - } - - //! Get the lesser index. - size_t Lesser() const { return lesser; } - //! Modify the lesser index. - size_t& Lesser() { return lesser; } - - //! Get the greater index. - size_t Greater() const { return greater; } - //! Modify the greater index. - size_t& Greater() { return greater; } - - //! Get the distance. - double Distance() const { return distance; } - //! Modify the distance. - double& Distance() { return distance; } -}; // class EdgePair - -} // namespace emst -} // namespace mlpack - -#endif // MLPACK_METHODS_EMST_EDGE_PAIR_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/emst/union_find.hpp b/src/sdk/mlpack/include/mlpack/methods/emst/union_find.hpp deleted file mode 100644 index 160ad4687..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/emst/union_find.hpp +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @file union_find.hpp - * @author Bill March (march@gatech.edu) - * - * Implements a union-find data structure. This structure tracks the components - * of a graph. Each point in the graph is initially in its own component. - * Calling unionfind.Union(x, y) unites the components indexed by x and y. - * unionfind.Find(x) returns the index of the component containing point x. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_EMST_UNION_FIND_HPP -#define MLPACK_METHODS_EMST_UNION_FIND_HPP - -#include - -namespace mlpack { -namespace emst { - -/** - * A Union-Find data structure. See Cormen, Rivest, & Stein for details. The - * structure tracks the components of a graph. Each point in the graph is - * initially in its own component. Calling Union(x, y) unites the components - * indexed by x and y. Find(x) returns the index of the component containing - * point x. - */ -class UnionFind -{ - private: - arma::Col parent; - arma::ivec rank; - - public: - //! Construct the object with the given size. - UnionFind(const size_t size) : parent(size), rank(size) - { - for (size_t i = 0; i < size; ++i) - { - parent[i] = i; - rank[i] = 0; - } - } - - //! Destroy the object (nothing to do). - ~UnionFind() { } - - /** - * Returns the component containing an element. - * - * @param x the component to be found - * @return The index of the component containing x - */ - size_t Find(const size_t x) - { - if (parent[x] == x) - { - return x; - } - else - { - // This ensures that the tree has a small depth. - parent[x] = Find(parent[x]); - return parent[x]; - } - } - - /** - * Union the components containing x and y. - * - * @param x one component - * @param y the other component - */ - void Union(const size_t x, const size_t y) - { - const size_t xRoot = Find(x); - const size_t yRoot = Find(y); - - if (xRoot == yRoot) - { - return; - } - else if (rank[xRoot] == rank[yRoot]) - { - parent[yRoot] = parent[xRoot]; - rank[xRoot] = rank[xRoot] + 1; - } - else if (rank[xRoot] > rank[yRoot]) - { - parent[yRoot] = xRoot; - } - else - { - parent[xRoot] = yRoot; - } - } -}; // class UnionFind - -} // namespace emst -} // namespace mlpack - -#endif // MLPACK_METHODS_EMST_UNION_FIND_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks.hpp b/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks.hpp deleted file mode 100644 index a13aaa784..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks.hpp +++ /dev/null @@ -1,296 +0,0 @@ -/** - * @file fastmks.hpp - * @author Ryan Curtin - * - * Definition of the FastMKS class, which implements fast exact max-kernel - * search. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_FASTMKS_HPP -#define MLPACK_METHODS_FASTMKS_FASTMKS_HPP - -#include -#include -#include "fastmks_stat.hpp" -#include -#include - -namespace mlpack { -namespace fastmks /** Fast max-kernel search. */ { - -/** - * An implementation of fast exact max-kernel search. Given a query dataset and - * a reference dataset (or optionally just a reference dataset which is also - * used as the query dataset), fast exact max-kernel search finds, for each - * point in the query dataset, the k points in the reference set with maximum - * kernel value K(p_q, p_r), where k is a specified parameter and K() is a - * Mercer kernel. - * - * For more information, see the following paper. - * - * @code - * @inproceedings{curtin2013fast, - * title={Fast Exact Max-Kernel Search}, - * author={Curtin, Ryan R. and Ram, Parikshit and Gray, Alexander G.}, - * booktitle={Proceedings of the 2013 SIAM International Conference on Data - * Mining (SDM 13)}, - * year={2013} - * } - * @endcode - * - * This class allows specification of the type of kernel and also of the type of - * tree. FastMKS can be run on kernels that work on arbitrary objects -- - * however, this only works with cover trees and other trees that are built only - * on points in the dataset (and not centroids of regions or anything like - * that). - * - * @tparam KernelType Type of kernel to run FastMKS with. - * @tparam MatType Type of data matrix (usually arma::mat). - * @tparam TreeType Type of tree to run FastMKS with; it must satisfy the - * TreeType policy API. - */ -template< - typename KernelType, - typename MatType = arma::mat, - template class TreeType = tree::StandardCoverTree -> -class FastMKS -{ - public: - //! Convenience typedef. - typedef TreeType, FastMKSStat, MatType> Tree; - - /** - * Create the FastMKS object with an empty reference set and default kernel. - * Make sure to call Train() before Search() is called! - * - * @param singleMode Whether or not to run single-tree search. - * @param naive Whether or not to run brute-force (naive) search. - */ - FastMKS(const bool singleMode = false, const bool naive = false); - - /** - * Create the FastMKS object with the given reference set (this is the set - * that is searched). Optionally, specify whether or not single-tree search - * or naive (brute-force) search should be used. - * - * @param referenceSet Set of reference data. - * @param singleMode Whether or not to run single-tree search. - * @param naive Whether or not to run brute-force (naive) search. - */ - FastMKS(const MatType& referenceSet, - const bool singleMode = false, - const bool naive = false); - - /** - * Create the FastMKS object using the reference set (this is the set that is - * searched) with an initialized kernel. This is useful for when the kernel - * stores state. Optionally, specify whether or not single-tree search or - * naive (brute-force) search should be used. - * - * @param referenceSet Reference set of data for FastMKS. - * @param kernel Initialized kernel. - * @param single Whether or not to run single-tree search. - * @param naive Whether or not to run brute-force (naive) search. - */ - FastMKS(const MatType& referenceSet, - KernelType& kernel, - const bool singleMode = false, - const bool naive = false); - - /** - * Create the FastMKS object with an already-initialized tree built on the - * reference points. Be sure that the tree is built with the metric type - * IPMetric. Optionally, whether or not to run single-tree search - * can be specified. Brute-force search is not available with this - * constructor since a tree is given (use one of the other constructors). - * - * @param referenceTree Tree built on reference data. - * @param single Whether or not to run single-tree search. - * @param naive Whether or not to run brute-force (naive) search. - */ - FastMKS(Tree* referenceTree, - const bool singleMode = false); - - /** - * Copy the parameters of the given model. - */ - FastMKS(const FastMKS& other); - - /** - * Take ownership of the given model. - */ - FastMKS(FastMKS&& other); - - /** - * Assign this model to be a copy of the given model. - */ - FastMKS& operator=(const FastMKS& other); - - //! Destructor for the FastMKS object. - ~FastMKS(); - - /** - * "Train" the FastMKS model on the given reference set (this will just build - * a tree, if the current search mode is not naive mode). - * - * @param referenceSet Set of reference points. - */ - void Train(const MatType& referenceSet); - - /** - * "Train" the FastMKS model on the given reference set and use the given - * kernel. This will just build a tree and replace the metric, if the current - * search mode is not naive mode. - * - * @param referenceSet Set of reference points. - * @param kernel Kernel to use for search. - */ - void Train(const MatType& referenceSet, KernelType& kernel); - - /** - * Train the FastMKS model on the given reference tree. This takes ownership - * of the tree, so you do not need to delete it! This will throw an exception - * if the model is searching in naive mode (i.e. if Naive() == true). - * - * @param tree Tree to use as reference data. - */ - void Train(Tree* referenceTree); - - /** - * Search for the points in the reference set with maximum kernel evaluation - * to each point in the given query set. The resulting kernel evaluations are - * stored in the kernels matrix, and the corresponding point indices are - * stored in the indices matrix. The results for each point in the query set - * are stored in the corresponding column of the kernels and products - * matrices; for instance, the index of the point with maximum kernel - * evaluation to point 4 in the query set will be stored in row 0 and column 4 - * of the indices matrix. - * - * If querySet only contains a few points, the extra overhead of building a - * tree to perform dual-tree search may not be warranted, and it may be faster - * to use single-tree search, either by setting singleMode to false in the - * constructor or with SingleMode(). - * - * @param querySet Set of query points (can be a single point). - * @param k The number of maximum kernels to find. - * @param indices Matrix to store resulting indices of max-kernel search in. - * @param kernels Matrix to store resulting max-kernel values in. - */ - void Search(const MatType& querySet, - const size_t k, - arma::Mat& indices, - arma::mat& kernels); - - /** - * Search for the points in the reference set with maximum kernel evaluation - * to each point in the query set corresponding to the given pre-built query - * tree. The resulting kernel evaluations are stored in the kernels matrix, - * and the corresponding point indices are stored in the indices matrix. The - * results for each point in the query set are stored in the corresponding - * column of the kernels and products matrices; for instance, the index of the - * point with maximum kernel evaluation to point 4 in the query set will be - * stored in row 0 and column 4 of the indices matrix. - * - * This will throw an exception if called while the FastMKS object has - * 'single' set to true. - * - * Be aware that if your tree modifies the original input matrix, the results - * here are with respect to the modified input matrix (that is, - * queryTree->Dataset()). - * - * @param queryTree Tree built on query points. - * @param k The number of maximum kernels to find. - * @param indices Matrix to store resulting indices of max-kernel search in. - * @param kernels Matrix to store resulting max-kernel values in. - */ - void Search(Tree* querySet, - const size_t k, - arma::Mat& indices, - arma::mat& kernels); - - /** - * Search for the maximum inner products of the query set (or if no query set - * was passed, the reference set is used). The resulting maximum inner - * products are stored in the products matrix and the corresponding point - * indices are stores in the indices matrix. The results for each point in - * the query set are stored in the corresponding column of the indices and - * products matrices; for instance, the index of the point with maximum inner - * product to point 4 in the query set will be stored in row 0 and column 4 of - * the indices matrix. - * - * @param k The number of maximum kernels to find. - * @param indices Matrix to store resulting indices of max-kernel search in. - * @param products Matrix to store resulting max-kernel values in. - */ - void Search(const size_t k, - arma::Mat& indices, - arma::mat& products); - - //! Get the inner-product metric induced by the given kernel. - const metric::IPMetric& Metric() const { return metric; } - //! Modify the inner-product metric induced by the given kernel. - metric::IPMetric& Metric() { return metric; } - - //! Get whether or not single-tree search is used. - bool SingleMode() const { return singleMode; } - //! Modify whether or not single-tree search is used. - bool& SingleMode() { return singleMode; } - - //! Get whether or not brute-force (naive) search is used. - bool Naive() const { return naive; } - //! Modify whether or not brute-force (naive) search is used. - bool& Naive() { return naive; } - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! The reference dataset. We never own this; only the tree or a higher level - //! does. - const MatType* referenceSet; - //! The tree built on the reference dataset. - Tree* referenceTree; - //! If true, this object created the tree and is responsible for it. - bool treeOwner; - //! If true, we own the dataset. This happens in only a few situations. - bool setOwner; - - //! If true, single-tree search is used. - bool singleMode; - //! If true, naive (brute-force) search is used. - bool naive; - - //! The instantiated inner-product metric induced by the given kernel. - metric::IPMetric metric; - - //! Candidate represents a possible candidate point (value, index). - typedef std::pair Candidate; - - //! Compare two candidates based on the value. - struct CandidateCmp { - bool operator()(const Candidate& c1, const Candidate& c2) - { - return c1.first > c2.first; - }; - }; - - //! Use a priority queue to represent the list of candidate points. - typedef std::priority_queue, - CandidateCmp> CandidateList; -}; - -} // namespace fastmks -} // namespace mlpack - -// Include implementation. -#include "fastmks_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_impl.hpp deleted file mode 100644 index c40f0be17..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_impl.hpp +++ /dev/null @@ -1,563 +0,0 @@ -/** - * @file fastmks_impl.hpp - * @author Ryan Curtin - * - * Implementation of the FastMKS class (fast max-kernel search). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_FASTMKS_IMPL_HPP -#define MLPACK_METHODS_FASTMKS_FASTMKS_IMPL_HPP - -// In case it hasn't yet been included. -#include "fastmks.hpp" - -#include "fastmks_rules.hpp" - -#include - -namespace mlpack { -namespace fastmks { - -// No data; create a model on an empty dataset. -template class TreeType> -FastMKS::FastMKS(const bool singleMode, - const bool naive) : - referenceSet(new MatType()), - referenceTree(NULL), - treeOwner(true), - setOwner(true), - singleMode(singleMode), - naive(naive) -{ - Timer::Start("tree_building"); - if (!naive) - referenceTree = new Tree(*referenceSet); - Timer::Stop("tree_building"); -} - -// No instantiated kernel. -template class TreeType> -FastMKS::FastMKS( - const MatType& referenceSet, - const bool singleMode, - const bool naive) : - referenceSet(&referenceSet), - referenceTree(NULL), - treeOwner(true), - setOwner(false), - singleMode(singleMode), - naive(naive) -{ - Timer::Start("tree_building"); - if (!naive) - referenceTree = new Tree(referenceSet); - Timer::Stop("tree_building"); -} - -// Instantiated kernel. -template class TreeType> -FastMKS::FastMKS(const MatType& referenceSet, - KernelType& kernel, - const bool singleMode, - const bool naive) : - referenceSet(&referenceSet), - referenceTree(NULL), - treeOwner(true), - setOwner(false), - singleMode(singleMode), - naive(naive), - metric(kernel) -{ - Timer::Start("tree_building"); - - // If necessary, the reference tree should be built. There is no query tree. - if (!naive) - referenceTree = new Tree(referenceSet, metric); - - Timer::Stop("tree_building"); -} - -// One dataset, pre-built tree. -template class TreeType> -FastMKS::FastMKS(Tree* referenceTree, - const bool singleMode) : - referenceSet(&referenceTree->Dataset()), - referenceTree(referenceTree), - treeOwner(false), - setOwner(false), - singleMode(singleMode), - naive(false), - metric(referenceTree->Metric()) -{ - // Nothing to do. -} - -template class TreeType> -FastMKS::FastMKS(const FastMKS& other) : - referenceSet(NULL), - referenceTree(other.referenceTree ? new Tree(*other.referenceTree) : NULL), - treeOwner(other.referenceTree != NULL), - setOwner(other.referenceTree == NULL), - singleMode(other.singleMode), - naive(other.naive), - metric(other.metric) -{ - // Set reference set correctly. - if (referenceTree) - referenceSet = &referenceTree->Dataset(); - else - referenceSet = new MatType(*other.referenceSet); -} - -template class TreeType> -FastMKS::FastMKS(FastMKS&& other) : - referenceSet(other.referenceSet), - referenceTree(other.referenceTree), - treeOwner(other.treeOwner), - setOwner(other.setOwner), - singleMode(other.singleMode), - naive(other.naive), - metric(std::move(other.metric)) -{ - // Clear information from the other. - other.referenceSet = NULL; - other.referenceTree = NULL; - other.treeOwner = false; - other.setOwner = false; - other.singleMode = false; - other.naive = false; -} - -template class TreeType> -FastMKS& -FastMKS::operator=(const FastMKS& other) -{ - // Clear anything we currently have. - if (treeOwner) - delete referenceTree; - if (setOwner) - delete referenceSet; - - referenceTree = NULL; - referenceSet = NULL; - - if (other.referenceTree) - { - referenceTree = new Tree(*other.referenceTree); - referenceSet = &referenceTree->Dataset(); - treeOwner = true; - setOwner = false; - } - else - { - referenceSet = new MatType(*other.referenceSet); - treeOwner = false; - setOwner = true; - } - - singleMode = other.singleMode; - naive = other.naive; -} - -template class TreeType> -FastMKS::~FastMKS() -{ - // If we created the trees, we must delete them. - if (treeOwner && referenceTree) - delete referenceTree; - if (setOwner) - delete referenceSet; -} - -template class TreeType> -void FastMKS::Train(const MatType& referenceSet) -{ - if (setOwner) - delete this->referenceSet; - - this->referenceSet = &referenceSet; - this->setOwner = false; - - if (!naive) - { - if (treeOwner && referenceTree) - delete referenceTree; - referenceTree = new Tree(referenceSet, metric); - treeOwner = true; - } -} - -template class TreeType> -void FastMKS::Train(const MatType& referenceSet, - KernelType& kernel) -{ - if (setOwner) - delete this->referenceSet; - - this->referenceSet = &referenceSet; - this->metric = metric::IPMetric(kernel); - this->setOwner = false; - - if (!naive) - { - if (treeOwner && referenceTree) - delete referenceTree; - referenceTree = new Tree(referenceSet, metric); - treeOwner = true; - } -} - -template class TreeType> -void FastMKS::Train(Tree* tree) -{ - if (naive) - throw std::invalid_argument("cannot call FastMKS::Train() with a tree when " - "in naive search mode"); - - if (setOwner) - delete this->referenceSet; - - this->referenceSet = &tree->Dataset(); - this->metric = metric::IPMetric(tree->Metric().Kernel()); - this->setOwner = false; - - if (treeOwner && referenceTree) - delete referenceTree; - - this->referenceTree = tree; - this->treeOwner = true; -} - -template class TreeType> -void FastMKS::Search( - const MatType& querySet, - const size_t k, - arma::Mat& indices, - arma::mat& kernels) -{ - if (k > referenceSet->n_cols) - { - std::stringstream ss; - ss << "requested value of k (" << k << ") is greater than the number of " - << "points in the reference set (" << referenceSet->n_cols << ")"; - throw std::invalid_argument(ss.str()); - } - - Timer::Start("computing_products"); - - // No remapping will be necessary because we are using the cover tree. - indices.set_size(k, querySet.n_cols); - kernels.set_size(k, querySet.n_cols); - - // Naive implementation. - if (naive) - { - // Simple double loop. Stupid, slow, but a good benchmark. - for (size_t q = 0; q < querySet.n_cols; ++q) - { - const Candidate def = std::make_pair(-DBL_MAX, size_t() - 1); - std::vector cList(k, def); - CandidateList pqueue(CandidateCmp(), std::move(cList)); - - for (size_t r = 0; r < referenceSet->n_cols; ++r) - { - const double eval = metric.Kernel().Evaluate(querySet.col(q), - referenceSet->col(r)); - - if (eval > pqueue.top().first) - { - Candidate c = std::make_pair(eval, r); - pqueue.pop(); - pqueue.push(c); - } - } - - for (size_t j = 1; j <= k; j++) - { - indices(k - j, q) = pqueue.top().second; - kernels(k - j, q) = pqueue.top().first; - pqueue.pop(); - } - } - - Timer::Stop("computing_products"); - - return; - } - - // Single-tree implementation. - if (singleMode) - { - // Create rules object (this will store the results). This constructor - // precalculates each self-kernel value. - typedef FastMKSRules RuleType; - RuleType rules(*referenceSet, querySet, k, metric.Kernel()); - - typename Tree::template SingleTreeTraverser traverser(rules); - - for (size_t i = 0; i < querySet.n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - Log::Info << rules.BaseCases() << " base cases." << std::endl; - Log::Info << rules.Scores() << " scores." << std::endl; - - rules.GetResults(indices, kernels); - - Timer::Stop("computing_products"); - return; - } - - // Dual-tree implementation. First, we need to build the query tree. We are - // assuming it doesn't map anything... - Timer::Stop("computing_products"); - Timer::Start("tree_building"); - Tree queryTree(querySet); - Timer::Stop("tree_building"); - - Search(&queryTree, k, indices, kernels); -} - -template class TreeType> -void FastMKS::Search( - Tree* queryTree, - const size_t k, - arma::Mat& indices, - arma::mat& kernels) -{ - if (k > referenceSet->n_cols) - { - std::stringstream ss; - ss << "requested value of k (" << k << ") is greater than the number of " - << "points in the reference set (" << referenceSet->n_cols << ")"; - throw std::invalid_argument(ss.str()); - } - - // If either naive mode or single mode is specified, this must fail. - if (naive || singleMode) - { - throw std::invalid_argument("can't call Search() with a query tree when " - "single mode or naive search is enabled"); - } - - // No remapping will be necessary because we are using the cover tree. - indices.set_size(k, queryTree->Dataset().n_cols); - kernels.set_size(k, queryTree->Dataset().n_cols); - - Timer::Start("computing_products"); - typedef FastMKSRules RuleType; - RuleType rules(*referenceSet, queryTree->Dataset(), k, metric.Kernel()); - - typename Tree::template DualTreeTraverser traverser(rules); - - traverser.Traverse(*queryTree, *referenceTree); - - Log::Info << rules.BaseCases() << " base cases." << std::endl; - Log::Info << rules.Scores() << " scores." << std::endl; - - rules.GetResults(indices, kernels); - - Timer::Stop("computing_products"); -} - -template class TreeType> -void FastMKS::Search( - const size_t k, - arma::Mat& indices, - arma::mat& kernels) -{ - // No remapping will be necessary because we are using the cover tree. - Timer::Start("computing_products"); - indices.set_size(k, referenceSet->n_cols); - kernels.set_size(k, referenceSet->n_cols); - - // Naive implementation. - if (naive) - { - // Simple double loop. Stupid, slow, but a good benchmark. - for (size_t q = 0; q < referenceSet->n_cols; ++q) - { - const Candidate def = std::make_pair(-DBL_MAX, size_t() - 1); - std::vector cList(k, def); - CandidateList pqueue(CandidateCmp(), std::move(cList)); - - for (size_t r = 0; r < referenceSet->n_cols; ++r) - { - if (q == r) - continue; // Don't return the point as its own candidate. - - const double eval = metric.Kernel().Evaluate(referenceSet->col(q), - referenceSet->col(r)); - - if (eval > pqueue.top().first) - { - Candidate c = std::make_pair(eval, r); - pqueue.pop(); - pqueue.push(c); - } - } - - for (size_t j = 1; j <= k; j++) - { - indices(k - j, q) = pqueue.top().second; - kernels(k - j, q) = pqueue.top().first; - pqueue.pop(); - } - } - - Timer::Stop("computing_products"); - - return; - } - - // Single-tree implementation. - if (singleMode) - { - // Create rules object (this will store the results). This constructor - // precalculates each self-kernel value. - typedef FastMKSRules RuleType; - RuleType rules(*referenceSet, *referenceSet, k, metric.Kernel()); - - typename Tree::template SingleTreeTraverser traverser(rules); - - for (size_t i = 0; i < referenceSet->n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - // Save the number of pruned nodes. - const size_t numPrunes = traverser.NumPrunes(); - - Log::Info << "Pruned " << numPrunes << " nodes." << std::endl; - - Log::Info << rules.BaseCases() << " base cases." << std::endl; - Log::Info << rules.Scores() << " scores." << std::endl; - - rules.GetResults(indices, kernels); - - Timer::Stop("computing_products"); - return; - } - - // Dual-tree implementation. - Timer::Stop("computing_products"); - - Search(referenceTree, k, indices, kernels); -} - -//! Serialize the model. -template class TreeType> -template -void FastMKS::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // Serialize preferences for search. - ar & BOOST_SERIALIZATION_NVP(naive); - ar & BOOST_SERIALIZATION_NVP(singleMode); - - // If we are doing naive search, serialize the dataset. Otherwise we - // serialize the tree. - if (naive) - { - if (Archive::is_loading::value) - { - if (setOwner && referenceSet) - delete referenceSet; - - setOwner = true; - } - - ar & BOOST_SERIALIZATION_NVP(referenceSet); - ar & BOOST_SERIALIZATION_NVP(metric); - } - else - { - // Delete the current reference tree, if necessary. - if (Archive::is_loading::value) - { - if (treeOwner && referenceTree) - delete referenceTree; - - treeOwner = true; - } - - ar & BOOST_SERIALIZATION_NVP(referenceTree); - - if (Archive::is_loading::value) - { - if (setOwner && referenceSet) - delete referenceSet; - - referenceSet = &referenceTree->Dataset(); - metric = metric::IPMetric(referenceTree->Metric().Kernel()); - setOwner = false; - } - } -} - -} // namespace fastmks -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_model.hpp b/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_model.hpp deleted file mode 100644 index 2250581ad..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_model.hpp +++ /dev/null @@ -1,165 +0,0 @@ -/** - * @file fastmks_model.hpp - * @author Ryan Curtin - * - * A utility struct to contain all the possible FastMKS models. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_FASTMKS_MODEL_HPP -#define MLPACK_METHODS_FASTMKS_FASTMKS_MODEL_HPP - -#include -#include "fastmks.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace mlpack { -namespace fastmks { - -//! A utility struct to contain all the possible FastMKS models, for use by the -//! mlpack_fastmks program. -class FastMKSModel -{ - public: - //! A list of all the kernels we support. - enum KernelTypes - { - LINEAR_KERNEL, - POLYNOMIAL_KERNEL, - COSINE_DISTANCE, - GAUSSIAN_KERNEL, - EPANECHNIKOV_KERNEL, - TRIANGULAR_KERNEL, - HYPTAN_KERNEL - }; - - /** - * Create the FastMKSModel with the given kernel type. - */ - FastMKSModel(const int kernelType = LINEAR_KERNEL); - - //! Copy constructor. - FastMKSModel(const FastMKSModel& other); - - //! Move constructor. - FastMKSModel(FastMKSModel&& other); - - //! Copy assignment operator. - FastMKSModel& operator=(const FastMKSModel& other); - - /** - * Clean memory. - */ - ~FastMKSModel(); - - /** - * Build the model on the given reference set. Make sure kernelType is equal - * to the correct entry in KernelTypes for the given KernelType class! - */ - template - void BuildModel(const arma::mat& referenceData, - TKernelType& kernel, - const bool singleMode, - const bool naive, - const double base); - - //! Get whether or not naive search is used. - bool Naive() const; - //! Set whether or not naive search is used. - bool& Naive(); - - //! Get whether or not single-tree search is used. - bool SingleMode() const; - //! Set whether or not single-tree search is used. - bool& SingleMode(); - - //! Get the kernel type. - int KernelType() const { return kernelType; } - //! Modify the kernel type. - int& KernelType() { return kernelType; } - - /** - * Search with a different query set. - * - * @param querySet Set to search with. - * @param k Number of max-kernel candidates to search for. - * @param indices A matrix in which to store the indices of max-kernel - * candidates. - * @param kernels A matrix in which to store the max-kernel candidate kernel - * values. - * @param base Base to use for cover tree building (if in dual-tree search - * mode). - */ - void Search(const arma::mat& querySet, - const size_t k, - arma::Mat& indices, - arma::mat& kernels, - const double base); - - /** - * Search with the reference set as the query set. - * - * @param k Number of max-kernel candidates to search for. - * @param indices A matrix in which to store the indices of max-kernel - * candidates. - * @param kernels A matrix in which to store the max-kernel candidate kernel - * values. - */ - void Search(const size_t k, - arma::Mat& indices, - arma::mat& kernels); - - /** - * Serialize the model. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! The type of kernel we are using. - int kernelType; - - //! This will only be non-NULL if this is the type of kernel we are using. - FastMKS* linear; - //! This will only be non-NULL if this is the type of kernel we are using. - FastMKS* polynomial; - //! This will only be non-NULL if this is the type of kernel we are using. - FastMKS* cosine; - //! This will only be non-NULL if this is the type of kernel we are using. - FastMKS* gaussian; - //! This will only be non-NULL if this is the type of kernel we are using. - FastMKS* epan; - //! This will only be non-NULL if this is the type of kernel we are using. - FastMKS* triangular; - //! This will only be non-NULL if this is the type of kernel we are using. - FastMKS* hyptan; - - //! Build a query tree and execute the search. - template - void Search(FastMKSType& f, - const arma::mat& querySet, - const size_t k, - arma::Mat& indices, - arma::mat& kernels, - const double base); -}; - -} // namespace fastmks -} // namespace mlpack - -#include "fastmks_model_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_model_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_model_impl.hpp deleted file mode 100644 index fb57c95df..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_model_impl.hpp +++ /dev/null @@ -1,218 +0,0 @@ -/** - * @file fastmks_model_impl.hpp - * @author Ryan Curtin - * - * Implementation of templated functions of FastMKSModel. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_FASTMKS_MODEL_IMPL_HPP -#define MLPACK_METHODS_FASTMKS_FASTMKS_MODEL_IMPL_HPP - -#include "fastmks_model.hpp" - -namespace mlpack { -namespace fastmks { - -//! This is called when the KernelType is the same as the model. -template -void BuildFastMKSModel(FastMKS& f, - KernelType& k, - const arma::mat& referenceData, - const double base) -{ - // Do we need to build the tree? - if (f.Naive()) - { - f.Train(referenceData, k); - } - else - { - // Create the tree with the specified base. - Timer::Start("tree_building"); - metric::IPMetric metric(k); - typename FastMKS::Tree* tree = - new typename FastMKS::Tree(referenceData, metric, base); - Timer::Stop("tree_building"); - - f.Train(tree); - } -} - -//! This is only called when something goes wrong. -template -void BuildFastMKSModel(FastMKSType& /* f */, - KernelType& /* k */, - const arma::mat& /* referenceData */, - const double /* base */) -{ - throw std::invalid_argument("FastMKSModel::BuildModel(): given kernel type is" - " not equal to kernel type of the model!"); -} - -template -void FastMKSModel::BuildModel(const arma::mat& referenceData, - TKernelType& kernel, - const bool singleMode, - const bool naive, - const double base) -{ - // Clean memory if necessary. - if (linear) - delete linear; - if (polynomial) - delete polynomial; - if (cosine) - delete cosine; - if (gaussian) - delete gaussian; - if (epan) - delete epan; - if (triangular) - delete triangular; - if (hyptan) - delete hyptan; - - linear = NULL; - polynomial = NULL; - cosine = NULL; - gaussian = NULL; - epan = NULL; - triangular = NULL; - hyptan = NULL; - - // Instantiate the right model. - switch (kernelType) - { - case LINEAR_KERNEL: - linear = new FastMKS(singleMode, naive); - BuildFastMKSModel(*linear, kernel, referenceData, base); - break; - - case POLYNOMIAL_KERNEL: - polynomial = new FastMKS(singleMode, naive); - BuildFastMKSModel(*polynomial, kernel, referenceData, base); - break; - - case COSINE_DISTANCE: - cosine = new FastMKS(singleMode, naive); - BuildFastMKSModel(*cosine, kernel, referenceData, base); - break; - - case GAUSSIAN_KERNEL: - gaussian = new FastMKS(singleMode, naive); - BuildFastMKSModel(*gaussian, kernel, referenceData, base); - break; - - case EPANECHNIKOV_KERNEL: - epan = new FastMKS(singleMode, naive); - BuildFastMKSModel(*epan, kernel, referenceData, base); - break; - - case TRIANGULAR_KERNEL: - triangular = new FastMKS(singleMode, naive); - BuildFastMKSModel(*triangular, kernel, referenceData, base); - break; - - case HYPTAN_KERNEL: - hyptan = new FastMKS(singleMode, naive); - BuildFastMKSModel(*hyptan, kernel, referenceData, base); - break; - } -} - -template -void FastMKSModel::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(kernelType); - - if (Archive::is_loading::value) - { - // Clean memory. - if (linear) - delete linear; - if (polynomial) - delete polynomial; - if (cosine) - delete cosine; - if (gaussian) - delete gaussian; - if (epan) - delete epan; - if (triangular) - delete triangular; - if (hyptan) - delete hyptan; - - linear = NULL; - polynomial = NULL; - cosine = NULL; - gaussian = NULL; - epan = NULL; - triangular = NULL; - hyptan = NULL; - } - - // Serialize the correct model. - switch (kernelType) - { - case LINEAR_KERNEL: - ar & BOOST_SERIALIZATION_NVP(linear); - break; - - case POLYNOMIAL_KERNEL: - ar & BOOST_SERIALIZATION_NVP(polynomial); - break; - - case COSINE_DISTANCE: - ar & BOOST_SERIALIZATION_NVP(cosine); - break; - - case GAUSSIAN_KERNEL: - ar & BOOST_SERIALIZATION_NVP(gaussian); - break; - - case EPANECHNIKOV_KERNEL: - ar & BOOST_SERIALIZATION_NVP(epan); - break; - - case TRIANGULAR_KERNEL: - ar & BOOST_SERIALIZATION_NVP(triangular); - break; - - case HYPTAN_KERNEL: - ar & BOOST_SERIALIZATION_NVP(hyptan); - break; - } -} - -template -void FastMKSModel::Search(FastMKSType& f, - const arma::mat& querySet, - const size_t k, - arma::Mat& indices, - arma::mat& kernels, - const double base) -{ - if (f.Naive() || f.SingleMode()) - { - f.Search(querySet, k, indices, kernels); - } - else - { - Timer::Start("tree_building"); - typename FastMKSType::Tree queryTree(querySet, base); - Timer::Stop("tree_building"); - - f.Search(&queryTree, k, indices, kernels); - } -} - -} // namespace fastmks -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_rules.hpp b/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_rules.hpp deleted file mode 100644 index 2002090a4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_rules.hpp +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @file fastmks_rules.hpp - * @author Ryan Curtin - * - * Rules for the single or dual tree traversal for fast max-kernel search. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_FASTMKS_RULES_HPP -#define MLPACK_METHODS_FASTMKS_FASTMKS_RULES_HPP - -#include -#include -#include -#include -#include - -namespace mlpack { -namespace fastmks { - -/** - * The FastMKSRules class is a template helper class used by FastMKS class when - * performing exact max-kernel search. For each point in the query dataset, it - * keeps track of the k best candidates in the reference dataset. - * - * @tparam KernelType Type of kernel to run FastMKS with. - * @tparam TreeType Type of tree to run FastMKS with; it must satisfy the - * TreeType policy API. - */ -template -class FastMKSRules -{ - public: - /** - * Construct the FastMKSRules object. This is usually done from within the - * FastMKS class at search time. - * - * @param referenceSet Set of reference data. - * @param querySet Set of query data. - * @param k Number of candidates to search for. - * @param kernel Kernel to run FastMKS with. - */ - FastMKSRules(const typename TreeType::Mat& referenceSet, - const typename TreeType::Mat& querySet, - const size_t k, - KernelType& kernel); - - /** - * Store the list of candidates for each query point in the given matrices. - * - * @param indices Matrix storing lists of candidate for each query point. - * @param products Matrix storing kernel value for each candidate. - */ - void GetResults(arma::Mat& indices, arma::mat& products); - - //! Compute the base case (kernel value) between two points. - double BaseCase(const size_t queryIndex, const size_t referenceIndex); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate to be recursed into. - */ - double Score(const size_t queryIndex, TreeType& referenceNode); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * @param queryNode Candidate query node to be recursed into. - * @param referenceNode Candidate reference node to be recursed into. - */ - double Score(TreeType& queryNode, TreeType& referenceNode); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that a node should not be recursed - * into at all (it should be pruned). This is used when the score has already - * been calculated, but another recursion may have modified the bounds for - * pruning. So the old score is checked against the new pruning bound. - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - * @param oldScore Old score produced by Score() (or Rescore()). - */ - double Rescore(const size_t queryIndex, - TreeType& referenceNode, - const double oldScore) const; - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that a node should not be recursed - * into at all (it should be pruned). This is used when the score has already - * been calculated, but another recursion may have modified the bounds for - * pruning. So the old score is checked against the new pruning bound. - * - * @param queryNode Candidate query node to be recursed into. - * @param referenceNode Candidate reference node to be recursed into. - * @param oldScore Old score produced by Score() (or Rescore()). - */ - double Rescore(TreeType& queryNode, - TreeType& referenceNode, - const double oldScore) const; - - //! Get the number of times BaseCase() was called. - size_t BaseCases() const { return baseCases; } - //! Modify the number of times BaseCase() was called. - size_t& BaseCases() { return baseCases; } - - //! Get the number of times Score() was called. - size_t Scores() const { return scores; } - //! Modify the number of times Score() was called. - size_t& Scores() { return scores; } - - typedef typename tree::TraversalInfo TraversalInfoType; - - const TraversalInfoType& TraversalInfo() const { return traversalInfo; } - TraversalInfoType& TraversalInfo() { return traversalInfo; } - - private: - //! The reference dataset. - const typename TreeType::Mat& referenceSet; - //! The query dataset. - const typename TreeType::Mat& querySet; - - //! Candidate represents a possible candidate point (value, index). - typedef std::pair Candidate; - - //! Compare two candidates based on the value. - struct CandidateCmp { - bool operator()(const Candidate& c1, const Candidate& c2) const - { - return c1.first > c2.first; - }; - }; - - //! Use a min heap to represent the list of candidate points. - //! We will use a boost::heap::priority_queue instead of a std::priority_queue - //! because we need to iterate over all the candidates and std::priority_queue - //! doesn't provide that interface. - typedef boost::heap::priority_queue> CandidateList; - - //! Set of candidates for each point. - std::vector candidates; - - //! Number of points to search for. - const size_t k; - - //! Cached query set self-kernels (|| q || for each q). - arma::vec queryKernels; - //! Cached reference set self-kernels (|| r || for each r). - arma::vec referenceKernels; - - //! The instantiated kernel. - KernelType& kernel; - - //! The last query index BaseCase() was called with. - size_t lastQueryIndex; - //! The last reference index BaseCase() was called with. - size_t lastReferenceIndex; - //! The last kernel evaluation resulting from BaseCase(). - double lastKernel; - - //! Calculate the bound for a given query node. - double CalculateBound(TreeType& queryNode) const; - - /** - * Helper function to insert a point into the list of candidate points. - * - * @param queryIndex Index of point whose neighbors we are inserting into. - * @param index Index of reference point which is being inserted. - * @param product Kernel value for given candidate. - */ - void InsertNeighbor(const size_t queryIndex, - const size_t index, - const double product); - - //! For benchmarking. - size_t baseCases; - //! For benchmarking. - size_t scores; - - TraversalInfoType traversalInfo; -}; - -} // namespace fastmks -} // namespace mlpack - -// Include implementation. -#include "fastmks_rules_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_rules_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_rules_impl.hpp deleted file mode 100644 index 4b98fd6c3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_rules_impl.hpp +++ /dev/null @@ -1,544 +0,0 @@ -/** - * @file fastmks_rules_impl.hpp - * @author Ryan Curtin - * - * Implementation of FastMKSRules for cover tree search. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_FASTMKS_RULES_IMPL_HPP -#define MLPACK_METHODS_FASTMKS_FASTMKS_RULES_IMPL_HPP - -// In case it hasn't already been included. -#include "fastmks_rules.hpp" - -namespace mlpack { -namespace fastmks { - -template -FastMKSRules::FastMKSRules( - const typename TreeType::Mat& referenceSet, - const typename TreeType::Mat& querySet, - const size_t k, - KernelType& kernel) : - referenceSet(referenceSet), - querySet(querySet), - k(k), - kernel(kernel), - lastQueryIndex(-1), - lastReferenceIndex(-1), - lastKernel(0.0), - baseCases(0), - scores(0) -{ - // Precompute each self-kernel. - queryKernels.set_size(querySet.n_cols); - for (size_t i = 0; i < querySet.n_cols; ++i) - queryKernels[i] = sqrt(kernel.Evaluate(querySet.col(i), - querySet.col(i))); - - referenceKernels.set_size(referenceSet.n_cols); - for (size_t i = 0; i < referenceSet.n_cols; ++i) - referenceKernels[i] = sqrt(kernel.Evaluate(referenceSet.col(i), - referenceSet.col(i))); - - // Set to invalid memory, so that the first node combination does not try to - // dereference null pointers. - traversalInfo.LastQueryNode() = (TreeType*) this; - traversalInfo.LastReferenceNode() = (TreeType*) this; - - // Let's build the list of candidate points for each query point. - // It will be initialized with k candidates: (-DBL_MAX, size_t() - 1) - // The list of candidates will be updated when visiting new points with the - // BaseCase() method. - const Candidate def = std::make_pair(-DBL_MAX, size_t() - 1); - - CandidateList pqueue; - pqueue.reserve(k); - for (size_t i = 0; i < k; i++) - pqueue.push(def); - std::vector tmp(querySet.n_cols, pqueue); - candidates.swap(tmp); -} - -template -void FastMKSRules::GetResults( - arma::Mat& indices, - arma::mat& products) -{ - indices.set_size(k, querySet.n_cols); - products.set_size(k, querySet.n_cols); - - for (size_t i = 0; i < querySet.n_cols; i++) - { - CandidateList& pqueue = candidates[i]; - for (size_t j = 1; j <= k; j++) - { - indices(k - j, i) = pqueue.top().second; - products(k - j, i) = pqueue.top().first; - pqueue.pop(); - } - } -} - -template -inline force_inline -double FastMKSRules::BaseCase( - const size_t queryIndex, - const size_t referenceIndex) -{ - // Score() always happens before BaseCase() for a given node combination. For - // cover trees, the kernel evaluation between the two centroid points already - // happened. So we don't need to do it. Note that this optimizes out if the - // first conditional is false (its result is known at compile time). - if (tree::TreeTraits::FirstPointIsCentroid) - { - if ((queryIndex == lastQueryIndex) && - (referenceIndex == lastReferenceIndex)) - return lastKernel; - - // Store new values. - lastQueryIndex = queryIndex; - lastReferenceIndex = referenceIndex; - } - - ++baseCases; - double kernelEval = kernel.Evaluate(querySet.col(queryIndex), - referenceSet.col(referenceIndex)); - - // Update the last kernel value, if we need to. - if (tree::TreeTraits::FirstPointIsCentroid) - lastKernel = kernelEval; - - // If the reference and query sets are identical, we still need to compute the - // base case (so that things can be bounded properly), but we won't add it to - // the results. - if ((&querySet == &referenceSet) && (queryIndex == referenceIndex)) - return kernelEval; - - InsertNeighbor(queryIndex, referenceIndex, kernelEval); - - return kernelEval; -} - -template -double FastMKSRules::Score(const size_t queryIndex, - TreeType& referenceNode) -{ - // Compare with the current best. - const double bestKernel = candidates[queryIndex].top().first; - - // See if we can perform a parent-child prune. - const double furthestDist = referenceNode.FurthestDescendantDistance(); - if (referenceNode.Parent() != NULL) - { - double maxKernelBound; - const double parentDist = referenceNode.ParentDistance(); - const double combinedDistBound = parentDist + furthestDist; - const double lastKernel = referenceNode.Parent()->Stat().LastKernel(); - if (kernel::KernelTraits::IsNormalized) - { - const double squaredDist = std::pow(combinedDistBound, 2.0); - const double delta = (1 - 0.5 * squaredDist); - if (lastKernel <= delta) - { - const double gamma = combinedDistBound * sqrt(1 - 0.25 * squaredDist); - maxKernelBound = lastKernel * delta + - gamma * sqrt(1 - std::pow(lastKernel, 2.0)); - } - else - { - maxKernelBound = 1.0; - } - } - else - { - maxKernelBound = lastKernel + - combinedDistBound * queryKernels[queryIndex]; - } - - if (maxKernelBound < bestKernel) - return DBL_MAX; - } - - // Calculate the maximum possible kernel value, either by calculating the - // centroid or, if the centroid is a point, use that. - ++scores; - double kernelEval; - if (tree::TreeTraits::FirstPointIsCentroid) - { - // Could it be that this kernel evaluation has already been calculated? - if (tree::TreeTraits::HasSelfChildren && - referenceNode.Parent() != NULL && - referenceNode.Point(0) == referenceNode.Parent()->Point(0)) - { - kernelEval = referenceNode.Parent()->Stat().LastKernel(); - } - else - { - kernelEval = BaseCase(queryIndex, referenceNode.Point(0)); - } - } - else - { - arma::vec refCenter; - referenceNode.Center(refCenter); - - kernelEval = kernel.Evaluate(querySet.col(queryIndex), refCenter); - } - - referenceNode.Stat().LastKernel() = kernelEval; - - double maxKernel; - if (kernel::KernelTraits::IsNormalized) - { - const double squaredDist = std::pow(furthestDist, 2.0); - const double delta = (1 - 0.5 * squaredDist); - if (kernelEval <= delta) - { - const double gamma = furthestDist * sqrt(1 - 0.25 * squaredDist); - maxKernel = kernelEval * delta + - gamma * sqrt(1 - std::pow(kernelEval, 2.0)); - } - else - { - maxKernel = 1.0; - } - } - else - { - maxKernel = kernelEval + furthestDist * queryKernels[queryIndex]; - } - - // We return the inverse of the maximum kernel so that larger kernels are - // recursed into first. - return (maxKernel >= bestKernel) ? (1.0 / maxKernel) : DBL_MAX; -} - -template -double FastMKSRules::Score(TreeType& queryNode, - TreeType& referenceNode) -{ - // Update and get the query node's bound. - queryNode.Stat().Bound() = CalculateBound(queryNode); - const double bestKernel = queryNode.Stat().Bound(); - - // First, see if we can make a parent-child or parent-parent prune. These - // four bounds on the maximum kernel value are looser than the bound normally - // used, but they can prevent a base case from needing to be calculated. - - // Convenience caching so lines are shorter. - const double queryParentDist = queryNode.ParentDistance(); - const double queryDescDist = queryNode.FurthestDescendantDistance(); - const double refParentDist = referenceNode.ParentDistance(); - const double refDescDist = referenceNode.FurthestDescendantDistance(); - double adjustedScore = traversalInfo.LastBaseCase(); - - const double queryDistBound = (queryParentDist + queryDescDist); - const double refDistBound = (refParentDist + refDescDist); - double dualQueryTerm; - double dualRefTerm; - - // The parent-child and parent-parent prunes work by applying the same pruning - // condition as when the parent node was used, except they are tighter because - // queryDistBound < queryNode.Parent()->FurthestDescendantDistance() - // and - // refDistBound < referenceNode.Parent()->FurthestDescendantDistance() - // so we construct the same bounds that were used when Score() was called with - // the parents, except with the tighter distance bounds. Sometimes this - // allows us to prune nodes without evaluating the base cases between them. - if (traversalInfo.LastQueryNode() == queryNode.Parent()) - { - // We can assume that queryNode.Parent() != NULL, because at the root node - // combination, the traversalInfo.LastQueryNode() pointer will _not_ be - // NULL. We also should be guaranteed that - // traversalInfo.LastReferenceNode() is either the reference node or the - // parent of the reference node. - adjustedScore += queryDistBound * - traversalInfo.LastReferenceNode()->Stat().SelfKernel(); - dualQueryTerm = queryDistBound; - } - else - { - // The query parent could be NULL, which does weird things and we have to - // consider. - if (traversalInfo.LastReferenceNode() != NULL) - { - adjustedScore += queryDescDist * - traversalInfo.LastReferenceNode()->Stat().SelfKernel(); - dualQueryTerm = queryDescDist; - } - else - { - // This makes it so a child-parent (or parent-parent) prune is not - // possible. - dualQueryTerm = 0.0; - adjustedScore = bestKernel; - } - } - - if (traversalInfo.LastReferenceNode() == referenceNode.Parent()) - { - // We can assume that referenceNode.Parent() != NULL, because at the root - // node combination, the traversalInfo.LastReferenceNode() pointer will - // _not_ be NULL. - adjustedScore += refDistBound * - traversalInfo.LastQueryNode()->Stat().SelfKernel(); - dualRefTerm = refDistBound; - } - else - { - // The reference parent could be NULL, which does weird things and we have - // to consider. - if (traversalInfo.LastQueryNode() != NULL) - { - adjustedScore += refDescDist * - traversalInfo.LastQueryNode()->Stat().SelfKernel(); - dualRefTerm = refDescDist; - } - else - { - // This makes it so a child-parent (or parent-parent) prune is not - // possible. - dualRefTerm = 0.0; - adjustedScore = bestKernel; - } - } - - // Now add the dual term. - adjustedScore += (dualQueryTerm * dualRefTerm); - - if (adjustedScore < bestKernel) - { - // It is not possible that this node combination can contain a point - // combination with kernel value better than the minimum kernel value to - // improve any of the results, so we can prune it. - return DBL_MAX; - } - - // We were unable to perform a parent-child or parent-parent prune, so now we - // must calculate kernel evaluation, if necessary. - double kernelEval = 0.0; - if (tree::TreeTraits::FirstPointIsCentroid) - { - // For this type of tree, we may have already calculated the base case in - // the parents. - if ((traversalInfo.LastQueryNode() != NULL) && - (traversalInfo.LastReferenceNode() != NULL) && - (traversalInfo.LastQueryNode()->Point(0) == queryNode.Point(0)) && - (traversalInfo.LastReferenceNode()->Point(0) == referenceNode.Point(0))) - { - // Base case already done. - kernelEval = traversalInfo.LastBaseCase(); - - // When BaseCase() is called after Score(), these must be correct so that - // another kernel evaluation is not performed. - lastQueryIndex = queryNode.Point(0); - lastReferenceIndex = referenceNode.Point(0); - } - else - { - // The kernel must be evaluated, but it is between points in the dataset, - // so we can call BaseCase(). BaseCase() will set lastQueryIndex and - // lastReferenceIndex correctly. - kernelEval = BaseCase(queryNode.Point(0), referenceNode.Point(0)); - } - - traversalInfo.LastBaseCase() = kernelEval; - } - else - { - // Calculate the maximum possible kernel value. - arma::vec queryCenter; - arma::vec refCenter; - queryNode.Center(queryCenter); - referenceNode.Center(refCenter); - - kernelEval = kernel.Evaluate(queryCenter, refCenter); - - traversalInfo.LastBaseCase() = kernelEval; - } - ++scores; - - double maxKernel; - if (kernel::KernelTraits::IsNormalized) - { - // We have a tighter bound for normalized kernels. - const double querySqDist = std::pow(queryDescDist, 2.0); - const double refSqDist = std::pow(refDescDist, 2.0); - const double bothSqDist = std::pow((queryDescDist + refDescDist), 2.0); - - if (kernelEval <= (1 - 0.5 * bothSqDist)) - { - const double queryDelta = (1 - 0.5 * querySqDist); - const double queryGamma = queryDescDist * sqrt(1 - 0.25 * querySqDist); - const double refDelta = (1 - 0.5 * refSqDist); - const double refGamma = refDescDist * sqrt(1 - 0.25 * refSqDist); - - maxKernel = kernelEval * (queryDelta * refDelta - queryGamma * refGamma) + - sqrt(1 - std::pow(kernelEval, 2.0)) * - (queryGamma * refDelta + queryDelta * refGamma); - } - else - { - maxKernel = 1.0; - } - } - else - { - // Use standard bound; kernel is not normalized. - const double refKernelTerm = queryDescDist * - referenceNode.Stat().SelfKernel(); - const double queryKernelTerm = refDescDist * queryNode.Stat().SelfKernel(); - - maxKernel = kernelEval + refKernelTerm + queryKernelTerm + - (queryDescDist * refDescDist); - } - - // Store relevant information for parent-child pruning. - traversalInfo.LastQueryNode() = &queryNode; - traversalInfo.LastReferenceNode() = &referenceNode; - - // We return the inverse of the maximum kernel so that larger kernels are - // recursed into first. - return (maxKernel >= bestKernel) ? (1.0 / maxKernel) : DBL_MAX; -} - -template -double FastMKSRules::Rescore(const size_t queryIndex, - TreeType& /*referenceNode*/, - const double oldScore) const -{ - const double bestKernel = candidates[queryIndex].top().first; - - return ((1.0 / oldScore) >= bestKernel) ? oldScore : DBL_MAX; -} - -template -double FastMKSRules::Rescore(TreeType& queryNode, - TreeType& /*referenceNode*/, - const double oldScore) const -{ - queryNode.Stat().Bound() = CalculateBound(queryNode); - const double bestKernel = queryNode.Stat().Bound(); - - return ((1.0 / oldScore) >= bestKernel) ? oldScore : DBL_MAX; -} - -/** - * Calculate the bound for the given query node. This bound represents the - * minimum value which a node combination must achieve to guarantee an - * improvement in the results. - * - * @param queryNode Query node to calculate bound for. - */ -template -double FastMKSRules::CalculateBound(TreeType& queryNode) - const -{ - // We have four possible bounds -- just like NeighborSearchRules, but they are - // slightly different in this context. - // - // (1) min ( min_{all points p in queryNode} P_p[k], - // min_{all children c in queryNode} B(c) ); - // (2) max_{all points p in queryNode} P_p[k] + (worst child distance + worst - // descendant distance) sqrt(K(I_p[k], I_p[k])); - // (3) max_{all children c in queryNode} B(c) + <-- not done yet. ignored. - // (4) B(parent of queryNode); - double worstPointKernel = DBL_MAX; - double bestAdjustedPointKernel = -DBL_MAX; - - const double queryDescendantDistance = queryNode.FurthestDescendantDistance(); - - // Loop over all points in this node to find the worst max-kernel value and - // the best possible adjusted max-kernel value that could be held by any - // descendant. - for (size_t i = 0; i < queryNode.NumPoints(); ++i) - { - const size_t point = queryNode.Point(i); - const CandidateList& candidatesPoints = candidates[point]; - if (candidatesPoints.top().first < worstPointKernel) - worstPointKernel = candidatesPoints.top().first; - - if (candidatesPoints.top().first == -DBL_MAX) - continue; // Avoid underflow. - - // This should be (queryDescendantDistance + centroidDistance) for any tree - // but it works for cover trees since centroidDistance = 0 for cover trees. - // The formulation here is slightly different than in Equation 43 of - // "Dual-tree fast exact max-kernel search". Because we could be searching - // for k max kernels and not just one, the bound for this point must - // actually be the minimum adjusted kernel of all k candidate kernels. - // So, - // B(N_q) = min_{1 \le j \le k} k_j^*(p_q) - - // \lambda_q \sqrt(K(p_j^*(p_q), p_j^*(p_q))) - // where p_j^*(p_q) is the j'th kernel candidate for query point p_q and - // k_j^*(p_q) is K(p_q, p_j^*(p_q)). - double worstPointCandidateKernel = DBL_MAX; - typedef typename CandidateList::const_iterator iter; - for (iter it = candidatesPoints.begin(); it != candidatesPoints.end(); ++it) - { - const double candidateKernel = it->first - queryDescendantDistance * - referenceKernels[it->second]; - if (candidateKernel < worstPointCandidateKernel) - worstPointCandidateKernel = candidateKernel; - } - - if (worstPointCandidateKernel > bestAdjustedPointKernel) - bestAdjustedPointKernel = worstPointCandidateKernel; - } - - // Loop over all the children in the node. - double worstChildKernel = DBL_MAX; - - for (size_t i = 0; i < queryNode.NumChildren(); ++i) - { - if (queryNode.Child(i).Stat().Bound() < worstChildKernel) - worstChildKernel = queryNode.Child(i).Stat().Bound(); - } - - // Now assemble bound (1). - const double firstBound = (worstPointKernel < worstChildKernel) ? - worstPointKernel : worstChildKernel; - - // Bound (2) is bestAdjustedPointKernel. - const double fourthBound = (queryNode.Parent() == NULL) ? -DBL_MAX : - queryNode.Parent()->Stat().Bound(); - - // Pick the best of these bounds. - const double interA = (firstBound > bestAdjustedPointKernel) ? firstBound : - bestAdjustedPointKernel; - const double interB = fourthBound; - - return (interA > interB) ? interA : interB; -} - -/** - * Helper function to insert a point into the list of candidate points. - * - * @param queryIndex Index of point whose neighbors we are inserting into. - * @param index Index of reference point which is being inserted. - * @param product Kernel value for given candidate. - */ -template -inline void FastMKSRules::InsertNeighbor( - const size_t queryIndex, - const size_t index, - const double product) -{ - CandidateList& pqueue = candidates[queryIndex]; - if (product > pqueue.top().first) - { - Candidate c = std::make_pair(product, index); - pqueue.pop(); - pqueue.push(c); - } -} - -} // namespace fastmks -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_stat.hpp b/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_stat.hpp deleted file mode 100644 index 05c29026c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/fastmks/fastmks_stat.hpp +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @file fastmks_stat.hpp - * @author Ryan Curtin - * - * The statistic used in trees with FastMKS. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_FASTMKS_FASTMKS_STAT_HPP -#define MLPACK_METHODS_FASTMKS_FASTMKS_STAT_HPP - -#include -#include - -namespace mlpack { -namespace fastmks { - -/** - * The statistic used in trees with FastMKS. This stores both the bound and the - * self-kernels for each node in the tree. - */ -class FastMKSStat -{ - public: - /** - * Default initialization. - */ - FastMKSStat() : - bound(-DBL_MAX), - selfKernel(0.0), - lastKernel(0.0), - lastKernelNode(NULL) - { } - - /** - * Initialize this statistic for the given tree node. The TreeType's metric - * better be IPMetric with some kernel type (that is, Metric().Kernel() must - * exist). - * - * @param node Node that this statistic is built for. - */ - template - FastMKSStat(const TreeType& node) : - bound(-DBL_MAX), - lastKernel(0.0), - lastKernelNode(NULL) - { - // Do we have to calculate the centroid? - if (tree::TreeTraits::FirstPointIsCentroid) - { - // If this type of tree has self-children, then maybe the evaluation is - // already done. These statistics are built bottom-up, so the child stat - // should already be done. - if ((tree::TreeTraits::HasSelfChildren) && - (node.NumChildren() > 0) && - (node.Point(0) == node.Child(0).Point(0))) - { - selfKernel = node.Child(0).Stat().SelfKernel(); - } - else - { - selfKernel = sqrt(node.Metric().Kernel().Evaluate( - node.Dataset().col(node.Point(0)), - node.Dataset().col(node.Point(0)))); - } - } - else - { - // Calculate the centroid. - arma::vec center; - node.Center(center); - - selfKernel = sqrt(node.Metric().Kernel().Evaluate(center, center)); - } - } - - //! Get the self-kernel. - double SelfKernel() const { return selfKernel; } - //! Modify the self-kernel. - double& SelfKernel() { return selfKernel; } - - //! Get the bound. - double Bound() const { return bound; } - //! Modify the bound. - double& Bound() { return bound; } - - //! Get the last kernel evaluation. - double LastKernel() const { return lastKernel; } - //! Modify the last kernel evaluation. - double& LastKernel() { return lastKernel; } - - //! Get the address of the node corresponding to the last distance evaluation. - void* LastKernelNode() const { return lastKernelNode; } - //! Modify the address of the node corresponding to the last distance - //! evaluation. - void*& LastKernelNode() { return lastKernelNode; } - - //! Serialize the statistic. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(bound); - ar & BOOST_SERIALIZATION_NVP(selfKernel); - - // Void out last kernel information on load. - if (Archive::is_loading::value) - { - lastKernel = 0.0; - lastKernelNode = NULL; - } - } - - private: - //! The bound for pruning. - double bound; - - //! The self-kernel evaluation: sqrt(K(centroid, centroid)). - double selfKernel; - - //! The last kernel evaluation. - double lastKernel; - - //! The node corresponding to the last kernel evaluation. This has to be void - //! otherwise we get recursive template arguments. - void* lastKernelNode; -}; - -} // namespace fastmks -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/gmm/diagonal_constraint.hpp b/src/sdk/mlpack/include/mlpack/methods/gmm/diagonal_constraint.hpp deleted file mode 100644 index bb6c1e1ee..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/gmm/diagonal_constraint.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file diagonal_constraint.hpp - * @author Ryan Curtin - * - * Constrain a covariance matrix to be diagonal. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_GMM_DIAGONAL_CONSTRAINT_HPP -#define MLPACK_METHODS_GMM_DIAGONAL_CONSTRAINT_HPP - -#include - -namespace mlpack { -namespace gmm { - -/** - * Force a covariance matrix to be diagonal. - */ -class DiagonalConstraint -{ - public: - //! Force a covariance matrix to be diagonal. - static void ApplyConstraint(arma::mat& covariance) - { - // Save the diagonal only. - covariance = arma::diagmat(arma::clamp(covariance.diag(), 1e-10, DBL_MAX)); - } - - //! Serialize the constraint (which holds nothing, so, nothing to do). - template - static void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace gmm -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/gmm/eigenvalue_ratio_constraint.hpp b/src/sdk/mlpack/include/mlpack/methods/gmm/eigenvalue_ratio_constraint.hpp deleted file mode 100644 index 830960549..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/gmm/eigenvalue_ratio_constraint.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file eigenvalue_ratio_constraint.hpp - * @author Ryan Curtin - * - * Constrain a covariance matrix to have a certain ratio of eigenvalues. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_GMM_EIGENVALUE_RATIO_CONSTRAINT_HPP -#define MLPACK_METHODS_GMM_EIGENVALUE_RATIO_CONSTRAINT_HPP - -#include - -namespace mlpack { -namespace gmm { - -/** - * Given a vector of eigenvalue ratios, ensure that the covariance matrix always - * has those eigenvalue ratios. When you create this object, make sure that the - * vector of ratios that you pass does not go out of scope, because this object - * holds a reference to that vector instead of copying it. (This doesn't apply - * if you are deserializing the object from a file.) - */ -class EigenvalueRatioConstraint -{ - public: - /** - * Create the EigenvalueRatioConstraint object with the given vector of - * eigenvalue ratios. These ratios are with respect to the first eigenvalue, - * which is the largest eigenvalue, so the first element of the vector should - * be 1. In addition, all other elements should be less than or equal to 1. - */ - EigenvalueRatioConstraint(const arma::vec& ratios) : - // Make an alias of the ratios vector. It will never be modified here. - ratios(const_cast(ratios.memptr()), ratios.n_elem, false) - { - // Check validity of ratios. - if (std::abs(ratios[0] - 1.0) > 1e-20) - Log::Fatal << "EigenvalueRatioConstraint::EigenvalueRatioConstraint(): " - << "first element of ratio vector is not 1.0!" << std::endl; - - for (size_t i = 1; i < ratios.n_elem; ++i) - { - if (ratios[i] > 1.0) - Log::Fatal << "EigenvalueRatioConstraint::EigenvalueRatioConstraint(): " - << "element " << i << " of ratio vector is greater than 1.0!" - << std::endl; - if (ratios[i] < 0.0) - Log::Warn << "EigenvalueRatioConstraint::EigenvalueRatioConstraint(): " - << "element " << i << " of ratio vectors is negative and will " - << "probably cause the covariance to be non-invertible..." - << std::endl; - } - } - - /** - * Apply the eigenvalue ratio constraint to the given covariance matrix. - */ - void ApplyConstraint(arma::mat& covariance) const - { - // Eigendecompose the matrix. - arma::vec eigenvalues; - arma::mat eigenvectors; - arma::eig_sym(eigenvalues, eigenvectors, covariance); - - // Change the eigenvalues to what we are forcing them to be. There - // shouldn't be any negative eigenvalues anyway, so it doesn't matter if we - // are suddenly forcing them to be positive. If the first eigenvalue is - // negative, well, there are going to be some problems later... - eigenvalues = (eigenvalues[0] * ratios); - - // Reassemble the matrix. - covariance = eigenvectors * arma::diagmat(eigenvalues) * eigenvectors.t(); - } - - //! Serialize the constraint. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - // Strip the const for the sake of loading/saving. This is the only time it - // is modified (other than the constructor). - ar & BOOST_SERIALIZATION_NVP(const_cast(ratios)); - } - - private: - //! Ratios for eigenvalues. - const arma::vec ratios; -}; - -} // namespace gmm -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/gmm/em_fit.hpp b/src/sdk/mlpack/include/mlpack/methods/gmm/em_fit.hpp deleted file mode 100644 index ad89c8192..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/gmm/em_fit.hpp +++ /dev/null @@ -1,201 +0,0 @@ -/** - * @file em_fit.hpp - * @author Ryan Curtin - * @author Michael Fox - * - * Utility class to fit a GMM using the EM algorithm. Used by - * GMM::Estimate<>(). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_GMM_EM_FIT_HPP -#define MLPACK_METHODS_GMM_EM_FIT_HPP - -#include -#include - -// Default clustering mechanism. -#include -// Default covariance matrix constraint. -#include "positive_definite_constraint.hpp" - -namespace mlpack { -namespace gmm { - -/** - * This class contains methods which can fit a GMM to observations using the EM - * algorithm. It requires an initial clustering mechanism, which is by default - * the KMeans algorithm. The clustering mechanism must implement the following - * method: - * - * - void Cluster(const arma::mat& observations, - * const size_t clusters, - * arma::Row& assignments); - * - * This method should create 'clusters' clusters, and return the assignment of - * each point to a cluster. - */ -template, - typename CovarianceConstraintPolicy = PositiveDefiniteConstraint> -class EMFit -{ - public: - /** - * Construct the EMFit object, optionally passing an InitialClusteringType - * object (just in case it needs to store state). Setting the maximum number - * of iterations to 0 means that the EM algorithm will iterate until - * convergence (with the given tolerance). - * - * The parameter forcePositive controls whether or not the covariance matrices - * are checked for positive definiteness at each iteration. This could be a - * time-consuming task, so, if you know your data is well-behaved, you can set - * it to false and save some runtime. - * - * @param maxIterations Maximum number of iterations for EM. - * @param tolerance Log-likelihood tolerance required for convergence. - * @param forcePositive Check for positive-definiteness of each covariance - * matrix at each iteration. - * @param clusterer Object which will perform the initial clustering. - */ - EMFit(const size_t maxIterations = 300, - const double tolerance = 1e-10, - InitialClusteringType clusterer = InitialClusteringType(), - CovarianceConstraintPolicy constraint = CovarianceConstraintPolicy()); - - /** - * Fit the observations to a Gaussian mixture model (GMM) using the EM - * algorithm. The size of the vectors (indicating the number of components) - * must already be set. Optionally, if useInitialModel is set to true, then - * the model given in the means, covariances, and weights parameters is used - * as the initial model, instead of using the InitialClusteringType::Cluster() - * option. - * - * @param observations List of observations to train on. - * @param means Vector to store trained means in. - * @param covariances Vector to store trained covariances in. - * @param weights Vector to store a priori weights in. - * @param useInitialModel If true, the given model is used for the initial - * clustering. - */ - void Estimate(const arma::mat& observations, - std::vector& dists, - arma::vec& weights, - const bool useInitialModel = false); - - /** - * Fit the observations to a Gaussian mixture model (GMM) using the EM - * algorithm, taking into account the probabilities of each point being from - * this mixture. The size of the vectors (indicating the number of - * components) must already be set. Optionally, if useInitialModel is set to - * true, then the model given in the means, covariances, and weights - * parameters is used as the initial model, instead of using the - * InitialClusteringType::Cluster() option. - * - * @param observations List of observations to train on. - * @param probabilities Probability of each point being from this model. - * @param means Vector to store trained means in. - * @param covariances Vector to store trained covariances in. - * @param weights Vector to store a priori weights in. - * @param useInitialModel If true, the given model is used for the initial - * clustering. - */ - void Estimate(const arma::mat& observations, - const arma::vec& probabilities, - std::vector& dists, - arma::vec& weights, - const bool useInitialModel = false); - - //! Get the clusterer. - const InitialClusteringType& Clusterer() const { return clusterer; } - //! Modify the clusterer. - InitialClusteringType& Clusterer() { return clusterer; } - - //! Get the covariance constraint policy class. - const CovarianceConstraintPolicy& Constraint() const { return constraint; } - //! Modify the covariance constraint policy class. - CovarianceConstraintPolicy& Constraint() { return constraint; } - - //! Get the maximum number of iterations of the EM algorithm. - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations of the EM algorithm. - size_t& MaxIterations() { return maxIterations; } - - //! Get the tolerance for the convergence of the EM algorithm. - double Tolerance() const { return tolerance; } - //! Modify the tolerance for the convergence of the EM algorithm. - double& Tolerance() { return tolerance; } - - //! Serialize the fitter. - template - void serialize(Archive& ar, const unsigned int version); - - private: - /** - * Run the clusterer, and then turn the cluster assignments into Gaussians. - * This is a helper function for both overloads of Estimate(). The vectors - * must be already set to the number of clusters. - * - * @param observations List of observations. - * @param means Vector to store means in. - * @param covariances Vector to store covariances in. - * @param weights Vector to store a priori weights in. - */ - void InitialClustering(const arma::mat& observations, - std::vector& dists, - arma::vec& weights); - - /** - * Calculate the log-likelihood of a model. Yes, this is reimplemented in the - * GMM code. Intuition suggests that the log-likelihood is not the best way - * to determine if the EM algorithm has converged. - * - * @param data Data matrix. - * @param means Vector of means. - * @param covariances Vector of covariance matrices. - * @param weights Vector of a priori weights. - */ - double LogLikelihood(const arma::mat& data, - const std::vector& - dists, - const arma::vec& weights) const; - - // Armadillo uses uword internally as an OpenMP index type, which crashes - // Visual Studio. - #ifndef _WIN32 - /** - * Use the Armadillo gmm_diag clusterer to train a GMM with diagonal - * covariance. If InitialClusteringType == kmeans::KMeans<>, this will use - * Armadillo's initialization also. - * - * @param observations Data to train on. - * @param dists Distributions to store model in. - * @param weights Prior weights. - * @param useInitialModel If true, the existing model will be used. - */ - void ArmadilloGMMWrapper( - const arma::mat& observations, - std::vector& dists, - arma::vec& weights, - const bool useInitialModel); - #endif - - //! Maximum iterations of EM algorithm. - size_t maxIterations; - //! Tolerance for convergence of EM. - double tolerance; - //! Object which will perform the clustering. - InitialClusteringType clusterer; - //! Object which applies constraints to the covariance matrix. - CovarianceConstraintPolicy constraint; -}; - -} // namespace gmm -} // namespace mlpack - -// Include implementation. -#include "em_fit_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/gmm/em_fit_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/gmm/em_fit_impl.hpp deleted file mode 100644 index 8c5782664..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/gmm/em_fit_impl.hpp +++ /dev/null @@ -1,394 +0,0 @@ -/** - * @file em_fit_impl.hpp - * @author Ryan Curtin - * @author Michael Fox - * - * Implementation of EM algorithm for fitting GMMs. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_GMM_EM_FIT_IMPL_HPP -#define MLPACK_METHODS_GMM_EM_FIT_IMPL_HPP - -// In case it hasn't been included yet. -#include "em_fit.hpp" -#include "diagonal_constraint.hpp" - -namespace mlpack { -namespace gmm { - -//! Constructor. -template -EMFit::EMFit( - const size_t maxIterations, - const double tolerance, - InitialClusteringType clusterer, - CovarianceConstraintPolicy constraint) : - maxIterations(maxIterations), - tolerance(tolerance), - clusterer(clusterer), - constraint(constraint) -{ /* Nothing to do. */ } - -template -void EMFit::Estimate( - const arma::mat& observations, - std::vector& dists, - arma::vec& weights, - const bool useInitialModel) -{ - // Shortcut: if the user is using the DiagonalConstraint, then we will call - // out to Armadillo. But Armadillo uses uword internally as an OpenMP index - // type, which crashes Visual Studio, so don't do this on Windows. - #ifndef _WIN32 - if (std::is_same::value) - { - ArmadilloGMMWrapper(observations, dists, weights, useInitialModel); - return; - } - #endif - - // Only perform initial clustering if the user wanted it. - if (!useInitialModel) - InitialClustering(observations, dists, weights); - - double l = LogLikelihood(observations, dists, weights); - - Log::Debug << "EMFit::Estimate(): initial clustering log-likelihood: " - << l << std::endl; - - double lOld = -DBL_MAX; - arma::mat condProb(observations.n_cols, dists.size()); - - // Iterate to update the model until no more improvement is found. - size_t iteration = 1; - while (std::abs(l - lOld) > tolerance && iteration != maxIterations) - { - Log::Info << "EMFit::Estimate(): iteration " << iteration << ", " - << "log-likelihood " << l << "." << std::endl; - - // Calculate the conditional probabilities of choosing a particular - // Gaussian given the observations and the present theta value. - for (size_t i = 0; i < dists.size(); i++) - { - // Store conditional probabilities into condProb vector for each - // Gaussian. First we make an alias of the condProb vector. - arma::vec condProbAlias = condProb.unsafe_col(i); - dists[i].Probability(observations, condProbAlias); - condProbAlias *= weights[i]; - } - - // Normalize row-wise. - for (size_t i = 0; i < condProb.n_rows; i++) - { - // Avoid dividing by zero; if the probability for everything is 0, we - // don't want to make it NaN. - const double probSum = accu(condProb.row(i)); - if (probSum != 0.0) - condProb.row(i) /= probSum; - } - - // Store the sum of the probability of each state over all the observations. - arma::vec probRowSums = trans(arma::sum(condProb, 0 /* columnwise */)); - - // Calculate the new value of the means using the updated conditional - // probabilities. - for (size_t i = 0; i < dists.size(); i++) - { - // Don't update if there's no probability of the Gaussian having points. - if (probRowSums[i] != 0) - dists[i].Mean() = (observations * condProb.col(i)) / probRowSums[i]; - - // Calculate the new value of the covariances using the updated - // conditional probabilities and the updated means. - arma::mat tmp = observations - (dists[i].Mean() * - arma::ones(observations.n_cols)); - arma::mat tmpB = tmp % (arma::ones(observations.n_rows) * - trans(condProb.col(i))); - - // Don't update if there's no probability of the Gaussian having points. - if (probRowSums[i] != 0.0) - { - arma::mat covariance = (tmp * trans(tmpB)) / probRowSums[i]; - // Apply covariance constraint. - constraint.ApplyConstraint(covariance); - dists[i].Covariance(std::move(covariance)); - } - } - - // Calculate the new values for omega using the updated conditional - // probabilities. - weights = probRowSums / observations.n_cols; - - // Update values of l; calculate new log-likelihood. - lOld = l; - l = LogLikelihood(observations, dists, weights); - - iteration++; - } -} - -template -void EMFit::Estimate( - const arma::mat& observations, - const arma::vec& probabilities, - std::vector& dists, - arma::vec& weights, - const bool useInitialModel) -{ - if (!useInitialModel) - InitialClustering(observations, dists, weights); - - double l = LogLikelihood(observations, dists, weights); - - Log::Debug << "EMFit::Estimate(): initial clustering log-likelihood: " - << l << std::endl; - - double lOld = -DBL_MAX; - arma::mat condProb(observations.n_cols, dists.size()); - - // Iterate to update the model until no more improvement is found. - size_t iteration = 1; - while (std::abs(l - lOld) > tolerance && iteration != maxIterations) - { - // Calculate the conditional probabilities of choosing a particular - // Gaussian given the observations and the present theta value. - for (size_t i = 0; i < dists.size(); i++) - { - // Store conditional probabilities into condProb vector for each - // Gaussian. First we make an alias of the condProb vector. - arma::vec condProbAlias = condProb.unsafe_col(i); - dists[i].Probability(observations, condProbAlias); - condProbAlias *= weights[i]; - } - - // Normalize row-wise. - for (size_t i = 0; i < condProb.n_rows; i++) - { - // Avoid dividing by zero; if the probability for everything is 0, we - // don't want to make it NaN. - const double probSum = accu(condProb.row(i)); - if (probSum != 0.0) - condProb.row(i) /= probSum; - } - - // This will store the sum of probabilities of each state over all the - // observations. - arma::vec probRowSums(dists.size()); - - // Calculate the new value of the means using the updated conditional - // probabilities. - for (size_t i = 0; i < dists.size(); i++) - { - // Calculate the sum of probabilities of points, which is the - // conditional probability of each point being from Gaussian i - // multiplied by the probability of the point being from this mixture - // model. - probRowSums[i] = accu(condProb.col(i) % probabilities); - - dists[i].Mean() = (observations * (condProb.col(i) % probabilities)) / - probRowSums[i]; - - // Calculate the new value of the covariances using the updated - // conditional probabilities and the updated means. - arma::mat tmp = observations - (dists[i].Mean() * - arma::ones(observations.n_cols)); - arma::mat tmpB = tmp % (arma::ones(observations.n_rows) * - trans(condProb.col(i) % probabilities)); - - arma::mat cov = (tmp * trans(tmpB)) / probRowSums[i]; - - // Apply covariance constraint. - constraint.ApplyConstraint(cov); - - dists[i].Covariance(std::move(cov)); - } - - // Calculate the new values for omega using the updated conditional - // probabilities. - weights = probRowSums / accu(probabilities); - - // Update values of l; calculate new log-likelihood. - lOld = l; - l = LogLikelihood(observations, dists, weights); - - iteration++; - } -} - -template -void EMFit:: -InitialClustering(const arma::mat& observations, - std::vector& dists, - arma::vec& weights) -{ - // Assignments from clustering. - arma::Row assignments; - - // Run clustering algorithm. - clusterer.Cluster(observations, dists.size(), assignments); - - std::vector means(dists.size()); - std::vector covs(dists.size()); - - // Now calculate the means, covariances, and weights. - weights.zeros(); - for (size_t i = 0; i < dists.size(); ++i) - { - means[i].zeros(dists[i].Mean().n_elem); - covs[i].zeros(dists[i].Covariance().n_rows, - dists[i].Covariance().n_cols); - } - - // From the assignments, generate our means, covariances, and weights. - for (size_t i = 0; i < observations.n_cols; ++i) - { - const size_t cluster = assignments[i]; - - // Add this to the relevant mean. - means[cluster] += observations.col(i); - - // Add this to the relevant covariance. - covs[cluster] += observations.col(i) * trans(observations.col(i)); - - // Now add one to the weights (we will normalize). - weights[cluster]++; - } - - // Now normalize the mean and covariance. - for (size_t i = 0; i < dists.size(); ++i) - { - means[i] /= (weights[i] > 1) ? weights[i] : 1; - } - - for (size_t i = 0; i < observations.n_cols; ++i) - { - const size_t cluster = assignments[i]; - const arma::vec normObs = observations.col(i) - means[cluster]; - covs[cluster] += normObs * normObs.t(); - } - - for (size_t i = 0; i < dists.size(); ++i) - { - covs[i] /= (weights[i] > 1) ? weights[i] : 1; - - // Apply constraints to covariance matrix. - constraint.ApplyConstraint(covs[i]); - - std::swap(dists[i].Mean(), means[i]); - dists[i].Covariance(std::move(covs[i])); - } - - // Finally, normalize weights. - weights /= accu(weights); -} - -template -double EMFit::LogLikelihood( - const arma::mat& observations, - const std::vector& dists, - const arma::vec& weights) const -{ - double logLikelihood = 0; - - arma::vec phis; - arma::mat likelihoods(dists.size(), observations.n_cols); - - for (size_t i = 0; i < dists.size(); ++i) - { - dists[i].Probability(observations, phis); - likelihoods.row(i) = weights(i) * trans(phis); - } - // Now sum over every point. - for (size_t j = 0; j < observations.n_cols; ++j) - { - if (accu(likelihoods.col(j)) == 0) - Log::Info << "Likelihood of point " << j << " is 0! It is probably an " - << "outlier." << std::endl; - logLikelihood += log(accu(likelihoods.col(j))); - } - - return logLikelihood; -} - -template -template -void EMFit::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(maxIterations); - ar & BOOST_SERIALIZATION_NVP(tolerance); - ar & BOOST_SERIALIZATION_NVP(clusterer); - ar & BOOST_SERIALIZATION_NVP(constraint); -} - -// Armadillo uses uword internally as an OpenMP index type, which crashes Visual -// Studio. -#ifndef _WIN32 -template -void EMFit:: -ArmadilloGMMWrapper(const arma::mat& observations, - std::vector& dists, - arma::vec& weights, - const bool useInitialModel) -{ - arma::gmm_diag g; - - // Warn the user that tolerance isn't used for convergence here if they've - // specified a non-default value. - if (tolerance != EMFit().Tolerance()) - Log::Warn << "GMM::Train(): tolerance ignored when training GMMs with " - << "DiagonalConstraint." << std::endl; - - // If the initial clustering is the default k-means, we'll just use - // Armadillo's implementation. If mlpack ever changes k-means defaults to use - // something that is reliably quicker than the Lloyd iteration k-means update, - // then this code maybe should be revisited. - if (!std::is_same>::value || - useInitialModel) - { - // Use clusterer to get initial values. - if (!useInitialModel) - InitialClustering(observations, dists, weights); - - // Assemble matrix of means. - arma::mat means(observations.n_rows, dists.size()); - arma::mat covs(observations.n_rows, dists.size()); - for (size_t i = 0; i < dists.size(); ++i) - { - means.col(i) = dists[i].Mean(); - covs.col(i) = dists[i].Covariance().diag(); - } - - g.reset(observations.n_rows, dists.size()); - g.set_params(std::move(means), std::move(covs), weights.t()); - - g.learn(observations, dists.size(), arma::eucl_dist, arma::keep_existing, 0, - maxIterations, 1e-10, false /* no printing */); - } - else - { - // Use Armadillo for the initial clustering. We'll try and match mlpack - // defaults. - g.learn(observations, dists.size(), arma::eucl_dist, arma::static_subset, - 1000, maxIterations, 1e-10, false /* no printing */); - } - - // Extract means, covariances, and weights. - weights = g.hefts.t(); - for (size_t i = 0; i < dists.size(); ++i) - { - dists[i].Mean() = g.means.col(i); - dists[i].Covariance(arma::diagmat(g.dcovs.col(i))); - } -} -#endif - -} // namespace gmm -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/gmm/gmm.hpp b/src/sdk/mlpack/include/mlpack/methods/gmm/gmm.hpp deleted file mode 100644 index c8f0e908f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/gmm/gmm.hpp +++ /dev/null @@ -1,292 +0,0 @@ -/** - * @author Parikshit Ram (pram@cc.gatech.edu) - * @author Michael Fox - * @file gmm.hpp - * - * Defines a Gaussian Mixture model and estimates the parameters of the model. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_MOG_MOG_EM_HPP -#define MLPACK_METHODS_MOG_MOG_EM_HPP - -#include - -// This is the default fitting method class. -#include "em_fit.hpp" - -namespace mlpack { -namespace gmm /** Gaussian Mixture Models. */ { - -/** - * A Gaussian Mixture Model (GMM). This class uses maximum likelihood loss - * functions to estimate the parameters of the GMM on a given dataset via the - * given fitting mechanism, defined by the FittingType template parameter. The - * GMM can be trained using normal data, or data with probabilities of being - * from this GMM (see GMM::Train() for more information). - * - * The Train() method uses a template type 'FittingType'. The FittingType - * template class must provide a way for the GMM to train on data. It must - * provide the following two functions: - * - * @code - * void Estimate(const arma::mat& observations, - * std::vector& dists, - * arma::vec& weights); - * - * void Estimate(const arma::mat& observations, - * const arma::vec& probabilities, - * std::vector& dists, - * arma::vec& weights); - * @endcode - * - * These functions should produce a trained GMM from the given observations and - * probabilities. These may modify the size of the model (by increasing the - * size of the mean and covariance vectors as well as the weight vectors), but - * the method should expect that these vectors are already set to the size of - * the GMM as specified in the constructor. - * - * For a sample implementation, see the EMFit class; this class uses the EM - * algorithm to train a GMM, and is the default fitting type for the Train() - * method. - * - * The GMM, once trained, can be used to generate random points from the - * distribution and estimate the probability of points being from the - * distribution. The parameters of the GMM can be obtained through the - * accessors and mutators. - * - * Example use: - * - * @code - * // Set up a mixture of 5 gaussians in a 4-dimensional space. - * GMM g(5, 4); - * - * // Train the GMM given the data observations, using the default EM fitting - * // mechanism. - * g.Train(data); - * - * // Get the probability of 'observation' being observed from this GMM. - * double probability = g.Probability(observation); - * - * // Get a random observation from the GMM. - * arma::vec observation = g.Random(); - * @endcode - */ -class GMM -{ - private: - //! The number of Gaussians in the model. - size_t gaussians; - //! The dimensionality of the model. - size_t dimensionality; - - //! Vector of Gaussians - std::vector dists; - - //! Vector of a priori weights for each Gaussian. - arma::vec weights; - - public: - /** - * Create an empty Gaussian Mixture Model, with zero gaussians. - */ - GMM() : - gaussians(0), - dimensionality(0) - { - // Warn the user. They probably don't want to do this. If this constructor - // is being used (because it is required by some template classes), the user - // should know that it is potentially dangerous. - Log::Debug << "GMM::GMM(): no parameters given; Estimate() may fail " - << "unless parameters are set." << std::endl; - } - - /** - * Create a GMM with the given number of Gaussians, each of which have the - * specified dimensionality. The means and covariances will be set to 0. - * - * @param gaussians Number of Gaussians in this GMM. - * @param dimensionality Dimensionality of each Gaussian. - */ - GMM(const size_t gaussians, const size_t dimensionality); - - /** - * Create a GMM with the given dists and weights. - * - * @param dists Distributions of the model. - * @param weights Weights of the model. - */ - GMM(const std::vector & dists, - const arma::vec& weights) : - gaussians(dists.size()), - dimensionality((!dists.empty()) ? dists[0].Mean().n_elem : 0), - dists(dists), - weights(weights) { /* Nothing to do. */ } - - //! Copy constructor for GMMs. - GMM(const GMM& other); - - //! Copy operator for GMMs. - GMM& operator=(const GMM& other); - - //! Return the number of gaussians in the model. - size_t Gaussians() const { return gaussians; } - //! Return the dimensionality of the model. - size_t Dimensionality() const { return dimensionality; } - - /** - * Return a const reference to a component distribution. - * - * @param i index of component. - */ - const distribution::GaussianDistribution& Component(size_t i) const { - return dists[i]; } - /** - * Return a reference to a component distribution. - * - * @param i index of component. - */ - distribution::GaussianDistribution& Component(size_t i) { return dists[i]; } - - //! Return a const reference to the a priori weights of each Gaussian. - const arma::vec& Weights() const { return weights; } - //! Return a reference to the a priori weights of each Gaussian. - arma::vec& Weights() { return weights; } - - /** - * Return the probability that the given observation came from this - * distribution. - * - * @param observation Observation to evaluate the probability of. - */ - double Probability(const arma::vec& observation) const; - - /** - * Return the probability that the given observation came from the given - * Gaussian component in this distribution. - * - * @param observation Observation to evaluate the probability of. - * @param component Index of the component of the GMM to be considered. - */ - double Probability(const arma::vec& observation, - const size_t component) const; - - /** - * Return a randomly generated observation according to the probability - * distribution defined by this object. - * - * @return Random observation from this GMM. - */ - arma::vec Random() const; - - /** - * Estimate the probability distribution directly from the given observations, - * using the given algorithm in the FittingType class to fit the data. - * - * The fitting will be performed 'trials' times; from these trials, the model - * with the greatest log-likelihood will be selected. By default, only one - * trial is performed. The log-likelihood of the best fitting is returned. - * - * Optionally, the existing model can be used as an initial model for the - * estimation by setting 'useExistingModel' to true. If the fitting procedure - * is deterministic after the initial position is given, then 'trials' should - * be set to 1. - * - * @tparam FittingType The type of fitting method which should be used - * (EMFit<> is suggested). - * @param observations Observations of the model. - * @param trials Number of trials to perform; the model in these trials with - * the greatest log-likelihood will be selected. - * @param useExistingModel If true, the existing model is used as an initial - * model for the estimation. - * @return The log-likelihood of the best fit. - */ - template> - double Train(const arma::mat& observations, - const size_t trials = 1, - const bool useExistingModel = false, - FittingType fitter = FittingType()); - - /** - * Estimate the probability distribution directly from the given observations, - * taking into account the probability of each observation actually being from - * this distribution, and using the given algorithm in the FittingType class - * to fit the data. - * - * The fitting will be performed 'trials' times; from these trials, the model - * with the greatest log-likelihood will be selected. By default, only one - * trial is performed. The log-likelihood of the best fitting is returned. - * - * Optionally, the existing model can be used as an initial model for the - * estimation by setting 'useExistingModel' to true. If the fitting procedure - * is deterministic after the initial position is given, then 'trials' should - * be set to 1. - * - * @param observations Observations of the model. - * @param probabilities Probability of each observation being from this - * distribution. - * @param trials Number of trials to perform; the model in these trials with - * the greatest log-likelihood will be selected. - * @param useExistingModel If true, the existing model is used as an initial - * model for the estimation. - * @return The log-likelihood of the best fit. - */ - template> - double Train(const arma::mat& observations, - const arma::vec& probabilities, - const size_t trials = 1, - const bool useExistingModel = false, - FittingType fitter = FittingType()); - - /** - * Classify the given observations as being from an individual component in - * this GMM. The resultant classifications are stored in the 'labels' object, - * and each label will be between 0 and (Gaussians() - 1). Supposing that a - * point was classified with label 2, and that our GMM object was called - * 'gmm', one could access the relevant Gaussian distribution as follows: - * - * @code - * arma::vec mean = gmm.Means()[2]; - * arma::mat covariance = gmm.Covariances()[2]; - * double priorWeight = gmm.Weights()[2]; - * @endcode - * - * @param observations List of observations to classify. - * @param labels Object which will be filled with labels. - */ - void Classify(const arma::mat& observations, - arma::Row& labels) const; - - /** - * Serialize the GMM. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /** - * This function computes the loglikelihood of the given model. This function - * is used by GMM::Train(). - * - * @param dataPoints Observations to calculate the likelihood for. - * @param means Means of the given mixture model. - * @param covars Covariances of the given mixture model. - * @param weights Weights of the given mixture model. - */ - double LogLikelihood( - const arma::mat& dataPoints, - const std::vector& distsL, - const arma::vec& weights) const; -}; - -} // namespace gmm -} // namespace mlpack - -// Include implementation. -#include "gmm_impl.hpp" - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/gmm/gmm_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/gmm/gmm_impl.hpp deleted file mode 100644 index 2662f062f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/gmm/gmm_impl.hpp +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @file gmm_impl.hpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * @author Ryan Curtin - * @author Michael Fox - * - * Implementation of template-based GMM methods. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_GMM_GMM_IMPL_HPP -#define MLPACK_METHODS_GMM_GMM_IMPL_HPP - -// In case it hasn't already been included. -#include "gmm.hpp" - -namespace mlpack { -namespace gmm { - -/** - * Fit the GMM to the given observations. - */ -template -double GMM::Train(const arma::mat& observations, - const size_t trials, - const bool useExistingModel, - FittingType fitter) -{ - double bestLikelihood; // This will be reported later. - - // We don't need to store temporary models if we are only doing one trial. - if (trials == 1) - { - // Train the model. The user will have been warned earlier if the GMM was - // initialized with no parameters (0 gaussians, dimensionality of 0). - fitter.Estimate(observations, dists, weights, useExistingModel); - bestLikelihood = LogLikelihood(observations, dists, weights); - } - else - { - if (trials == 0) - return -DBL_MAX; // It's what they asked for... - - // If each trial must start from the same initial location, we must save it. - std::vector distsOrig; - arma::vec weightsOrig; - if (useExistingModel) - { - distsOrig = dists; - weightsOrig = weights; - } - - // We need to keep temporary copies. We'll do the first training into the - // actual model position, so that if it's the best we don't need to copy it. - fitter.Estimate(observations, dists, weights, useExistingModel); - - bestLikelihood = LogLikelihood(observations, dists, weights); - - Log::Info << "GMM::Train(): Log-likelihood of trial 0 is " - << bestLikelihood << "." << std::endl; - - // Now the temporary model. - std::vector distsTrial(gaussians, - distribution::GaussianDistribution(dimensionality)); - arma::vec weightsTrial(gaussians); - - for (size_t trial = 1; trial < trials; ++trial) - { - if (useExistingModel) - { - distsTrial = distsOrig; - weightsTrial = weightsOrig; - } - - fitter.Estimate(observations, distsTrial, weightsTrial, useExistingModel); - - // Check to see if the log-likelihood of this one is better. - double newLikelihood = LogLikelihood(observations, distsTrial, - weightsTrial); - - Log::Info << "GMM::Train(): Log-likelihood of trial " << trial << " is " - << newLikelihood << "." << std::endl; - - if (newLikelihood > bestLikelihood) - { - // Save new likelihood and copy new model. - bestLikelihood = newLikelihood; - - dists = distsTrial; - weights = weightsTrial; - } - } - } - - // Report final log-likelihood and return it. - Log::Info << "GMM::Train(): log-likelihood of trained GMM is " - << bestLikelihood << "." << std::endl; - return bestLikelihood; -} - -/** - * Fit the GMM to the given observations, each of which has a certain - * probability of being from this distribution. - */ -template -double GMM::Train(const arma::mat& observations, - const arma::vec& probabilities, - const size_t trials, - const bool useExistingModel, - FittingType fitter) -{ - double bestLikelihood; // This will be reported later. - - // We don't need to store temporary models if we are only doing one trial. - if (trials == 1) - { - // Train the model. The user will have been warned earlier if the GMM was - // initialized with no parameters (0 gaussians, dimensionality of 0). - fitter.Estimate(observations, probabilities, dists, weights, - useExistingModel); - bestLikelihood = LogLikelihood(observations, dists, weights); - } - else - { - if (trials == 0) - return -DBL_MAX; // It's what they asked for... - - // If each trial must start from the same initial location, we must save it. - std::vector distsOrig; - arma::vec weightsOrig; - if (useExistingModel) - { - distsOrig = dists; - weightsOrig = weights; - } - - // We need to keep temporary copies. We'll do the first training into the - // actual model position, so that if it's the best we don't need to copy it. - fitter.Estimate(observations, probabilities, dists, weights, - useExistingModel); - - bestLikelihood = LogLikelihood(observations, dists, weights); - - Log::Debug << "GMM::Train(): Log-likelihood of trial 0 is " - << bestLikelihood << "." << std::endl; - - // Now the temporary model. - std::vector distsTrial(gaussians, - distribution::GaussianDistribution(dimensionality)); - arma::vec weightsTrial(gaussians); - - for (size_t trial = 1; trial < trials; ++trial) - { - if (useExistingModel) - { - distsTrial = distsOrig; - weightsTrial = weightsOrig; - } - - fitter.Estimate(observations, probabilities, distsTrial, weightsTrial, - useExistingModel); - - // Check to see if the log-likelihood of this one is better. - double newLikelihood = LogLikelihood(observations, distsTrial, - weightsTrial); - - Log::Debug << "GMM::Train(): Log-likelihood of trial " << trial << " is " - << newLikelihood << "." << std::endl; - - if (newLikelihood > bestLikelihood) - { - // Save new likelihood and copy new model. - bestLikelihood = newLikelihood; - - dists = distsTrial; - weights = weightsTrial; - } - } - } - - // Report final log-likelihood and return it. - Log::Info << "GMM::Train(): log-likelihood of trained GMM is " - << bestLikelihood << "." << std::endl; - return bestLikelihood; -} - -/** - * Serialize the object. - */ -template -void GMM::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(gaussians); - ar & BOOST_SERIALIZATION_NVP(dimensionality); - - // Load (or save) the gaussians. Not going to use the default std::vector - // serialize here because it won't call out correctly to serialize() for each - // Gaussian distribution. - if (Archive::is_loading::value) - dists.resize(gaussians); - - ar & BOOST_SERIALIZATION_NVP(dists); - - ar & BOOST_SERIALIZATION_NVP(weights); -} - -} // namespace gmm -} // namespace mlpack - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/gmm/no_constraint.hpp b/src/sdk/mlpack/include/mlpack/methods/gmm/no_constraint.hpp deleted file mode 100644 index 22ccf16e4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/gmm/no_constraint.hpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @file no_constraint.hpp - * @author Ryan Curtin - * - * No constraint on the covariance matrix. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_GMM_NO_CONSTRAINT_HPP -#define MLPACK_METHODS_GMM_NO_CONSTRAINT_HPP - -#include - -namespace mlpack { -namespace gmm { - -/** - * This class enforces no constraint on the covariance matrix. It's faster this - * way, although depending on your situation you may end up with a - * non-invertible covariance matrix. - */ -class NoConstraint -{ - public: - //! Do nothing, and do not modify the covariance matrix. - static void ApplyConstraint(const arma::mat& /* covariance */) { } - - //! Serialize the object (nothing to do). - template - static void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace gmm -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/gmm/positive_definite_constraint.hpp b/src/sdk/mlpack/include/mlpack/methods/gmm/positive_definite_constraint.hpp deleted file mode 100644 index 517c9d354..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/gmm/positive_definite_constraint.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file positive_definite_constraint.hpp - * @author Ryan Curtin - * - * Restricts a covariance matrix to being positive definite. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_GMM_POSITIVE_DEFINITE_CONSTRAINT_HPP -#define MLPACK_METHODS_GMM_POSITIVE_DEFINITE_CONSTRAINT_HPP - -#include - -namespace mlpack { -namespace gmm { - -/** - * Given a covariance matrix, force the matrix to be positive definite. Also - * force a minimum value on the diagonal, so that even if the matrix is - * invertible, it doesn't cause problems with Cholesky decompositions. The - * forcing here is also done in order to bring the condition number of the - * matrix under 1e5 (10k), which should help with numerical stability. - */ -class PositiveDefiniteConstraint -{ - public: - /** - * Apply the positive definiteness constraint to the given covariance matrix, - * and ensure each value on the diagonal is at least 1e-50. - * - * @param covariance Covariance matrix. - */ - static void ApplyConstraint(arma::mat& covariance) - { - // What we want to do is make sure that the matrix is positive definite and - // that the condition number isn't too large. We also need to ensure that - // the covariance matrix is not too close to zero (hence, we ensure that all - // eigenvalues are at least 1e-50). - arma::vec eigval; - arma::mat eigvec; - arma::eig_sym(eigval, eigvec, covariance); - - // If the matrix is not positive definite or if the condition number is - // large, we must project it back onto the cone of positive definite - // matrices with reasonable condition number (I'm picking 1e5 here, not for - // any particular reason). - if ((eigval[0] < 0.0) || ((eigval[eigval.n_elem - 1] / eigval[0]) > 1e5) || - (eigval[eigval.n_elem - 1] < 1e-50)) - { - // Project any negative eigenvalues back to non-negative, and project any - // too-small eigenvalues to a large enough value. Make them as small as - // possible to satisfy our constraint on the condition number. - const double minEigval = std::max(eigval[eigval.n_elem - 1] / 1e5, 1e-50); - for (size_t i = 0; i < eigval.n_elem; ++i) - eigval[i] = std::max(eigval[i], minEigval); - - // Now reassemble the covariance matrix. - covariance = eigvec * arma::diagmat(eigval) * eigvec.t(); - } - } - - //! Serialize the constraint (which stores nothing, so, nothing to do). - template - static void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace gmm -} // namespace mlpack - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm.hpp b/src/sdk/mlpack/include/mlpack/methods/hmm/hmm.hpp deleted file mode 100644 index 0e902896f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm.hpp +++ /dev/null @@ -1,385 +0,0 @@ -/** - * @file hmm.hpp - * @author Ryan Curtin - * @author Tran Quoc Long - * @author Michael Fox - * - * Definition of HMM class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HMM_HMM_HPP -#define MLPACK_METHODS_HMM_HMM_HPP - -#include -#include - -namespace mlpack { -namespace hmm /** Hidden Markov Models. */ { - -/** - * A class that represents a Hidden Markov Model with an arbitrary type of - * emission distribution. This HMM class supports training (supervised and - * unsupervised), prediction of state sequences via the Viterbi algorithm, - * estimation of state probabilities, generation of random sequences, and - * calculation of the log-likelihood of a given sequence. - * - * The template parameter, Distribution, specifies the distribution which the - * emissions follow. The class should implement the following functions: - * - * @code - * class Distribution - * { - * public: - * // The type of observation used by this distribution. - * typedef something DataType; - * - * // Return the probability of the given observation. - * double Probability(const DataType& observation) const; - * - * // Estimate the distribution based on the given observations. - * void Train(const std::vector& observations); - * - * // Estimate the distribution based on the given observations, given also - * // the probability of each observation coming from this distribution. - * void Train(const std::vector& observations, - * const std::vector& probabilities); - * }; - * @endcode - * - * See the mlpack::distribution::DiscreteDistribution class for an example. One - * would use the DiscreteDistribution class when the observations are - * non-negative integers. Other distributions could be Gaussians, a mixture of - * Gaussians (GMM), or any other probability distribution implementing the - * four Distribution functions. - * - * Usage of the HMM class generally involves either training an HMM or loading - * an already-known HMM and taking probability measurements of sequences. - * Example code for supervised training of a Gaussian HMM (that is, where the - * emission output distribution is a single Gaussian for each hidden state) is - * given below. - * - * @code - * extern arma::mat observations; // Each column is an observation. - * extern arma::Row states; // Hidden states for each observation. - * // Create an untrained HMM with 5 hidden states and default (N(0, 1)) - * // Gaussian distributions with the dimensionality of the dataset. - * HMM hmm(5, GaussianDistribution(observations.n_rows)); - * - * // Train the HMM (the labels could be omitted to perform unsupervised - * // training). - * hmm.Train(observations, states); - * @endcode - * - * Once initialized, the HMM can evaluate the probability of a certain sequence - * (with LogLikelihood()), predict the most likely sequence of hidden states - * (with Predict()), generate a sequence (with Generate()), or estimate the - * probabilities of each state for a sequence of observations (with Train()). - * - * @tparam Distribution Type of emission distribution for this HMM. - */ -template -class HMM -{ - public: - /** - * Create the Hidden Markov Model with the given number of hidden states and - * the given default distribution for emissions. The dimensionality of the - * observations is taken from the emissions variable, so it is important that - * the given default emission distribution is set with the correct - * dimensionality. Alternately, set the dimensionality with Dimensionality(). - * Optionally, the tolerance for convergence of the Baum-Welch algorithm can - * be set. - * - * By default, the transition matrix and initial probability vector are set to - * contain equal probability for each state. - * - * @param states Number of states. - * @param emissions Default distribution for emissions. - * @param tolerance Tolerance for convergence of training algorithm - * (Baum-Welch). - */ - HMM(const size_t states = 0, - const Distribution emissions = Distribution(), - const double tolerance = 1e-5); - - /** - * Create the Hidden Markov Model with the given initial probability vector, - * the given transition matrix, and the given emission distributions. The - * dimensionality of the observations of the HMM are taken from the given - * emission distributions. Alternately, the dimensionality can be set with - * Dimensionality(). - * - * The initial state probability vector should have length equal to the number - * of states, and each entry represents the probability of being in the given - * state at time T = 0 (the beginning of a sequence). - * - * The transition matrix should be such that T(i, j) is the probability of - * transition to state i from state j. The columns of the matrix should sum - * to 1. - * - * The emission matrix should be such that E(i, j) is the probability of - * emission i while in state j. The columns of the matrix should sum to 1. - * - * Optionally, the tolerance for convergence of the Baum-Welch algorithm can - * be set. - * - * @param initial Initial state probabilities. - * @param transition Transition matrix. - * @param emission Emission distributions. - * @param tolerance Tolerance for convergence of training algorithm - * (Baum-Welch). - */ - HMM(const arma::vec& initial, - const arma::mat& transition, - const std::vector& emission, - const double tolerance = 1e-5); - - /** - * Train the model using the Baum-Welch algorithm, with only the given - * unlabeled observations. Instead of giving a guess transition and emission - * matrix here, do that in the constructor. Each matrix in the vector of data - * sequences holds an individual data sequence; each point in each individual - * data sequence should be a column in the matrix. The number of rows in each - * matrix should be equal to the dimensionality of the HMM (which is set in - * the constructor). - * - * It is preferable to use the other overload of Train(), with labeled data. - * That will produce much better results. However, if labeled data is - * unavailable, this will work. In addition, it is possible to use Train() - * with labeled data first, and then continue to train the model using this - * overload of Train() with unlabeled data. - * - * The tolerance of the Baum-Welch algorithm can be set either in the - * constructor or with the Tolerance() method. When the change in - * log-likelihood of the model between iterations is less than the tolerance, - * the Baum-Welch algorithm terminates. - * - * @note - * Train() can be called multiple times with different sequences; each time it - * is called, it uses the current parameters of the HMM as a starting point - * for training. - * @endnote - * - * @param dataSeq Vector of observation sequences. - */ - void Train(const std::vector& dataSeq); - - /** - * Train the model using the given labeled observations; the transition and - * emission matrices are directly estimated. Each matrix in the vector of - * data sequences corresponds to a vector in the vector of state sequences. - * Each point in each individual data sequence should be a column in the - * matrix, and its state should be the corresponding element in the state - * sequence vector. For instance, dataSeq[0].col(3) corresponds to the fourth - * observation in the first data sequence, and its state is stateSeq[0][3]. - * The number of rows in each matrix should be equal to the dimensionality of - * the HMM (which is set in the constructor). - * - * @note - * Train() can be called multiple times with different sequences; each time it - * is called, it uses the current parameters of the HMM as a starting point - * for training. - * @endnote - * - * @param dataSeq Vector of observation sequences. - * @param stateSeq Vector of state sequences, corresponding to each - * observation. - */ - void Train(const std::vector& dataSeq, - const std::vector >& stateSeq); - - /** - * Estimate the probabilities of each hidden state at each time step for each - * given data observation, using the Forward-Backward algorithm. Each matrix - * which is returned has columns equal to the number of data observations, and - * rows equal to the number of hidden states in the model. The log-likelihood - * of the most probable sequence is returned. - * - * @param dataSeq Sequence of observations. - * @param stateProb Matrix in which the probabilities of each state at each - * time interval will be stored. - * @param forwardProb Matrix in which the forward probabilities of each state - * at each time interval will be stored. - * @param backwardProb Matrix in which the backward probabilities of each - * state at each time interval will be stored. - * @param scales Vector in which the scaling factors at each time interval - * will be stored. - * @return Log-likelihood of most likely state sequence. - */ - double Estimate(const arma::mat& dataSeq, - arma::mat& stateProb, - arma::mat& forwardProb, - arma::mat& backwardProb, - arma::vec& scales) const; - - /** - * Estimate the probabilities of each hidden state at each time step of each - * given data observation, using the Forward-Backward algorithm. The returned - * matrix of state probabilities has columns equal to the number of data - * observations, and rows equal to the number of hidden states in the model. - * The log-likelihood of the most probable sequence is returned. - * - * @param dataSeq Sequence of observations. - * @param stateProb Probabilities of each state at each time interval. - * @return Log-likelihood of most likely state sequence. - */ - double Estimate(const arma::mat& dataSeq, - arma::mat& stateProb) const; - - /** - * Generate a random data sequence of the given length. The data sequence is - * stored in the dataSequence parameter, and the state sequence is stored in - * the stateSequence parameter. Each column of dataSequence represents a - * random observation. - * - * @param length Length of random sequence to generate. - * @param dataSequence Vector to store data in. - * @param stateSequence Vector to store states in. - * @param startState Hidden state to start sequence in (default 0). - */ - void Generate(const size_t length, - arma::mat& dataSequence, - arma::Row& stateSequence, - const size_t startState = 0) const; - - /** - * Compute the most probable hidden state sequence for the given data - * sequence, using the Viterbi algorithm, returning the log-likelihood of the - * most likely state sequence. - * - * @param dataSeq Sequence of observations. - * @param stateSeq Vector in which the most probable state sequence will be - * stored. - * @return Log-likelihood of most probable state sequence. - */ - double Predict(const arma::mat& dataSeq, - arma::Row& stateSeq) const; - - /** - * Compute the log-likelihood of the given data sequence. - * - * @param dataSeq Data sequence to evaluate the likelihood of. - * @return Log-likelihood of the given sequence. - */ - double LogLikelihood(const arma::mat& dataSeq) const; - - /** - * HMM filtering. Computes the k-step-ahead expected emission at each time - * conditioned only on prior observations. That is - * E{ Y[t+k] | Y[0], ..., Y[t] }. - * The returned matrix has columns equal to the number of observations. Note - * that the expectation may not be meaningful for discrete emissions. - * - * @param dataSeq Sequence of observations. - * @param filterSeq Vector in which the expected emission sequence will be - * stored. - * @param ahead Number of steps ahead (k) for expectations. - */ - void Filter(const arma::mat& dataSeq, - arma::mat& filterSeq, - size_t ahead = 0) const; - - /** - * HMM smoothing. Computes expected emission at each time conditioned on all - * observations. That is - * E{ Y[t] | Y[0], ..., Y[T] }. - * The returned matrix has columns equal to the number of observations. Note - * that the expectation may not be meaningful for discrete emissions. - * - * @param dataSeq Sequence of observations. - * @param smoothSeq Vector in which the expected emission sequence will be - * stored. - */ - void Smooth(const arma::mat& dataSeq, - arma::mat& smoothSeq) const; - - //! Return the vector of initial state probabilities. - const arma::vec& Initial() const { return initial; } - //! Modify the vector of initial state probabilities. - arma::vec& Initial() { return initial; } - - //! Return the transition matrix. - const arma::mat& Transition() const { return transition; } - //! Return a modifiable transition matrix reference. - arma::mat& Transition() { return transition; } - - //! Return the emission distributions. - const std::vector& Emission() const { return emission; } - //! Return a modifiable emission probability matrix reference. - std::vector& Emission() { return emission; } - - //! Get the dimensionality of observations. - size_t Dimensionality() const { return dimensionality; } - //! Set the dimensionality of observations. - size_t& Dimensionality() { return dimensionality; } - - //! Get the tolerance of the Baum-Welch algorithm. - double Tolerance() const { return tolerance; } - //! Modify the tolerance of the Baum-Welch algorithm. - double& Tolerance() { return tolerance; } - - /** - * Serialize the object. - */ - template - void serialize(Archive& ar, const unsigned int version); - - protected: - // Helper functions. - /** - * The Forward algorithm (part of the Forward-Backward algorithm). Computes - * forward probabilities for each state for each observation in the given data - * sequence. The returned matrix has rows equal to the number of hidden - * states and columns equal to the number of observations. - * - * @param dataSeq Data sequence to compute probabilities for. - * @param scales Vector in which scaling factors will be saved. - * @param forwardProb Matrix in which forward probabilities will be saved. - */ - void Forward(const arma::mat& dataSeq, - arma::vec& scales, - arma::mat& forwardProb) const; - - /** - * The Backward algorithm (part of the Forward-Backward algorithm). Computes - * backward probabilities for each state for each observation in the given - * data sequence, using the scaling factors found (presumably) by Forward(). - * The returned matrix has rows equal to the number of hidden states and - * columns equal to the number of observations. - * - * @param dataSeq Data sequence to compute probabilities for. - * @param scales Vector of scaling factors. - * @param backwardProb Matrix in which backward probabilities will be saved. - */ - void Backward(const arma::mat& dataSeq, - const arma::vec& scales, - arma::mat& backwardProb) const; - - //! Set of emission probability distributions; one for each state. - std::vector emission; - - //! Transition probability matrix. - arma::mat transition; - - private: - //! Initial state probability vector. - arma::vec initial; - - //! Dimensionality of observations. - size_t dimensionality; - - //! Tolerance of Baum-Welch algorithm. - double tolerance; -}; - -} // namespace hmm -} // namespace mlpack - -// Include implementation. -#include "hmm_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_impl.hpp deleted file mode 100644 index 5fc711f68..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_impl.hpp +++ /dev/null @@ -1,609 +0,0 @@ -/** - * @file hmm_impl.hpp - * @author Ryan Curtin - * @author Tran Quoc Long - * @author Michael Fox - * - * Implementation of HMM class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HMM_HMM_IMPL_HPP -#define MLPACK_METHODS_HMM_HMM_IMPL_HPP - -// Just in case... -#include "hmm.hpp" - -namespace mlpack { -namespace hmm { - -/** - * Create the Hidden Markov Model with the given number of hidden states and the - * given number of emission states. - */ -template -HMM::HMM(const size_t states, - const Distribution emissions, - const double tolerance) : - emission(states, /* default distribution */ emissions), - transition(arma::randu(states, states)), - initial(arma::randu(states) / (double) states), - dimensionality(emissions.Dimensionality()), - tolerance(tolerance) -{ - // Normalize the transition probabilities and initial state probabilities. - initial /= arma::accu(initial); - for (size_t i = 0; i < transition.n_cols; ++i) - transition.col(i) /= arma::accu(transition.col(i)); -} - -/** - * Create the Hidden Markov Model with the given transition matrix and the given - * emission probability matrix. - */ -template -HMM::HMM(const arma::vec& initial, - const arma::mat& transition, - const std::vector& emission, - const double tolerance) : - emission(emission), - transition(transition), - initial(initial), - tolerance(tolerance) -{ - // Set the dimensionality, if we can. - if (emission.size() > 0) - dimensionality = emission[0].Dimensionality(); - else - { - Log::Warn << "HMM::HMM(): no emission distributions given; assuming a " - << "dimensionality of 0 and hoping it gets set right later." - << std::endl; - dimensionality = 0; - } -} - -/** - * Train the model using the Baum-Welch algorithm, with only the given unlabeled - * observations. Each matrix in the vector of data sequences holds an - * individual data sequence; each point in each individual data sequence should - * be a column in the matrix. The number of rows in each matrix should be equal - * to the dimensionality of the HMM. - * - * It is preferable to use the other overload of Train(), with labeled data. - * That will produce much better results. However, if labeled data is - * unavailable, this will work. In addition, it is possible to use Train() with - * labeled data first, and then continue to train the model using this overload - * of Train() with unlabeled data. - * - * @param dataSeq Set of data sequences to train on. - */ -template -void HMM::Train(const std::vector& dataSeq) -{ - // We should allow a guess at the transition and emission matrices. - double loglik = 0; - double oldLoglik = 0; - - // Maximum iterations? - size_t iterations = 1000; - - // Find length of all sequences and ensure they are the correct size. - size_t totalLength = 0; - for (size_t seq = 0; seq < dataSeq.size(); seq++) - { - totalLength += dataSeq[seq].n_cols; - - if (dataSeq[seq].n_rows != dimensionality) - Log::Fatal << "HMM::Train(): data sequence " << seq << " has " - << "dimensionality " << dataSeq[seq].n_rows << " (expected " - << dimensionality << " dimensions)." << std::endl; - } - - // These are used later for training of each distribution. We initialize it - // all now so we don't have to do any allocation later on. - std::vector emissionProb(transition.n_cols, - arma::vec(totalLength)); - arma::mat emissionList(dimensionality, totalLength); - - // This should be the Baum-Welch algorithm (EM for HMM estimation). This - // follows the procedure outlined in Elliot, Aggoun, and Moore's book "Hidden - // Markov Models: Estimation and Control", pp. 36-40. - for (size_t iter = 0; iter < iterations; iter++) - { - // Clear new transition matrix and emission probabilities. - arma::vec newInitial(transition.n_rows); - newInitial.zeros(); - arma::mat newTransition(transition.n_rows, transition.n_cols); - newTransition.zeros(); - - // Reset log likelihood. - loglik = 0; - - // Sum over time. - size_t sumTime = 0; - - // Loop over each sequence. - for (size_t seq = 0; seq < dataSeq.size(); seq++) - { - arma::mat stateProb; - arma::mat forward; - arma::mat backward; - arma::vec scales; - - // Add the log-likelihood of this sequence. This is the E-step. - loglik += Estimate(dataSeq[seq], stateProb, forward, backward, scales); - - // Add to estimate of initial probability for state j. - for (size_t j = 0; j < transition.n_cols; ++j) - newInitial[j] += stateProb(j, 0); - - // Now re-estimate the parameters. This is the M-step. - // pi_i = sum_d ((1 / P(seq[d])) sum_t (f(i, 0) b(i, 0)) - // T_ij = sum_d ((1 / P(seq[d])) sum_t (f(i, t) T_ij E_i(seq[d][t]) b(i, - // t + 1))) - // E_ij = sum_d ((1 / P(seq[d])) sum_{t | seq[d][t] = j} f(i, t) b(i, t) - // We store the new estimates in a different matrix. - for (size_t t = 0; t < dataSeq[seq].n_cols; ++t) - { - for (size_t j = 0; j < transition.n_cols; ++j) - { - if (t < dataSeq[seq].n_cols - 1) - { - // Estimate of T_ij (probability of transition from state j to state - // i). We postpone multiplication of the old T_ij until later. - for (size_t i = 0; i < transition.n_rows; i++) - newTransition(i, j) += forward(j, t) * backward(i, t + 1) * - emission[i].Probability(dataSeq[seq].unsafe_col(t + 1)) / - scales[t + 1]; - } - - // Add to list of emission observations, for Distribution::Train(). - emissionList.col(sumTime) = dataSeq[seq].col(t); - emissionProb[j][sumTime] = stateProb(j, t); - } - sumTime++; - } - } - - if (std::abs(oldLoglik - loglik) < tolerance) - { - Log::Debug << "Converged after " << iter << " iterations." << std::endl; - break; - } - - oldLoglik = loglik; - - // Normalize the new initial probabilities. - if (dataSeq.size() > 1) - initial = newInitial / dataSeq.size(); - else - initial = newInitial; - - // Assign the new transition matrix. We use %= (element-wise - // multiplication) because every element of the new transition matrix must - // still be multiplied by the old elements (this is the multiplication we - // earlier postponed). - transition %= newTransition; - - // Now we normalize the transition matrix. - for (size_t i = 0; i < transition.n_cols; i++) - { - const double sum = accu(transition.col(i)); - if (sum > 0.0) - transition.col(i) /= sum; - else - transition.col(i).fill(1.0 / (double) transition.n_rows); - } - - // Now estimate emission probabilities. - for (size_t state = 0; state < transition.n_cols; state++) - emission[state].Train(emissionList, emissionProb[state]); - - Log::Debug << "Iteration " << iter << ": log-likelihood " << loglik - << "." << std::endl; - } -} - -/** - * Train the model using the given labeled observations; the transition and - * emission matrices are directly estimated. - */ -template -void HMM::Train(const std::vector& dataSeq, - const std::vector >& stateSeq) -{ - // Simple error checking. - if (dataSeq.size() != stateSeq.size()) - { - Log::Fatal << "HMM::Train(): number of data sequences (" << dataSeq.size() - << ") not equal to number of state sequences (" << stateSeq.size() - << ")." << std::endl; - } - - initial.zeros(); - transition.zeros(); - - // Estimate the transition and emission matrices directly from the - // observations. The emission list holds the time indices for observations - // from each state. - std::vector > > - emissionList(transition.n_cols); - for (size_t seq = 0; seq < dataSeq.size(); seq++) - { - // Simple error checking. - if (dataSeq[seq].n_cols != stateSeq[seq].n_elem) - { - Log::Fatal << "HMM::Train(): number of observations (" - << dataSeq[seq].n_cols << ") in sequence " << seq - << " not equal to number of states (" << stateSeq[seq].n_cols - << ") in sequence " << seq << "." << std::endl; - } - - if (dataSeq[seq].n_rows != dimensionality) - { - Log::Fatal << "HMM::Train(): data sequence " << seq << " has " - << "dimensionality " << dataSeq[seq].n_rows << " (expected " - << dimensionality << " dimensions)." << std::endl; - } - - // Loop over each observation in the sequence. For estimation of the - // transition matrix, we must ignore the last observation. - initial[stateSeq[seq][0]]++; - for (size_t t = 0; t < dataSeq[seq].n_cols - 1; t++) - { - transition(stateSeq[seq][t + 1], stateSeq[seq][t])++; - emissionList[stateSeq[seq][t]].push_back(std::make_pair(seq, t)); - } - - // Last observation. - emissionList[stateSeq[seq][stateSeq[seq].n_elem - 1]].push_back( - std::make_pair(seq, stateSeq[seq].n_elem - 1)); - } - - // Normalize initial weights. - initial /= accu(initial); - - // Normalize transition matrix. - for (size_t col = 0; col < transition.n_cols; col++) - { - // If the transition probability sum is greater than 0 in this column, the - // emission probability sum will also be greater than 0. We want to avoid - // division by 0. - double sum = accu(transition.col(col)); - if (sum > 0) - transition.col(col) /= sum; - } - - // Estimate emission matrix. - for (size_t state = 0; state < transition.n_cols; state++) - { - // Generate full sequence of observations for this state from the list of - // emissions that are from this state. - if (emissionList[state].size() > 0) - { - arma::mat emissions(dimensionality, emissionList[state].size()); - for (size_t i = 0; i < emissions.n_cols; i++) - { - emissions.col(i) = dataSeq[emissionList[state][i].first].col( - emissionList[state][i].second); - } - - emission[state].Train(emissions); - } - else - { - Log::Warn << "There are no observations in training data with hidden " - << "state " << state << "! The corresponding emission distribution " - << "is likely to be meaningless." << std::endl; - } - } -} - -/** - * Estimate the probabilities of each hidden state at each time step for each - * given data observation. - */ -template -double HMM::Estimate(const arma::mat& dataSeq, - arma::mat& stateProb, - arma::mat& forwardProb, - arma::mat& backwardProb, - arma::vec& scales) const -{ - // First run the forward-backward algorithm. - Forward(dataSeq, scales, forwardProb); - Backward(dataSeq, scales, backwardProb); - - // Now assemble the state probability matrix based on the forward and backward - // probabilities. - stateProb = forwardProb % backwardProb; - - // Finally assemble the log-likelihood and return it. - return accu(log(scales)); -} - -/** - * Estimate the probabilities of each hidden state at each time step for each - * given data observation. - */ -template -double HMM::Estimate(const arma::mat& dataSeq, - arma::mat& stateProb) const -{ - // We don't need to save these. - arma::mat forwardProb, backwardProb; - arma::vec scales; - - return Estimate(dataSeq, stateProb, forwardProb, backwardProb, scales); -} - -/** - * Generate a random data sequence of a given length. The data sequence is - * stored in the dataSequence parameter, and the state sequence is stored in - * the stateSequence parameter. - */ -template -void HMM::Generate(const size_t length, - arma::mat& dataSequence, - arma::Row& stateSequence, - const size_t startState) const -{ - // Set vectors to the right size. - stateSequence.set_size(length); - dataSequence.set_size(dimensionality, length); - - // Set start state (default is 0). - stateSequence[0] = startState; - - // Choose first emission state. - double randValue = math::Random(); - - // We just have to find where our random value sits in the probability - // distribution of emissions for our starting state. - dataSequence.col(0) = emission[startState].Random(); - - // Now choose the states and emissions for the rest of the sequence. - for (size_t t = 1; t < length; t++) - { - // First choose the hidden state. - randValue = math::Random(); - - // Now find where our random value sits in the probability distribution of - // state changes. - double probSum = 0; - for (size_t st = 0; st < transition.n_rows; st++) - { - probSum += transition(st, stateSequence[t - 1]); - if (randValue <= probSum) - { - stateSequence[t] = st; - break; - } - } - - // Now choose the emission. - dataSequence.col(t) = emission[stateSequence[t]].Random(); - } -} - -/** - * Compute the most probable hidden state sequence for the given observation - * using the Viterbi algorithm. Returns the log-likelihood of the most likely - * sequence. - */ -template -double HMM::Predict(const arma::mat& dataSeq, - arma::Row& stateSeq) const -{ - // This is an implementation of the Viterbi algorithm for finding the most - // probable sequence of states to produce the observed data sequence. We - // don't use log-likelihoods to save that little bit of time, but we'll - // calculate the log-likelihood at the end of it all. - stateSeq.set_size(dataSeq.n_cols); - arma::mat logStateProb(transition.n_rows, dataSeq.n_cols); - arma::mat stateSeqBack(transition.n_rows, dataSeq.n_cols); - - // Store the logs of the transposed transition matrix. This is because we - // will be using the rows of the transition matrix. - arma::mat logTrans(log(trans(transition))); - - // The calculation of the first state is slightly different; the probability - // of the first state being state j is the maximum probability that the state - // came to be j from another state. - logStateProb.col(0).zeros(); - for (size_t state = 0; state < transition.n_rows; state++) - { - logStateProb(state, 0) = log(initial[state] * - emission[state].Probability(dataSeq.unsafe_col(0))); - stateSeqBack(state, 0) = state; - } - - // Store the best first state. - arma::uword index; - for (size_t t = 1; t < dataSeq.n_cols; t++) - { - // Assemble the state probability for this element. - // Given that we are in state j, we use state with the highest probability - // of being the previous state. - for (size_t j = 0; j < transition.n_rows; j++) - { - arma::vec prob = logStateProb.col(t - 1) + logTrans.col(j); - logStateProb(j, t) = prob.max(index) + - log(emission[j].Probability(dataSeq.unsafe_col(t))); - stateSeqBack(j, t) = index; - } - } - - // Backtrack to find the most probable state sequence. - logStateProb.unsafe_col(dataSeq.n_cols - 1).max(index); - stateSeq[dataSeq.n_cols - 1] = index; - for (size_t t = 2; t <= dataSeq.n_cols; t++) - stateSeq[dataSeq.n_cols - t] = - stateSeqBack(stateSeq[dataSeq.n_cols - t + 1], dataSeq.n_cols - t + 1); - - return logStateProb(stateSeq(dataSeq.n_cols - 1), dataSeq.n_cols - 1); -} - -/** - * Compute the log-likelihood of the given data sequence. - */ -template -double HMM::LogLikelihood(const arma::mat& dataSeq) const -{ - arma::mat forward; - arma::vec scales; - - Forward(dataSeq, scales, forward); - - // The log-likelihood is the log of the scales for each time step. - return accu(log(scales)); -} - -/** - * HMM filtering. - */ -template -void HMM::Filter(const arma::mat& dataSeq, - arma::mat& filterSeq, - size_t ahead) const -{ - // First run the forward algorithm. - arma::mat forwardProb; - arma::vec scales; - Forward(dataSeq, scales, forwardProb); - - // Propagate state ahead. - if (ahead != 0) - forwardProb = pow(transition, ahead) * forwardProb; - - // Compute expected emissions. - // Will not work for distributions without a Mean() function. - filterSeq.zeros(dimensionality, dataSeq.n_cols); - for (size_t i = 0; i < emission.size(); i++) - filterSeq += emission[i].Mean() * forwardProb.row(i); -} - -/** - * HMM smoothing. - */ -template -void HMM::Smooth(const arma::mat& dataSeq, - arma::mat& smoothSeq) const -{ - // First run the forward algorithm. - arma::mat stateProb; - Estimate(dataSeq, stateProb); - - // Compute expected emissions. - // Will not work for distributions without a Mean() function. - smoothSeq.zeros(dimensionality, dataSeq.n_cols); - for (size_t i = 0; i < emission.size(); i++) - smoothSeq += emission[i].Mean() * stateProb.row(i); -} - -/** - * The Forward procedure (part of the Forward-Backward algorithm). - */ -template -void HMM::Forward(const arma::mat& dataSeq, - arma::vec& scales, - arma::mat& forwardProb) const -{ - // Our goal is to calculate the forward probabilities: - // P(X_k | o_{1:k}) for all possible states X_k, for each time point k. - forwardProb.zeros(transition.n_rows, dataSeq.n_cols); - scales.zeros(dataSeq.n_cols); - - // The first entry in the forward algorithm uses the initial state - // probabilities. Note that MATLAB assumes that the starting state (at - // t = -1) is state 0; this is not our assumption here. To force that - // behavior, you could append a single starting state to every single data - // sequence and that should produce results in line with MATLAB. - for (size_t state = 0; state < transition.n_rows; state++) - forwardProb(state, 0) = initial(state) * - emission[state].Probability(dataSeq.unsafe_col(0)); - - // Then normalize the column. - scales[0] = accu(forwardProb.col(0)); - if (scales[0] > 0.0) - forwardProb.col(0) /= scales[0]; - - // Now compute the probabilities for each successive observation. - for (size_t t = 1; t < dataSeq.n_cols; t++) - { - for (size_t j = 0; j < transition.n_rows; j++) - { - // The forward probability of state j at time t is the sum over all states - // of the probability of the previous state transitioning to the current - // state and emitting the given observation. - forwardProb(j, t) = accu(forwardProb.col(t - 1) % - trans(transition.row(j))) * - emission[j].Probability(dataSeq.unsafe_col(t)); - } - - // Normalize probability. - scales[t] = accu(forwardProb.col(t)); - if (scales[t] > 0.0) - forwardProb.col(t) /= scales[t]; - } -} - -template -void HMM::Backward(const arma::mat& dataSeq, - const arma::vec& scales, - arma::mat& backwardProb) const -{ - // Our goal is to calculate the backward probabilities: - // P(X_k | o_{k + 1:T}) for all possible states X_k, for each time point k. - backwardProb.zeros(transition.n_rows, dataSeq.n_cols); - - // The last element probability is 1. - backwardProb.col(dataSeq.n_cols - 1).fill(1); - - // Now step backwards through all other observations. - for (size_t t = dataSeq.n_cols - 2; t + 1 > 0; t--) - { - for (size_t j = 0; j < transition.n_rows; j++) - { - // The backward probability of state j at time t is the sum over all state - // of the probability of the next state having been a transition from the - // current state multiplied by the probability of each of those states - // emitting the given observation. - for (size_t state = 0; state < transition.n_rows; state++) - backwardProb(j, t) += transition(state, j) * backwardProb(state, t + 1) - * emission[state].Probability(dataSeq.unsafe_col(t + 1)); - - // Normalize by the weights from the forward algorithm. - if (scales[t + 1] > 0.0) - backwardProb(j, t) /= scales[t + 1]; - } - } -} - -//! Serialize the HMM. -template -template -void HMM::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(dimensionality); - ar & BOOST_SERIALIZATION_NVP(tolerance); - ar & BOOST_SERIALIZATION_NVP(transition); - ar & BOOST_SERIALIZATION_NVP(initial); - - // Now serialize each emission. If we are loading, we must resize the vector - // of emissions correctly. - if (Archive::is_loading::value) - emission.resize(transition.n_rows); - - // Load the emissions; generate the correct name for each one. - ar & BOOST_SERIALIZATION_NVP(emission); -} - -} // namespace hmm -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_model.hpp b/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_model.hpp deleted file mode 100644 index 698bbf0bd..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_model.hpp +++ /dev/null @@ -1,205 +0,0 @@ -/** - * @file hmm_model.hpp - * @author Ryan Curtin - * - * A serializable HMM model that also stores the type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HMM_HMM_MODEL_HPP -#define MLPACK_METHODS_HMM_HMM_MODEL_HPP - -#include "hmm.hpp" -#include - -namespace mlpack { -namespace hmm { - -enum HMMType : char -{ - DiscreteHMM = 0, - GaussianHMM, - GaussianMixtureModelHMM -}; - -/** - * A serializable HMM model that also stores the type. - */ -class HMMModel -{ - private: - //! The type of the HMM. - HMMType type; - //! Not used if type is not DiscreteHMM. - HMM* discreteHMM; - //! Not used if type is not GaussianHMM. - HMM* gaussianHMM; - //! Not used if type is not GaussianMixtureModelHMM. - HMM* gmmHMM; - - public: - //! Construct an uninitialized model. - HMMModel() : - type(HMMType::DiscreteHMM), - discreteHMM(new HMM()), - gaussianHMM(NULL), - gmmHMM(NULL) - { - // Nothing to do. - } - - //! Construct a model of the given type. - HMMModel(const HMMType type) : - type(type), - discreteHMM(NULL), - gaussianHMM(NULL), - gmmHMM(NULL) - { - if (type == HMMType::DiscreteHMM) - discreteHMM = new HMM(); - else if (type == HMMType::GaussianHMM) - gaussianHMM = new HMM(); - else if (type == HMMType::GaussianMixtureModelHMM) - gmmHMM = new HMM(); - } - - //! Copy another model. - HMMModel(const HMMModel& other) : - type(other.type), - discreteHMM(NULL), - gaussianHMM(NULL), - gmmHMM(NULL) - { - if (type == HMMType::DiscreteHMM) - discreteHMM = - new HMM(*other.discreteHMM); - else if (type == HMMType::GaussianHMM) - gaussianHMM = - new HMM(*other.gaussianHMM); - else if (type == HMMType::GaussianMixtureModelHMM) - gmmHMM = new HMM(*other.gmmHMM); - } - - //! Take ownership of another model. - HMMModel(HMMModel&& other) : - type(other.type), - discreteHMM(other.discreteHMM), - gaussianHMM(other.gaussianHMM), - gmmHMM(other.gmmHMM) - { - other.type = HMMType::DiscreteHMM; - other.discreteHMM = new HMM(); - other.gaussianHMM = NULL; - other.gmmHMM = NULL; - } - - //! Copy assignment operator. - HMMModel& operator=(const HMMModel& other) - { - if (this == &other) - return *this; - - delete discreteHMM; - delete gaussianHMM; - delete gmmHMM; - - discreteHMM = NULL; - gaussianHMM = NULL; - gmmHMM = NULL; - - type = other.type; - if (type == HMMType::DiscreteHMM) - discreteHMM = - new HMM(*other.discreteHMM); - else if (type == HMMType::GaussianHMM) - gaussianHMM = - new HMM(*other.gaussianHMM); - else if (type == HMMType::GaussianMixtureModelHMM) - gmmHMM = new HMM(*other.gmmHMM); - - return *this; - } - - //! Clean memory. - ~HMMModel() - { - delete discreteHMM; - delete gaussianHMM; - delete gmmHMM; - } - - /** - * Given a functor type, perform that functor with the optional extra info on - * the HMM. - */ - template - void PerformAction(ExtraInfoType* x) - { - if (type == HMMType::DiscreteHMM) - ActionType::Apply(*discreteHMM, x); - else if (type == HMMType::GaussianHMM) - ActionType::Apply(*gaussianHMM, x); - else if (type == HMMType::GaussianMixtureModelHMM) - ActionType::Apply(*gmmHMM, x); - } - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(type); - - // If necessary, clean memory. - if (Archive::is_loading::value) - { - delete discreteHMM; - delete gaussianHMM; - delete gmmHMM; - - discreteHMM = NULL; - gaussianHMM = NULL; - gmmHMM = NULL; - } - - if (type == HMMType::DiscreteHMM) - ar & BOOST_SERIALIZATION_NVP(discreteHMM); - else if (type == HMMType::GaussianHMM) - ar & BOOST_SERIALIZATION_NVP(gaussianHMM); - else if (type == HMMType::GaussianMixtureModelHMM) - ar & BOOST_SERIALIZATION_NVP(gmmHMM); - } - - // Accessor method for type of HMM - HMMType Type() { return type; } - - /** - * Accessor methods for discreteHMM, gaussianHMM and gmmHMM. - * Note that an instatiation of this class will only contain one type of HMM - * (as indicated by the "type" instance variable) - the other two pointers - * will be NULL. - * - * For instance, if the HMMModel object holds a discrete HMM, then: - * type --> DiscreteHMM - * gaussianHMM --> NULL - * gmmHMM --> NULL - * discreteHMM --> HMM object - * and hence, calls to GMMHMM() and GaussianHMM() will return NULL. Only the - * call to DiscreteHMM() will return a non NULL pointer. - * - * Hence, in practice, a user should be careful to first check the type of HMM - * (by calling the Type() accessor) and then perform subsequent actions, to - * avoid null pointer dereferences. - */ - HMM* DiscreteHMM() { return discreteHMM; } - HMM* GaussianHMM() { return gaussianHMM; } - HMM* GMMHMM() { return gmmHMM; } -}; - -} // namespace hmm -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_regression.hpp b/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_regression.hpp deleted file mode 100644 index a6fa7af13..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_regression.hpp +++ /dev/null @@ -1,338 +0,0 @@ -/** - * @file hmm_regression.hpp - * @author Michael Fox - * - * Definition of HMMRegression class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HMM_HMM_REGRESSION_HPP -#define MLPACK_METHODS_HMM_HMM_REGRESSION_HPP - -#include -#include -#include "hmm.hpp" - -namespace mlpack { -namespace hmm /** Hidden Markov Models. */ { - -/** - * A class that represents a Hidden Markov Model Regression (HMMR). HMMR is an - * extension of Hidden Markov Models to regression analysis. The method is - * described in (Fridman, 1993) - * https://www.ima.umn.edu/preprints/January1994/1195.pdf - * An HMMR is a linear regression model whose coefficients are determined by a - * finite-state Markov chain. The error terms are conditionally independently - * normally distributed with zero mean and state-dependent variance. Let Q_t be - * a finite-state Markov chain, X_t a vector of predictors and Y_t a response. - * The HMMR is - * Y_t = X_t \beta_{Q_t} + \sigma_{Q_t} \epsilon_t - * - * This HMMR class supports training (supervised and unsupervised), prediction - * of state sequences via the Viterbi algorithm, estimation of state - * probabilities, filtering and smoothing of responses, and calculation of the - * log-likelihood of a given sequence. - * - * Usage of the HMMR class generally involves either training an HMMR or loading - * an already-known HMMR and using to filter a sequence. - * Example code for supervised training of an HMMR is given below. - * - * @code - * // Each column is a vector of predictors for a single observation. - * arma::mat predictors(5, 100, arma::fill::randn); - * // Responses for each observation - * arma::vec responses(100, arma::fill::randn); - * - * // Create an untrained HMMR with 3 hidden states - * RegressionDistribution rd(predictors, responses); - * arma::mat transition("0.5 0.5;" "0.5 0.5;"); - * std::vector emissions(2,rd); - * HMMRegression hmmr("0.9 0.1", transition, emissions); - * - * // Train the HMM (supply a state sequence to perform supervised training) - * std::vector predictorsSeq(1, predictors); - * std::vector< arma::vec> responsesSeq(1, responses); - * hmmr.Train(predictorsSeq, responsesSeq); - * hmm.Train(observations, states); - * @endcode - * - * Once initialized, the HMMR can evaluate the probability of a certain sequence - * (with LogLikelihood()), predict the most likely sequence of hidden states - * (with Predict()), estimate the probabilities of each state for a sequence of - * observations (with Estimate()), or perform filtering or smoothing of - * observations. - * - */ -class HMMRegression : public HMM -{ - public: - /** - * Create the Hidden Markov Model Regression with the given number of hidden - * states and the given default regression emission. The dimensionality of the - * observations is taken from the emissions variable, so it is important that - * the given default emission distribution is set with the correct - * dimensionality. Alternately, set the dimensionality with Dimensionality(). - * Optionally, the tolerance for convergence of the Baum-Welch algorithm can - * be set. - * - * By default, the transition matrix and initial probability vector are set to - * contain equal probability for each state. - * - * @param states Number of states. - * @param emissions Default distribution for emissions. - * @param tolerance Tolerance for convergence of training algorithm - * (Baum-Welch). - */ - HMMRegression(const size_t states, - const distribution::RegressionDistribution emissions, - const double tolerance = 1e-5) : - HMM(states, emissions, tolerance) - { /* nothing to do */ } - - /** - * Create the Hidden Markov Model Regression with the given initial - * probability vector, the given transition matrix, and the given regression - * emission distributions. The dimensionality of the observations of the HMMR - * are taken from the given emission distributions. Alternately, the - * dimensionality can be set with Dimensionality(). - * - * The initial state probability vector should have length equal to the number - * of states, and each entry represents the probability of being in the given - * state at time T = 0 (the beginning of a sequence). - * - * The transition matrix should be such that T(i, j) is the probability of - * transition to state i from state j. The columns of the matrix should sum - * to 1. - * - * Optionally, the tolerance for convergence of the Baum-Welch algorithm can - * be set. - * - * @param initial Initial state probabilities. - * @param transition Transition matrix. - * @param emission Emission distributions. - * @param tolerance Tolerance for convergence of training algorithm - * (Baum-Welch). - */ - HMMRegression(const arma::vec& initial, - const arma::mat& transition, - const std::vector& emission, - const double tolerance = 1e-5) : - HMM(initial, transition, emission, - tolerance) - { /* nothing to do */ } - - - - /** - * Train the model using the Baum-Welch algorithm, with only the given - * predictors and responses. Instead of giving a guess transition and emission - * here, do that in the constructor. Each matrix in the vector of predictors - * corresponds to an individual data sequence, and likewise for each vec in - * the vector of responses. The number of rows in each matrix of predictors - * plus one should be equal to the dimensionality of the HMM (which is set in - * the constructor). - * - * It is preferable to use the other overload of Train(), with labeled data. - * That will produce much better results. However, if labeled data is - * unavailable, this will work. In addition, it is possible to use Train() - * with labeled data first, and then continue to train the model using this - * overload of Train() with unlabeled data. - * - * The tolerance of the Baum-Welch algorithm can be set either in the - * constructor or with the Tolerance() method. When the change in - * log-likelihood of the model between iterations is less than the tolerance, - * the Baum-Welch algorithm terminates. - * - * @note - * Train() can be called multiple times with different sequences; each time it - * is called, it uses the current parameters of the HMM as a starting point - * for training. - * @endnote - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - */ - void Train(const std::vector& predictors, - const std::vector& responses); - - /** - * Train the model using the given labeled observations; the transition and - * regression emissions are directly estimated. Each matrix in the vector of - * predictors corresponds to an individual data sequence, and likewise for - * each vec in the vector of responses. The number of rows in each matrix of - * predictors plus one should be equal to the dimensionality of the HMM - * (which is set in the constructor). - * - * @note - * Train() can be called multiple times with different sequences; each time it - * is called, it uses the current parameters of the HMMR as a starting point - * for training. - * @endnote - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - * @param stateSeq Vector of state sequences, corresponding to each - * observation. - */ - void Train(const std::vector& predictors, - const std::vector& responses, - const std::vector >& stateSeq); - - /** - * Estimate the probabilities of each hidden state at each time step for each - * given data observation, using the Forward-Backward algorithm. Each matrix - * which is returned has columns equal to the number of data observations, and - * rows equal to the number of hidden states in the model. The log-likelihood - * of the most probable sequence is returned. - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - * @param stateProb Matrix in which the probabilities of each state at each - * time interval will be stored. - * @param forwardProb Matrix in which the forward probabilities of each state - * at each time interval will be stored. - * @param backwardProb Matrix in which the backward probabilities of each - * state at each time interval will be stored. - * @param scales Vector in which the scaling factors at each time interval - * will be stored. - * @return Log-likelihood of most likely state sequence. - */ - double Estimate(const arma::mat& predictors, - const arma::vec& responses, - arma::mat& stateProb, - arma::mat& forwardProb, - arma::mat& backwardProb, - arma::vec& scales) const; - - /** - * Estimate the probabilities of each hidden state at each time step of each - * given data observation, using the Forward-Backward algorithm. The returned - * matrix of state probabilities has columns equal to the number of data - * observations, and rows equal to the number of hidden states in the model. - * The log-likelihood of the most probable sequence is returned. - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - * @param stateProb Probabilities of each state at each time interval. - * @return Log-likelihood of most likely state sequence. - */ - double Estimate(const arma::mat& predictors, - const arma::vec& responses, - arma::mat& stateProb) const; - - /** - * Compute the most probable hidden state sequence for the given predictors - * and responses, using the Viterbi algorithm, returning the log-likelihood of - * the most likely state sequence. - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - * @param stateSeq Vector in which the most probable state sequence will be - * stored. - * @return Log-likelihood of most probable state sequence. - */ - double Predict(const arma::mat& predictors, - const arma::vec& responses, - arma::Row& stateSeq) const; - - /** - * Compute the log-likelihood of the given predictors and responses. - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - * @return Log-likelihood of the given sequence. - */ - double LogLikelihood(const arma::mat& predictors, - const arma::vec& responses) const; - /** - * HMMR filtering. Computes the k-step-ahead expected response at each time - * conditioned only on prior observations. That is - * E{ Y[t+k] | Y[0], ..., Y[t] }. - * The returned matrix has columns equal to the number of observations. Note - * that the expectation may not be meaningful for discrete emissions. - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - * @param initial Distribution of initial state. - * @param ahead Number of steps ahead (k) for expectations. - * @param filterSeq Vector in which the expected emission sequence will be - * stored. - */ - void Filter(const arma::mat& predictors, - const arma::vec& responses, - arma::vec& filterSeq, - size_t ahead = 0) const; - - /** - * HMM smoothing. Computes expected emission at each time conditioned on all - * observations. That is - * E{ Y[t] | Y[0], ..., Y[T] }. - * The returned matrix has columns equal to the number of observations. Note - * that the expectation may not be meaningful for discrete emissions. - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences.. - * @param initial Distribution of initial state. - * @param smoothSeq Vector in which the expected emission sequence will be - * stored. - */ - void Smooth(const arma::mat& predictors, - const arma::vec& responses, - arma::vec& smoothSeq) const; - - private: - /** - * Utility functions to facilitate the use of the HMM class for HMMR. - */ - void StackData(const std::vector& predictors, - const std::vector& responses, - std::vector& dataSeq) const; - - void StackData(const arma::mat& predictors, - const arma::vec& responses, - arma::mat& dataSeq) const; - - /** - * The Forward algorithm (part of the Forward-Backward algorithm). Computes - * forward probabilities for each state for each observation in the given data - * sequence. The returned matrix has rows equal to the number of hidden - * states and columns equal to the number of observations. - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - * @param scales Vector in which scaling factors will be saved. - * @param forwardProb Matrix in which forward probabilities will be saved. - */ - void Forward(const arma::mat& predictors, - const arma::vec& responses, - arma::vec& scales, - arma::mat& forwardProb) const; - - /** - * The Backward algorithm (part of the Forward-Backward algorithm). Computes - * backward probabilities for each state for each observation in the given - * data sequence, using the scaling factors found (presumably) by Forward(). - * The returned matrix has rows equal to the number of hidden states and - * columns equal to the number of observations. - * - * @param predictors Vector of predictor sequences. - * @param responses Vector of response sequences. - * @param scales Vector of scaling factors. - * @param backwardProb Matrix in which backward probabilities will be saved. - */ - void Backward(const arma::mat& predictors, - const arma::vec& responses, - const arma::vec& scales, - arma::mat& backwardProb) const; -}; - -} // namespace hmm -} // namespace mlpack - -// Include implementation. -#include "hmm_regression_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_regression_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_regression_impl.hpp deleted file mode 100644 index 7d3e82ba6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_regression_impl.hpp +++ /dev/null @@ -1,196 +0,0 @@ -/** - * @file hmm_regression_impl.hpp - * @author Ryan Curtin - * @author Tran Quoc Long - * @author Michael Fox - * - * Implementation of HMMRegression class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HMM_HMM_REGRESSION_IMPL_HPP -#define MLPACK_METHODS_HMM_HMM_REGRESSION_IMPL_HPP - -// Just in case... -#include "hmm_regression.hpp" - -namespace mlpack { -namespace hmm { - -void HMMRegression::Train(const std::vector& predictors, - const std::vector& responses) -{ - std::vector dataSeq; - StackData(predictors, responses, dataSeq); - this->HMM::Train(dataSeq); -} - -void HMMRegression::Train(const std::vector& predictors, - const std::vector& responses, - const std::vector >& stateSeq) -{ - std::vector dataSeq; - StackData(predictors, responses, dataSeq); - this->HMM::Train(dataSeq, stateSeq); -} - -/** - * Estimate the probabilities of each hidden state at each time step for each - * given data observation. - */ -double HMMRegression::Estimate(const arma::mat& predictors, - const arma::vec& responses, - arma::mat& stateProb, - arma::mat& forwardProb, - arma::mat& backwardProb, - arma::vec& scales) const -{ - arma::mat dataSeq; - StackData(predictors, responses, dataSeq); - return this->HMM::Estimate(dataSeq, stateProb, forwardProb, - backwardProb, scales); -} - -/** - * Estimate the probabilities of each hidden state at each time step for each - * given data observation. - */ -double HMMRegression::Estimate(const arma::mat& predictors, - const arma::vec& responses, - arma::mat& stateProb) const -{ - arma::mat dataSeq; - StackData(predictors, responses, dataSeq); - return this->HMM::Estimate(dataSeq, stateProb); -} - -/** - * Compute the most probable hidden state sequence for the given observation - * using the Viterbi algorithm. Returns the log-likelihood of the most likely - * sequence. - */ -double HMMRegression::Predict(const arma::mat& predictors, - const arma::vec& responses, - arma::Row& stateSeq) const -{ - arma::mat dataSeq; - StackData(predictors, responses, dataSeq); - return this->HMM::Predict(dataSeq, stateSeq); -} - -/** - * Compute the log-likelihood of the given data sequence. - */ -double HMMRegression::LogLikelihood(const arma::mat& predictors, - const arma::vec& responses) const -{ - arma::mat dataSeq; - StackData(predictors, responses, dataSeq); - return this->HMM::LogLikelihood(dataSeq); -} - -/** - * HMMRegression filtering. - */ -void HMMRegression::Filter(const arma::mat& predictors, - const arma::vec& responses, - arma::vec& filterSeq, - size_t ahead) const -{ - // First run the forward algorithm - arma::mat forwardProb; - arma::vec scales; - Forward(predictors, responses, scales, forwardProb); - - // Propagate state, predictors ahead - if (ahead != 0) - { - forwardProb = pow(transition, ahead)*forwardProb; - forwardProb = forwardProb.cols(0, forwardProb.n_cols-ahead-1); - } - - // Compute expected emissions. - filterSeq.resize(responses.n_elem - ahead); - filterSeq.zeros(); - arma::vec nextSeq; - for (size_t i = 0; i < emission.size(); i++) - { - emission[i].Predict(predictors.cols(ahead, predictors.n_cols-1), nextSeq); - filterSeq = filterSeq + nextSeq%(forwardProb.row(i).t()); - } -} - -/** - * HMM smoothing. - */ -void HMMRegression::Smooth(const arma::mat& predictors, - const arma::vec& responses, - arma::vec& smoothSeq) const -{ - // First run the forward algorithm - arma::mat stateProb; - Estimate(predictors, responses, stateProb); - - // Compute expected emissions. - smoothSeq.resize(responses.n_elem); - smoothSeq.zeros(); - arma::vec nextSeq; - for (size_t i = 0; i < emission.size(); i++) - { - emission[i].Predict(predictors, nextSeq); - smoothSeq = smoothSeq + nextSeq%(stateProb.row(i).t()); - } -} - -/** - * The Forward procedure (part of the Forward-Backward algorithm). - */ -void HMMRegression::Forward(const arma::mat& predictors, - const arma::vec& responses, - arma::vec& scales, - arma::mat& forwardProb) const -{ - arma::mat dataSeq; - StackData(predictors, responses, dataSeq); - this->HMM::Forward(dataSeq, scales, forwardProb); -} - - -void HMMRegression::Backward(const arma::mat& predictors, - const arma::vec& responses, - const arma::vec& scales, - arma::mat& backwardProb) const -{ - arma::mat dataSeq; - StackData(predictors, responses, dataSeq); - this->HMM::Backward(dataSeq, scales, backwardProb); -} - -void HMMRegression::StackData(const std::vector& predictors, - const std::vector& responses, - std::vector& dataSeq) const -{ - arma::mat nextSeq; - for (size_t i = 0; i < predictors.size(); i++) - { - nextSeq = predictors[i]; - nextSeq.insert_rows(0, responses[i].t()); - dataSeq.push_back(nextSeq); - } -} - -void HMMRegression::StackData(const arma::mat& predictors, - const arma::vec& responses, - arma::mat& dataSeq) const -{ - dataSeq = predictors; - dataSeq.insert_rows(0, responses.t()); -} - -} // namespace hmm -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_util.hpp b/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_util.hpp deleted file mode 100644 index 5b56d1671..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_util.hpp +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @file hmm_util.hpp - * @author Ryan Curtin - * - * Utility to read HMM type from file. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HMM_HMM_UTIL_HPP -#define MLPACK_METHODS_HMM_HMM_UTIL_HPP - -#include - -namespace mlpack { -namespace hmm { - -//! HMMType, to be stored on disk. This is of type char, which is one byte. -//! (I'm not sure what will happen on systems where one byte is not eight bits.) -enum HMMType : char -{ - DiscreteHMM = 0, - GaussianHMM, - GaussianMixtureModelHMM -}; - -//! ActionType should implement static void Apply(HMMType&). -template -void LoadHMMAndPerformAction(const std::string& modelFile, - ExtraInfoType* x = NULL); - -//! Save an HMM to a file. The file must also encode what type of HMM is being -//! stored. -template -void SaveHMM(HMMType& hmm, const std::string& modelFile); - -} // namespace hmm -} // namespace mlpack - -#include "hmm_util_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_util_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_util_impl.hpp deleted file mode 100644 index 4b19b2cac..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hmm/hmm_util_impl.hpp +++ /dev/null @@ -1,175 +0,0 @@ -/** - * @file hmm_util_impl.hpp - * @author Ryan Curtin - * - * Implementation of HMM utilities to load arbitrary HMM types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HMM_HMM_UTIL_IMPL_HPP -#define MLPACK_METHODS_HMM_HMM_UTIL_IMPL_HPP - -#include - -#include -#include - -namespace mlpack { -namespace hmm { - -// Forward declarations of utility functions. - -// Set up the archive for deserialization. -template -void LoadHMMAndPerformActionHelper(const std::string& modelFile, - ExtraInfoType* x = NULL); - -// Actually deserialize into the correct type. -template -void DeserializeHMMAndPerformAction(ArchiveType& ar, ExtraInfoType* x = NULL); - -template -void LoadHMMAndPerformAction(const std::string& modelFile, - ExtraInfoType* x) -{ - using namespace boost::archive; - - const std::string extension = data::Extension(modelFile); - if (extension == "xml") - LoadHMMAndPerformActionHelper(modelFile, x); - else if (extension == "bin") - LoadHMMAndPerformActionHelper(modelFile, x); - else if (extension == "txt") - LoadHMMAndPerformActionHelper(modelFile, x); - else - Log::Fatal << "Unknown extension '" << extension << "' for HMM model file " - << "(known: 'xml', 'txt', 'bin')." << std::endl; -} - -template -void LoadHMMAndPerformActionHelper(const std::string& modelFile, - ExtraInfoType* x) -{ - std::ifstream ifs(modelFile); - if (ifs.fail()) - Log::Fatal << "Cannot open model file '" << modelFile << "' for loading!" - << std::endl; - ArchiveType ar(ifs); - - // Read in the unsigned integer that denotes the type of the model. - char type; - ar >> BOOST_SERIALIZATION_NVP(type); - - using namespace mlpack::distribution; - - switch (type) - { - case HMMType::DiscreteHMM: - DeserializeHMMAndPerformAction>(ar, x); - break; - - case HMMType::GaussianHMM: - DeserializeHMMAndPerformAction>(ar, x); - break; - - case HMMType::GaussianMixtureModelHMM: - DeserializeHMMAndPerformAction>(ar, x); - break; - - default: - Log::Fatal << "Unknown HMM type '" << (unsigned int) type << "'!" - << std::endl; - } -} - -template -void DeserializeHMMAndPerformAction(ArchiveType& ar, ExtraInfoType* x) -{ - // Extract the HMM and perform the action. - HMMType hmm; - ar >> BOOST_SERIALIZATION_NVP(hmm); - ActionType::Apply(hmm, x); -} - -// Helper function. -template -void SaveHMMHelper(HMMType& hmm, const std::string& modelFile); - -template -char GetHMMType(); - -template -void SaveHMM(HMMType& hmm, const std::string& modelFile) -{ - using namespace boost::archive; - - const std::string extension = data::Extension(modelFile); - if (extension == "xml") - SaveHMMHelper(hmm, modelFile); - else if (extension == "bin") - SaveHMMHelper(hmm, modelFile); - else if (extension == "txt") - SaveHMMHelper(hmm, modelFile); - else - Log::Fatal << "Unknown extension '" << extension << "' for HMM model file." - << std::endl; -} - -template -void SaveHMMHelper(HMMType& hmm, const std::string& modelFile) -{ - std::ofstream ofs(modelFile); - if (ofs.fail()) - Log::Fatal << "Cannot open model file '" << modelFile << "' for saving!" - << std::endl; - ArchiveType ar(ofs); - - // Write out the unsigned integer that denotes the type of the model. - char type = GetHMMType(); - if (type == char(-1)) - Log::Fatal << "Unknown HMM type given to SaveHMM()!" << std::endl; - - ar << BOOST_SERIALIZATION_NVP(type); - ar << BOOST_SERIALIZATION_NVP(hmm); -} - -// Utility functions to turn a type into something we can store. -template -char GetHMMType() { return char(-1); } - -template<> -char GetHMMType>() -{ - return HMMType::DiscreteHMM; -} - -template<> -char GetHMMType>() -{ - return HMMType::GaussianHMM; -} - -template<> -char GetHMMType>() -{ - return HMMType::GaussianMixtureModelHMM; -} - -} // namespace hmm -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split.hpp deleted file mode 100644 index 8b18de8db..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split.hpp +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @file binary_numeric_split.hpp - * @author Ryan Curtin - * - * An implementation of the binary-tree-based numeric splitting procedure - * described by Gama, Rocha, and Medas in their KDD 2003 paper. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_SPLIT_BINARY_NUMERIC_SPLIT_HPP -#define MLPACK_METHODS_HOEFFDING_SPLIT_BINARY_NUMERIC_SPLIT_HPP - -#include "binary_numeric_split_info.hpp" - -namespace mlpack { -namespace tree { - -/** - * The BinaryNumericSplit class implements the numeric feature splitting - * strategy devised by Gama, Rocha, and Medas in the following paper: - * - * @code - * @inproceedings{gama2003accurate, - * title={Accurate Decision Trees for Mining High-Speed Data Streams}, - * author={Gama, J. and Rocha, R. and Medas, P.}, - * year={2003}, - * booktitle={Proceedings of the Ninth ACM SIGKDD International Conference on - * Knowledge Discovery and Data Mining (KDD '03)}, - * pages={523--528} - * } - * @endcode - * - * This splitting procedure builds a binary tree on points it has seen so far, - * and then EvaluateFitnessFunction() returns the best possible split in O(n) - * time, where n is the number of samples seen so far. Every split with this - * split type returns only two splits (greater than or equal to the split point, - * and less than the split point). The Train() function should take O(1) time. - * - * @tparam FitnessFunction Fitness function to use for calculating gain. - * @tparam ObservationType Type of observation used by this dimension. - */ -template -class BinaryNumericSplit -{ - public: - //! The splitting information required by the BinaryNumericSplit. - typedef BinaryNumericSplitInfo SplitInfo; - - /** - * Create the BinaryNumericSplit object with the given number of classes. - * - * @param numClasses Number of classes in dataset. - */ - BinaryNumericSplit(const size_t numClasses = 0); - - /** - * Create the BinaryNumericSplit object with the given number of classes, - * using information from the given other split for other parameters. In this - * case, there are no other parameters, but this function is required by the - * HoeffdingTree class. - */ - BinaryNumericSplit(const size_t numClasses, const BinaryNumericSplit& other); - - /** - * Train on the given value with the given label. - * - * @param value The value to train on. - * @param label The label to train on. - */ - void Train(ObservationType value, const size_t label); - - /** - * Given the points seen so far, evaluate the fitness function, returning the - * best possible gain of a binary split. Note that this takes O(n) time, - * where n is the number of points seen so far. So this may not exactly be - * fast... - * - * The best possible split will be stored in bestFitness, and the second best - * possible split will be stored in secondBestFitness. - * - * @param bestFitness Fitness function value for best possible split. - * @param secondBestFitness Fitness function value for second best possible - * split. - */ - void EvaluateFitnessFunction(double& bestFitness, - double& secondBestFitness); - - // Return the number of children if this node were to split on this feature. - size_t NumChildren() const { return 2; } - - /** - * Given that a split should happen, return the majority classes of the (two) - * children and an initialized SplitInfo object. - * - * @param childMajorities Majority classes of the children after the split. - * @param splitInfo Split information. - */ - void Split(arma::Col& childMajorities, SplitInfo& splitInfo); - - //! The majority class of the points seen so far. - size_t MajorityClass() const; - //! The probability of the majority class given the points seen so far. - double MajorityProbability() const; - - //! Serialize the object. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! The elements seen so far, in sorted order. - std::multimap sortedElements; - //! The classes we have seen so far (for majority calculations). - arma::Col classCounts; - - //! A cached best split point. - ObservationType bestSplit; - //! If true, the cached best split point is accurate (that is, we have not - //! seen any more samples since we calculated it). - bool isAccurate; -}; - -// Convenience typedef. -template -using BinaryDoubleNumericSplit = BinaryNumericSplit; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "binary_numeric_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split_impl.hpp deleted file mode 100644 index 5586c8b3f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split_impl.hpp +++ /dev/null @@ -1,186 +0,0 @@ -/** - * @file binary_numeric_split_impl.hpp - * @author Ryan Curtin - * - * Implementation of the BinaryNumericSplit class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_BINARY_NUMERIC_SPLIT_IMPL_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_BINARY_NUMERIC_SPLIT_IMPL_HPP - -// In case it hasn't been included yet. -#include "binary_numeric_split.hpp" - -namespace mlpack { -namespace tree { - -template -BinaryNumericSplit::BinaryNumericSplit( - const size_t numClasses) : - classCounts(numClasses), - bestSplit(std::numeric_limits::min()), - isAccurate(true) -{ - // Zero out class counts. - classCounts.zeros(); -} - -template -BinaryNumericSplit::BinaryNumericSplit( - const size_t numClasses, - const BinaryNumericSplit& /* other */) : - classCounts(numClasses), - bestSplit(std::numeric_limits::min()), - isAccurate(true) -{ - // Zero out class counts. - classCounts.zeros(); -} - -template -void BinaryNumericSplit::Train( - ObservationType value, - const size_t label) -{ - // Push it into the multimap, and update the class counts. - sortedElements.insert(std::pair(value, label)); - ++classCounts[label]; - - // Whatever we have cached is no longer valid. - isAccurate = false; -} - -template -void BinaryNumericSplit:: - EvaluateFitnessFunction(double& bestFitness, - double& secondBestFitness) -{ - // Unfortunately, we have to iterate over the map. - bestSplit = std::numeric_limits::min(); - - // Initialize the sufficient statistics. - arma::Mat counts(classCounts.n_elem, 2); - counts.col(0).zeros(); - counts.col(1) = classCounts; - - bestFitness = FitnessFunction::Evaluate(counts); - secondBestFitness = 0.0; - - // Initialize to the first observation, so we don't calculate gain on the - // first iteration (it will be 0). - ObservationType lastObservation = (*sortedElements.begin()).first; - size_t lastClass = classCounts.n_elem; - for (typename std::multimap::const_iterator it = - sortedElements.begin(); it != sortedElements.end(); ++it) - { - // If this value is the same as the last, or if this is the first value, or - // we have the same class as the previous observation, don't calculate the - // gain---it can't be any better. (See Fayyad and Irani, 1991.) - if (((*it).first != lastObservation) || ((*it).second != lastClass)) - { - lastObservation = (*it).first; - lastClass = (*it).second; - - const double value = FitnessFunction::Evaluate(counts); - if (value > bestFitness) - { - bestFitness = value; - bestSplit = (*it).first; - } - else if (value > secondBestFitness) - { - secondBestFitness = value; - } - } - - // Move the point to the right side of the split. - --counts((*it).second, 1); - ++counts((*it).second, 0); - } - - isAccurate = true; -} - -template -void BinaryNumericSplit::Split( - arma::Col& childMajorities, - SplitInfo& splitInfo) -{ - if (!isAccurate) - { - double bestGain, secondBestGain; - EvaluateFitnessFunction(bestGain, secondBestGain); - } - - // Make one child for each side of the split. - childMajorities.set_size(2); - - arma::Mat counts(classCounts.n_elem, 2); - counts.col(0).zeros(); - counts.col(1) = classCounts; - - double min = DBL_MAX; - double max = -DBL_MAX; - for (typename std::multimap::const_iterator it = - sortedElements.begin(); // (*it).first < bestSplit; ++it) - it != sortedElements.end(); ++it) - { - // Move the point to the correct side of the split. - if ((*it).first < bestSplit) - { - --counts((*it).second, 1); - ++counts((*it).second, 0); - } - if ((*it).first < min) - min = (*it).first; - if ((*it).first > max) - max = (*it).first; - } - - // Calculate the majority classes of the children. - arma::uword maxIndex; - counts.unsafe_col(0).max(maxIndex); - childMajorities[0] = size_t(maxIndex); - counts.unsafe_col(1).max(maxIndex); - childMajorities[1] = size_t(maxIndex); - - // Create the according SplitInfo object. - splitInfo = SplitInfo(bestSplit); -} - -template -size_t BinaryNumericSplit::MajorityClass() - const -{ - arma::uword maxIndex; - classCounts.max(maxIndex); - return size_t(maxIndex); -} - -template -double BinaryNumericSplit:: - MajorityProbability() const -{ - return double(arma::max(classCounts)) / double(arma::accu(classCounts)); -} - -template -template -void BinaryNumericSplit::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // Serialize. - ar & BOOST_SERIALIZATION_NVP(sortedElements); - ar & BOOST_SERIALIZATION_NVP(classCounts); -} - - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split_info.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split_info.hpp deleted file mode 100644 index d0f20cde0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/binary_numeric_split_info.hpp +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @file binary_numeric_split_info.hpp - * @author Ryan Curtin - * - * After a binary numeric split has been made, this holds information on the - * split (just the split point). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_BINARY_NUMERIC_SPLIT_INFO_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_BINARY_NUMERIC_SPLIT_INFO_HPP - -#include - -namespace mlpack { -namespace tree { - -template -class BinaryNumericSplitInfo -{ - public: - BinaryNumericSplitInfo() { /* Nothing to do. */ } - BinaryNumericSplitInfo(const ObservationType& splitPoint) : - splitPoint(splitPoint) { /* Nothing to do. */ } - - template - size_t CalculateDirection(const eT& value) const - { - return (value < splitPoint) ? 0 : 1; - } - - //! Serialize the split (save/load the split points). - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(splitPoint); - } - - private: - ObservationType splitPoint; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/categorical_split_info.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/categorical_split_info.hpp deleted file mode 100644 index 7c7a1da35..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/categorical_split_info.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file categorical_split_info.hpp - * @author Ryan Curtin - * - * After a categorical split has been made, this holds information on the split. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_CATEGORICAL_SPLIT_INFO_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_CATEGORICAL_SPLIT_INFO_HPP - -#include - -namespace mlpack { -namespace tree { - -class CategoricalSplitInfo -{ - public: - CategoricalSplitInfo(const size_t /* categories */) { } - - template - static size_t CalculateDirection(const eT& value) - { - // We have a child for each categorical value, and value should be in the - // range [0, categories). - return size_t(value); - } - - //! Serialize the object. (Nothing needs to be saved.) - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/gini_impurity.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/gini_impurity.hpp deleted file mode 100644 index 8952bb74a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/gini_impurity.hpp +++ /dev/null @@ -1,89 +0,0 @@ -/** - * @file gini_impurity.hpp - * @author Ryan Curtin - * - * The GiniImpurity class, which is a fitness function (FitnessFunction) for - * streaming decision trees. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_GINI_INDEX_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_GINI_INDEX_HPP - -#include - -namespace mlpack { -namespace tree { - -class GiniImpurity -{ - public: - static double Evaluate(const arma::Mat& counts) - { - // We need to sum over the difference between the un-split node and the - // split nodes. First we'll calculate the number of elements in each split - // and total. - size_t numElem = 0; - arma::vec splitCounts(counts.n_cols); - for (size_t i = 0; i < counts.n_cols; ++i) - { - splitCounts[i] = arma::accu(counts.col(i)); - numElem += splitCounts[i]; - } - - // Corner case: if there are no elements, the impurity is zero. - if (numElem == 0) - return 0.0; - - arma::Col classCounts = arma::sum(counts, 1); - - // Calculate the Gini impurity of the un-split node. - double impurity = 0.0; - for (size_t i = 0; i < classCounts.n_elem; ++i) - { - const double f = ((double) classCounts[i] / (double) numElem); - impurity += f * (1.0 - f); - } - - // Now calculate the impurity of the split nodes and subtract them from the - // overall impurity. - for (size_t i = 0; i < counts.n_cols; ++i) - { - if (splitCounts[i] > 0) - { - double splitImpurity = 0.0; - for (size_t j = 0; j < counts.n_rows; ++j) - { - const double f = ((double) counts(j, i) / (double) splitCounts[i]); - splitImpurity += f * (1.0 - f); - } - - impurity -= ((double) splitCounts[i] / (double) numElem) * - splitImpurity; - } - } - - return impurity; - } - - /** - * Return the range of the Gini impurity for the given number of classes. - * (That is, the difference between the maximum possible value and the minimum - * possible value.) - */ - static double Range(const size_t numClasses) - { - // The best possible case is that only one class exists, which gives a Gini - // impurity of 0. The worst possible case is that the classes are evenly - // distributed, which gives n * (1/n * (1 - 1/n)) = 1 - 1/n. - return 1.0 - (1.0 / double(numClasses)); - } -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_categorical_split.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_categorical_split.hpp deleted file mode 100644 index 162999be1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_categorical_split.hpp +++ /dev/null @@ -1,129 +0,0 @@ -/** - * @file hoeffding_categorical_split.hpp - * @author Ryan Curtin - * - * A class that contains the information necessary to perform a categorical - * split for Hoeffding trees. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_CATEGORICAL_SPLIT_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_CATEGORICAL_SPLIT_HPP - -#include -#include "categorical_split_info.hpp" - -namespace mlpack { -namespace tree { - -/** - * This is the standard Hoeffding-bound categorical feature proposed in the - * paper below: - * - * @code - * @inproceedings{domingos2000mining, - * title={{Mining High-Speed Data Streams}}, - * author={Domingos, P. and Hulten, G.}, - * year={2000}, - * booktitle={Proceedings of the Sixth ACM SIGKDD International Conference on - * Knowledge Discovery and Data Mining (KDD '00)}, - * pages={71--80} - * } - * @endcode - * - * This class will track the sufficient statistics of the training points it has - * seen. The HoeffdingSplit class (and other related classes) can use this - * class to track categorical features and split decision tree nodes. - * - * @tparam FitnessFunction Fitness function to use for calculating gain. - */ -template -class HoeffdingCategoricalSplit -{ - public: - //! The type of split information required by the HoeffdingCategoricalSplit. - typedef CategoricalSplitInfo SplitInfo; - - /** - * Create the HoeffdingCategoricalSplit given a number of categories for this - * dimension and a number of classes. - * - * @param numCategories Number of categories in this dimension. - * @param numClasses Number of classes in this dimension. - */ - HoeffdingCategoricalSplit(const size_t numCategories = 0, - const size_t numClasses = 0); - - /** - * Create the HoeffdingCategoricalSplit given a number of categories for this - * dimension and a number of classes and another HoeffdingCategoricalSplit to - * take parameters from. In this particular case, there are no parameters to - * take, but this constructor is required by the HoeffdingTree class. - */ - HoeffdingCategoricalSplit(const size_t numCategories, - const size_t numClasses, - const HoeffdingCategoricalSplit& other); - - /** - * Train on the given value with the given label. - * - * @param value Value to train on. - * @param label Label to train on. - */ - template - void Train(eT value, const size_t label); - - /** - * Given the points seen so far, evaluate the fitness function, returning the - * gain for the best possible split and the second best possible split. In - * this splitting technique, we only split one possible way, so - * secondBestFitness will always be 0. - * - * @param bestFitness The fitness function result for this split. - * @param secondBestFitness This is always set to 0 (this split only splits - * one way). - */ - void EvaluateFitnessFunction(double& bestFitness, double& secondBestFitness) - const; - - //! Return the number of children, if the node were to split. - size_t NumChildren() const { return sufficientStatistics.n_cols; } - - /** - * Gather the information for a split: get the labels of the child majorities, - * and initialize the SplitInfo object. - * - * @param childMajorities Majorities of child nodes to be created. - * @param splitInfo Information for splitting. - */ - void Split(arma::Col& childMajorities, SplitInfo& splitInfo); - - //! Get the majority class seen so far. - size_t MajorityClass() const; - //! Get the probability of the majority class given the points seen so far. - double MajorityProbability() const; - - //! Serialize the categorical split. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(sufficientStatistics); - } - - private: - //! The sufficient statistics for all points seen so far. Each column - //! corresponds to a category, and contains a count of each of the classes - //! seen for points in that category. - arma::Mat sufficientStatistics; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "hoeffding_categorical_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_categorical_split_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_categorical_split_impl.hpp deleted file mode 100644 index 93e6a46fc..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_categorical_split_impl.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @file hoeffding_categorical_split_impl.hpp - * @author Ryan Curtin - * - * Implemental of the HoeffdingCategoricalSplit class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_CATEGORICAL_SPLIT_IMPL_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_CATEGORICAL_SPLIT_IMPL_HPP - -// In case it hasn't been included yet. -#include "hoeffding_categorical_split.hpp" - -namespace mlpack { -namespace tree { - -template -HoeffdingCategoricalSplit::HoeffdingCategoricalSplit( - const size_t numCategories, - const size_t numClasses) : - sufficientStatistics(numClasses, numCategories) -{ - sufficientStatistics.zeros(); -} - -template -HoeffdingCategoricalSplit::HoeffdingCategoricalSplit( - const size_t numCategories, - const size_t numClasses, - const HoeffdingCategoricalSplit& /* other */) : - sufficientStatistics(numClasses, numCategories) -{ - sufficientStatistics.zeros(); -} - -template -template -void HoeffdingCategoricalSplit::Train(eT value, - const size_t label) -{ - // Add this to our counts. - // 'value' should be categorical, so we should be able to cast to size_t... - sufficientStatistics(label, size_t(value))++; -} - -template -void HoeffdingCategoricalSplit::EvaluateFitnessFunction( - double& bestFitness, - double& secondBestFitness) const -{ - bestFitness = FitnessFunction::Evaluate(sufficientStatistics); - secondBestFitness = 0.0; // We only split one possible way. -} - -template -void HoeffdingCategoricalSplit::Split( - arma::Col& childMajorities, - SplitInfo& splitInfo) -{ - // We'll make one child for each category. - childMajorities.set_size(sufficientStatistics.n_cols); - for (size_t i = 0; i < sufficientStatistics.n_cols; ++i) - { - arma::uword maxIndex = 0; - sufficientStatistics.unsafe_col(i).max(maxIndex); - childMajorities[i] = size_t(maxIndex); - } - - // Create the according SplitInfo object. - splitInfo = SplitInfo(sufficientStatistics.n_cols); -} - -template -size_t HoeffdingCategoricalSplit::MajorityClass() const -{ - // Calculate the class that we have seen the most of. - arma::Col classCounts = arma::sum(sufficientStatistics, 1); - - arma::uword maxIndex = 0; - classCounts.max(maxIndex); - - return size_t(maxIndex); -} - -template -double HoeffdingCategoricalSplit::MajorityProbability() const -{ - arma::Col classCounts = arma::sum(sufficientStatistics, 1); - - return double(classCounts.max()) / double(arma::accu(classCounts)); -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_numeric_split.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_numeric_split.hpp deleted file mode 100644 index 48ef8cddb..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_numeric_split.hpp +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @file hoeffding_numeric_split.hpp - * @author Ryan Curtin - * - * A numeric feature split for Hoeffding trees. This is a very simple - * implementation based on a minor note in the paper "Mining High-Speed Data - * Streams" by Pedro Domingos and Geoff Hulten. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_NUMERIC_SPLIT_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_NUMERIC_SPLIT_HPP - -#include -#include "numeric_split_info.hpp" - -namespace mlpack { -namespace tree { - -/** - * The HoeffdingNumericSplit class implements the numeric feature splitting - * strategy alluded to by Domingos and Hulten in the following paper: - * - * @code - * @inproceedings{domingos2000mining, - * title={{Mining High-Speed Data Streams}}, - * author={Domingos, P. and Hulten, G.}, - * year={2000}, - * booktitle={Proceedings of the Sixth ACM SIGKDD International Conference on - * Knowledge Discovery and Data Mining (KDD '00)}, - * pages={71--80} - * } - * @endcode - * - * The strategy alluded to is very simple: we discretize the numeric features - * that we see. But in this case, we don't know how many bins we have, which - * makes things a little difficult. This class only makes binary splits, and - * has a maximum number of bins. The binning strategy is simple: the split - * caches the minimum and maximum value of points seen so far, and when the - * number of points hits a predefined threshold, the cached minimum-maximum - * range is equally split into bins, and splitting proceeds in the same way as - * with the categorical splits. This is a simple and stupid strategy, so don't - * expect it to be the best possible thing you can do. - * - * @tparam FitnessFunction Fitness function to use for calculating gain. - * @tparam ObservationType Type of observations in this dimension. - */ -template -class HoeffdingNumericSplit -{ - public: - //! The splitting information type required by the HoeffdingNumericSplit. - typedef NumericSplitInfo SplitInfo; - - /** - * Create the HoeffdingNumericSplit class, and specify some basic parameters - * about how the binning should take place. - * - * @param numClasses Number of classes. - * @param bins Number of bins. - * @param observationsBeforeBinning Number of points to see before binning is - * performed. - */ - HoeffdingNumericSplit(const size_t numClasses = 0, - const size_t bins = 10, - const size_t observationsBeforeBinning = 100); - - /** - * Create the HoeffdingNumericSplit class, using the parameters from the given - * other split object. - */ - HoeffdingNumericSplit(const size_t numClasses, - const HoeffdingNumericSplit& other); - - /** - * Train the HoeffdingNumericSplit on the given observed value (remember that - * this object only cares about the information for a single feature, not an - * entire point). - * - * @param value Value in the dimension that this HoeffdingNumericSplit refers - * to. - * @param label Label of the given point. - */ - void Train(ObservationType value, const size_t label); - - /** - * Evaluate the fitness function given what has been calculated so far. In - * this case, if binning has not yet been performed, 0 will be returned (i.e., - * no gain). Because this split can only split one possible way, - * secondBestFitness (the fitness function for the second best possible split) - * will be set to 0. - * - * @param bestFitness Value of the fitness function for the best possible - * split. - * @param secondBestFitness Value of the fitness function for the second best - * possible split (always 0 for this split). - */ - void EvaluateFitnessFunction(double& bestFitness, double& secondBestFitness) - const; - - //! Return the number of children if this node splits on this feature. - size_t NumChildren() const { return bins; } - - /** - * Return the majority class of each child to be created, if a split on this - * dimension was performed. Also create the split object. - */ - void Split(arma::Col& childMajorities, SplitInfo& splitInfo) const; - - //! Return the majority class. - size_t MajorityClass() const; - //! Return the probability of the majority class. - double MajorityProbability() const; - - //! Return the number of bins. - size_t Bins() const { return bins; } - - //! Serialize the object. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Before binning, this holds the points we have seen so far. - arma::Col observations; - //! This holds the labels of the points before binning. - arma::Col labels; - - //! The split points for the binning (length bins - 1). - arma::Col splitPoints; - //! The number of bins. - size_t bins; - //! The number of observations we must see before binning. - size_t observationsBeforeBinning; - //! The number of samples we have seen so far. - size_t samplesSeen; - - //! After binning, this contains the sufficient statistics. - arma::Mat sufficientStatistics; -}; - -//! Convenience typedef. -template -using HoeffdingDoubleNumericSplit = HoeffdingNumericSplit; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "hoeffding_numeric_split_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_numeric_split_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_numeric_split_impl.hpp deleted file mode 100644 index df0edee3d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_numeric_split_impl.hpp +++ /dev/null @@ -1,242 +0,0 @@ -/** - * @file hoeffding_numeric_split_impl.hpp - * @author Ryan Curtin - * - * An implementation of the simple HoeffdingNumericSplit class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_NUMERIC_SPLIT_IMPL_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_NUMERIC_SPLIT_IMPL_HPP - -#include "hoeffding_numeric_split.hpp" - -namespace mlpack { -namespace tree { - -template -HoeffdingNumericSplit::HoeffdingNumericSplit( - const size_t numClasses, - const size_t bins, - const size_t observationsBeforeBinning) : - observations(observationsBeforeBinning - 1), - labels(observationsBeforeBinning - 1), - bins(bins), - observationsBeforeBinning(observationsBeforeBinning), - samplesSeen(0), - sufficientStatistics(arma::zeros>(numClasses, bins)) -{ - observations.zeros(); - labels.zeros(); -} - -template -HoeffdingNumericSplit::HoeffdingNumericSplit( - const size_t numClasses, - const HoeffdingNumericSplit& other) : - observations(other.observationsBeforeBinning - 1), - labels(other.observationsBeforeBinning - 1), - bins(other.bins), - observationsBeforeBinning(other.observationsBeforeBinning), - samplesSeen(0), - sufficientStatistics(arma::zeros>(numClasses, bins)) -{ - observations.zeros(); - labels.zeros(); -} - -template -void HoeffdingNumericSplit::Train( - ObservationType value, - const size_t label) -{ - if (samplesSeen < observationsBeforeBinning - 1) - { - // Add this to the samples we have seen. - observations[samplesSeen] = value; - labels[samplesSeen] = label; - ++samplesSeen; - return; - } - else if (samplesSeen == observationsBeforeBinning - 1) - { - // Now we need to make the bins. - ObservationType min = value; - ObservationType max = value; - for (size_t i = 0; i < observationsBeforeBinning - 1; ++i) - { - if (observations[i] < min) - min = observations[i]; - else if (observations[i] > max) - max = observations[i]; - } - - // Now split these. We can't use linspace, because we don't want to include - // the endpoints. - splitPoints.resize(bins - 1); - const ObservationType binWidth = (max - min) / bins; - for (size_t i = 0; i < bins - 1; ++i) - splitPoints[i] = min + (i + 1) * binWidth; - ++samplesSeen; - - // Now, add all of the points we've seen to the sufficient statistics. - for (size_t i = 0; i < observationsBeforeBinning - 1; ++i) - { - // What bin does the point fall into? - size_t bin = 0; - while (bin < bins - 1 && observations[i] > splitPoints[bin]) - ++bin; - - sufficientStatistics(labels[i], bin)++; - } - } - - // If we've gotten to here, then we need to add the point to the sufficient - // statistics. What bin does the point fall into? - size_t bin = 0; - while (bin < bins - 1 && value > splitPoints[bin]) - ++bin; - - sufficientStatistics(label, bin)++; -} - -template -void HoeffdingNumericSplit:: - EvaluateFitnessFunction(double& bestFitness, - double& secondBestFitness) const -{ - secondBestFitness = 0.0; // We can only split one way. - if (samplesSeen < observationsBeforeBinning) - bestFitness = 0.0; - else - bestFitness = FitnessFunction::Evaluate(sufficientStatistics); -} - -template -void HoeffdingNumericSplit::Split( - arma::Col& childMajorities, - SplitInfo& splitInfo) const -{ - childMajorities.set_size(sufficientStatistics.n_cols); - for (size_t i = 0; i < sufficientStatistics.n_cols; ++i) - { - arma::uword maxIndex = 0; - sufficientStatistics.unsafe_col(i).max(maxIndex); - childMajorities[i] = size_t(maxIndex); - } - - // Create the SplitInfo object. - splitInfo = SplitInfo(splitPoints); -} - -template -size_t HoeffdingNumericSplit:: - MajorityClass() const -{ - // If we haven't yet determined the bins, we must calculate this by hand. - if (samplesSeen < observationsBeforeBinning) - { - arma::Col classes(sufficientStatistics.n_rows); - classes.zeros(); - - for (size_t i = 0; i < samplesSeen; ++i) - classes[labels[i]]++; - - arma::uword majorityClass; - classes.max(majorityClass); - return size_t(majorityClass); - } - else - { - // We've calculated the bins, so we can just sum over the sufficient - // statistics. - arma::Col classCounts = arma::sum(sufficientStatistics, 1); - - arma::uword maxIndex = 0; - classCounts.max(maxIndex); - return size_t(maxIndex); - } -} - -template -double HoeffdingNumericSplit:: - MajorityProbability() const -{ - // If we haven't yet determined the bins, we must calculate this by hand. - if (samplesSeen < observationsBeforeBinning) - { - arma::Col classes(sufficientStatistics.n_rows); - classes.zeros(); - - for (size_t i = 0; i < samplesSeen; ++i) - classes[labels[i]]++; - - return double(classes.max()) / double(arma::accu(classes)); - } - else - { - // We've calculated the bins, so we can just sum over the sufficient - // statistics. - arma::Col classCounts = arma::sum(sufficientStatistics, 1); - - return double(classCounts.max()) / double(arma::sum(classCounts)); - } -} - -template -template -void HoeffdingNumericSplit::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(samplesSeen); - ar & BOOST_SERIALIZATION_NVP(observationsBeforeBinning); - ar & BOOST_SERIALIZATION_NVP(bins); - - if (samplesSeen >= observationsBeforeBinning) - { - // The binning has happened, so we only need to save the resulting bins. - ar & BOOST_SERIALIZATION_NVP(splitPoints); - ar & BOOST_SERIALIZATION_NVP(sufficientStatistics); - - if (Archive::is_loading::value) - { - // Clean other objects. - observations.clear(); - labels.clear(); - } - } - else - { - // The binning has not happened yet, so we only need to save the information - // required before binning. - if (Archive::is_loading::value) - { - observations.zeros(observationsBeforeBinning); - labels.zeros(observationsBeforeBinning); - } - - // Save the number of classes. - size_t numClasses; - if (Archive::is_saving::value) - numClasses = sufficientStatistics.n_rows; - ar & BOOST_SERIALIZATION_NVP(numClasses); - ar & BOOST_SERIALIZATION_NVP(observations); - ar & BOOST_SERIALIZATION_NVP(labels); - - if (Archive::is_loading::value) - { - // Clean other objects. - splitPoints.clear(); - sufficientStatistics.zeros(numClasses, bins); - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree.hpp deleted file mode 100644 index d5e5d33c5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree.hpp +++ /dev/null @@ -1,362 +0,0 @@ -/** - * @file hoeffding_split.hpp - * @author Ryan Curtin - * - * An implementation of the standard Hoeffding tree by Pedro Domingos and Geoff - * Hulten in ``Mining High-Speed Data Streams''. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_TREE_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_TREE_HPP - -#include -#include -#include "gini_impurity.hpp" -#include "hoeffding_numeric_split.hpp" -#include "hoeffding_categorical_split.hpp" - -namespace mlpack { -namespace tree { - -/** - * The HoeffdingTree object represents all of the necessary information for a - * Hoeffding-bound-based decision tree. This class is able to train on samples - * in streaming settings and batch settings, and perform splits based on the - * Hoeffding bound. The Hoeffding tree (also known as the "very fast decision - * tree" -- VFDT) is described in the following paper: - * - * @code - * @inproceedings{domingos2000mining, - * title={{Mining High-Speed Data Streams}}, - * author={Domingos, P. and Hulten, G.}, - * year={2000}, - * booktitle={Proceedings of the Sixth ACM SIGKDD International Conference - * on Knowledge Discovery and Data Mining (KDD '00)}, - * pages={71--80} - * } - * @endcode - * - * The class is modular, and takes three template parameters. The first, - * FitnessFunction, is the fitness function that should be used to determine - * whether a split is beneficial; examples might be GiniImpurity or - * InformationGain. The NumericSplitType determines how numeric attributes are - * handled, and the CategoricalSplitType determines how categorical attributes - * are handled. As far as the actual splitting goes, the meat of the splitting - * procedure will be contained in those two classes. - * - * @tparam FitnessFunction Fitness function to use. - * @tparam NumericSplitType Technique for splitting numeric features. - * @tparam CategoricalSplitType Technique for splitting categorical features. - */ -template class NumericSplitType = - HoeffdingDoubleNumericSplit, - template class CategoricalSplitType = - HoeffdingCategoricalSplit -> -class HoeffdingTree -{ - public: - //! Allow access to the numeric split type. - typedef NumericSplitType NumericSplit; - //! Allow access to the categorical split type. - typedef CategoricalSplitType CategoricalSplit; - - /** - * Construct the Hoeffding tree with the given parameters and given training - * data. The tree may be trained either in batch mode (which looks at all - * points before splitting, and propagates these points to the created - * children for further training), or in streaming mode, where each point is - * only considered once. (In general, batch mode will give better-performing - * trees, but will have higher memory and runtime costs for the same dataset.) - * - * @param data Dataset to train on. - * @param datasetInfo Information on the dataset (types of each feature). - * @param labels Labels of each point in the dataset. - * @param numClasses Number of classes in the dataset. - * @param batchTraining Whether or not to train in batch. - * @param successProbability Probability of success required in Hoeffding - * bounds before a split can happen. - * @param maxSamples Maximum number of samples before a split is forced (0 - * never forces a split); ignored in batch training mode. - * @param checkInterval Number of samples required before each split; ignored - * in batch training mode. - * @param minSamples If the node has seen this many points or fewer, no split - * will be allowed. - */ - template - HoeffdingTree(const MatType& data, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const bool batchTraining = true, - const double successProbability = 0.95, - const size_t maxSamples = 0, - const size_t checkInterval = 100, - const size_t minSamples = 100, - const CategoricalSplitType& categoricalSplitIn - = CategoricalSplitType(0, 0), - const NumericSplitType& numericSplitIn = - NumericSplitType(0)); - - /** - * Construct the Hoeffding tree with the given parameters, but training on no - * data. The dimensionMappings parameter is only used if it is desired that - * this node does not create its own dimensionMappings object (for instance, - * if this is a child of another node in the tree). - * - * @param dimensionality Dimensionality of the dataset. - * @param numClasses Number of classes in the dataset. - * @param datasetInfo Information on the dataset (types of each feature). - * @param successProbability Probability of success required in Hoeffding - * bound before a split can happen. - * @param maxSamples Maximum number of samples before a split is forced. - * @param checkInterval Number of samples required before each split check. - * @param minSamples If the node has seen this many points or fewer, no split - * will be allowed. - * @param dimensionMappings Mappings from dimension indices to positions in - * numeric and categorical split vectors. If left NULL, a new one will - * be created. - */ - HoeffdingTree(const data::DatasetInfo& datasetInfo, - const size_t numClasses, - const double successProbability = 0.95, - const size_t maxSamples = 0, - const size_t checkInterval = 100, - const size_t minSamples = 100, - const CategoricalSplitType& categoricalSplitIn - = CategoricalSplitType(0, 0), - const NumericSplitType& numericSplitIn = - NumericSplitType(0), - std::unordered_map>* - dimensionMappings = NULL); - - /** - * Construct a Hoeffding tree with no data and no information. Be sure to - * call Train() before trying to use the tree. - */ - HoeffdingTree(); - - /** - * Copy another tree (warning: this will duplicate the tree entirely, and may - * use a lot of memory. Make sure it's what you want before you do it). - * - * @param other Tree to copy. - */ - HoeffdingTree(const HoeffdingTree& other); - - /** - * Clean up memory. - */ - ~HoeffdingTree(); - - /** - * Train on a set of points, either in streaming mode or in batch mode, with - * the given labels. - * - * @param data Data points to train on. - * @param label Labels of data points. - * @param batchTraining If true, perform training in batch. - */ - template - void Train(const MatType& data, - const arma::Row& labels, - const bool batchTraining = true); - - /** - * Train on a set of points, either in streaming mode or in batch mode, with - * the given labels and the given DatasetInfo. This will reset the tree. - */ - template - void Train(const MatType& data, - const data::DatasetInfo& info, - const arma::Row& labels, - const bool batchTraining = true); - - /** - * Train on a single point in streaming mode, with the given label. - * - * @param point Point to train on. - * @param label Label of point to train on. - */ - template - void Train(const VecType& point, const size_t label); - - /** - * Check if a split would satisfy the conditions of the Hoeffding bound with - * the node's specified success probability. If so, the number of children - * that would be created is returned. If not, 0 is returned. - */ - size_t SplitCheck(); - - //! Get the splitting dimension (size_t(-1) if no split). - size_t SplitDimension() const { return splitDimension; } - - //! Get the majority class. - size_t MajorityClass() const { return majorityClass; } - //! Modify the majority class. - size_t& MajorityClass() { return majorityClass; } - - //! Get the probability of the majority class (based on training samples). - double MajorityProbability() const { return majorityProbability; } - //! Modify the probability of the majority class. - double& MajorityProbability() { return majorityProbability; } - - //! Get the number of children. - size_t NumChildren() const { return children.size(); } - - //! Get a child. - const HoeffdingTree& Child(const size_t i) const { return *children[i]; } - //! Modify a child. - HoeffdingTree& Child(const size_t i) { return *children[i]; } - - //! Get the confidence required for a split. - double SuccessProbability() const { return successProbability; } - //! Modify the confidence required for a split. - void SuccessProbability(const double successProbability); - - //! Get the minimum number of samples for a split. - size_t MinSamples() const { return minSamples; } - //! Modify the minimum number of samples for a split. - void MinSamples(const size_t minSamples); - - //! Get the maximum number of samples before a split is forced. - size_t MaxSamples() const { return maxSamples; } - //! Modify the maximum number of samples before a split is forced. - void MaxSamples(const size_t maxSamples); - - //! Get the number of samples before a split check is performed. - size_t CheckInterval() const { return checkInterval; } - //! Modify the number of samples before a split check is performed. - void CheckInterval(const size_t checkInterval); - - /** - * Given a point and that this node is not a leaf, calculate the index of the - * child node this point would go towards. This method is primarily used by - * the Classify() function, but it can be used in a standalone sense too. - * - * @param point Point to classify. - */ - template - size_t CalculateDirection(const VecType& point) const; - - /** - * Classify the given point, using this node and the entire (sub)tree beneath - * it. The predicted label is returned. - * - * @param point Point to classify. - * @return Predicted label of point. - */ - template - size_t Classify(const VecType& point) const; - - //! Get the size of the Hoeffding Tree. - size_t NumDescendants() const; - - /** - * Classify the given point and also return an estimate of the probability - * that the prediction is correct. (This estimate is simply the probability - * that a training point was from the majority class in the leaf that this - * point binned to.) - * - * @param point Point to classify. - * @param prediction Predicted label of point. - * @param probability An estimate of the probability that the prediction is - * correct. - */ - template - void Classify(const VecType& point, size_t& prediction, double& probability) - const; - - /** - * Classify the given points, using this node and the entire (sub)tree beneath - * it. The predicted labels for each point are returned. - * - * @param data Points to classify. - * @param predictions Predicted labels for each point. - */ - template - void Classify(const MatType& data, arma::Row& predictions) const; - - /** - * Classify the given points, using this node and the entire (sub)tree beneath - * it. The predicted labels for each point are returned, as well as an - * estimate of the probability that the prediction is correct for each point. - * This estimate is simply the MajorityProbability() for the leaf that each - * point bins to. - * - * @param data Points to classify. - * @param predictions Predicted labels for each point. - * @param probabilities Probability estimates for each predicted label. - */ - template - void Classify(const MatType& data, - arma::Row& predictions, - arma::rowvec& probabilities) const; - - /** - * Given that this node should split, create the children. - */ - void CreateChildren(); - - //! Serialize the split. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - // We need to keep some information for before we have split. - - //! Information for splitting of numeric features (used before split). - std::vector> numericSplits; - //! Information for splitting of categorical features (used before split). - std::vector> categoricalSplits; - - //! This structure is owned by this node only if it is the root of the tree. - std::unordered_map>* dimensionMappings; - //! Indicates whether or not we own the mappings. - bool ownsMappings; - - //! The number of samples seen so far by this node. - size_t numSamples; - //! The number of classes this node is trained on. - size_t numClasses; - //! The maximum number of samples we can see before splitting. - size_t maxSamples; - //! The number of samples that should be seen before checking for a split. - size_t checkInterval; - //! The minimum number of samples for splitting. - size_t minSamples; - //! The dataset information. - const data::DatasetInfo* datasetInfo; - //! Whether or not we own the dataset information. - bool ownsInfo; - //! The required probability of success for a split to be performed. - double successProbability; - - // And we need to keep some information for after we have split. - - //! The dimension that this node has split on. - size_t splitDimension; - //! The majority class of this node. - size_t majorityClass; - //! The empirical probability of a point this node saw having the majority - //! class. - double majorityProbability; - //! If the split is categorical, this holds the splitting information. - typename CategoricalSplitType::SplitInfo categoricalSplit; - //! If the split is numeric, this holds the splitting information. - typename NumericSplitType::SplitInfo numericSplit; - //! If the split has occurred, these are the children. - std::vector children; -}; - -} // namespace tree -} // namespace mlpack - -#include "hoeffding_tree_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree_impl.hpp deleted file mode 100644 index a2f79529d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree_impl.hpp +++ /dev/null @@ -1,889 +0,0 @@ -/** - * @file hoeffding_split_impl.hpp - * @author Ryan Curtin - * - * Implementation of the HoeffdingTree class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_TREE_IMPL_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_HOEFFDING_TREE_IMPL_HPP - -// In case it hasn't been included yet. -#include "hoeffding_tree.hpp" -#include - -namespace mlpack { -namespace tree { - -template class NumericSplitType, - template class CategoricalSplitType> -template -HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::HoeffdingTree(const MatType& data, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const bool batchTraining, - const double successProbability, - const size_t maxSamples, - const size_t checkInterval, - const size_t minSamples, - const CategoricalSplitType& - categoricalSplitIn, - const NumericSplitType& numericSplitIn) : - dimensionMappings(new std::unordered_map>()), - ownsMappings(true), - numSamples(0), - numClasses(numClasses), - maxSamples((maxSamples == 0) ? size_t(-1) : maxSamples), - checkInterval(checkInterval), - minSamples(minSamples), - datasetInfo(new data::DatasetInfo(datasetInfo)), - ownsInfo(true), - successProbability(successProbability), - splitDimension(size_t(-1)), - categoricalSplit(0), - numericSplit() -{ - // Generate dimension mappings and create split objects. - for (size_t i = 0; i < datasetInfo.Dimensionality(); ++i) - { - if (datasetInfo.Type(i) == data::Datatype::categorical) - { - categoricalSplits.push_back(CategoricalSplitType( - datasetInfo.NumMappings(i), numClasses, categoricalSplitIn)); - (*dimensionMappings)[i] = std::make_pair(data::Datatype::categorical, - categoricalSplits.size() - 1); - } - else - { - numericSplits.push_back(NumericSplitType(numClasses, - numericSplitIn)); - (*dimensionMappings)[i] = std::make_pair(data::Datatype::numeric, - numericSplits.size() - 1); - } - } - - // Now train. - Train(data, labels, batchTraining); -} - -template class NumericSplitType, - template class CategoricalSplitType> -HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::HoeffdingTree(const data::DatasetInfo& datasetInfo, - const size_t numClasses, - const double successProbability, - const size_t maxSamples, - const size_t checkInterval, - const size_t minSamples, - const CategoricalSplitType& - categoricalSplitIn, - const NumericSplitType& numericSplitIn, - std::unordered_map>* - dimensionMappingsIn) : - dimensionMappings((dimensionMappingsIn != NULL) ? dimensionMappingsIn : - new std::unordered_map>()), - ownsMappings(dimensionMappingsIn == NULL), - numSamples(0), - numClasses(numClasses), - maxSamples((maxSamples == 0) ? size_t(-1) : maxSamples), - checkInterval(checkInterval), - minSamples(minSamples), - datasetInfo(new data::DatasetInfo(datasetInfo)), - ownsInfo(true), - successProbability(successProbability), - splitDimension(size_t(-1)), - categoricalSplit(0), - numericSplit() -{ - // Do we need to generate the mappings too? - if (ownsMappings) - { - for (size_t i = 0; i < datasetInfo.Dimensionality(); ++i) - { - if (datasetInfo.Type(i) == data::Datatype::categorical) - { - categoricalSplits.push_back(CategoricalSplitType( - datasetInfo.NumMappings(i), numClasses, categoricalSplitIn)); - (*dimensionMappings)[i] = std::make_pair(data::Datatype::categorical, - categoricalSplits.size() - 1); - } - else - { - numericSplits.push_back(NumericSplitType(numClasses, - numericSplitIn)); - (*dimensionMappings)[i] = std::make_pair(data::Datatype::numeric, - numericSplits.size() - 1); - } - } - } - else - { - for (size_t i = 0; i < datasetInfo.Dimensionality(); ++i) - { - if (datasetInfo.Type(i) == data::Datatype::categorical) - { - categoricalSplits.push_back(CategoricalSplitType( - datasetInfo.NumMappings(i), numClasses, categoricalSplitIn)); - } - else - { - numericSplits.push_back(NumericSplitType(numClasses, - numericSplitIn)); - } - } - } -} - -template class NumericSplitType, - template class CategoricalSplitType> -HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::HoeffdingTree() : - dimensionMappings( - new std::unordered_map>()), - ownsMappings(true), - numSamples(0), - numClasses(0), - maxSamples(size_t(-1)), - checkInterval(100), - minSamples(100), - datasetInfo(new data::DatasetInfo()), - ownsInfo(true), - successProbability(0.95), - splitDimension(size_t(-1)), - categoricalSplit(0), - numericSplit() -{ - // Nothing to do. -} - -// Copy constructor. -template class NumericSplitType, - template class CategoricalSplitType> -HoeffdingTree:: - HoeffdingTree(const HoeffdingTree& other) : - numericSplits(other.numericSplits), - categoricalSplits(other.categoricalSplits), - dimensionMappings(new std::unordered_map>(*other.dimensionMappings)), - ownsMappings(true), - numSamples(other.numSamples), - numClasses(other.numClasses), - maxSamples(other.maxSamples), - checkInterval(other.checkInterval), - minSamples(other.minSamples), - datasetInfo(new data::DatasetInfo(*other.datasetInfo)), - ownsInfo(true), - successProbability(other.successProbability), - splitDimension(other.splitDimension), - majorityClass(other.majorityClass), - majorityProbability(other.majorityProbability), - categoricalSplit(other.categoricalSplit), - numericSplit(other.numericSplit) -{ - // Copy each of the children. - for (size_t i = 0; i < other.children.size(); ++i) - children.push_back(new HoeffdingTree(*other.children[i])); -} - -template class NumericSplitType, - template class CategoricalSplitType> -HoeffdingTree:: - ~HoeffdingTree() -{ - if (ownsMappings) - delete dimensionMappings; - if (ownsInfo) - delete datasetInfo; - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; -} - -//! Train on a set of points. -template class NumericSplitType, - template class CategoricalSplitType> -template -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::Train(const MatType& data, - const arma::Row& labels, - const bool batchTraining) -{ - if (batchTraining) - { - // Pass all the points through the nodes, and then split only after that. - checkInterval = data.n_cols; // Only split on the last sample. - // Don't split if there are fewer than five points. - size_t oldMaxSamples = maxSamples; - maxSamples = std::max(size_t(data.n_cols - 1), size_t(5)); - for (size_t i = 0; i < data.n_cols; ++i) - Train(data.col(i), labels[i]); - maxSamples = oldMaxSamples; - - // Now, if we did split, find out which points go to which child, and - // perform the same batch training. - if (children.size() > 0) - { - // We need to create a vector of indices that represent the points that - // must go to each child, so we need children.size() vectors, but we don't - // know how long they will be. Therefore, we will create vectors each of - // size data.n_cols, but will probably not use all the memory we - // allocated, and then pass subvectors to the submat() function. - std::vector indices(children.size(), arma::uvec(data.n_cols)); - arma::Col counts = - arma::zeros>(children.size()); - - for (size_t i = 0; i < data.n_cols; ++i) - { - size_t direction = CalculateDirection(data.col(i)); - size_t currentIndex = counts[direction]; - indices[direction][currentIndex] = i; - counts[direction]++; - } - - // Now pass each of these submatrices to the children to perform - // batch-mode training. - for (size_t i = 0; i < children.size(); ++i) - { - // If we don't have any points that go to the child in question, don't - // train that child. - if (counts[i] == 0) - continue; - - // The submatrix here is non-contiguous, but I think this will be faster - // than copying the points to an ordered state. We still have to - // assemble the labels vector, though. - arma::Row childLabels = labels.cols( - indices[i].subvec(0, counts[i] - 1)); - - // Unfortunately, limitations of Armadillo's non-contiguous subviews - // prohibits us from successfully passing the non-contiguous subview to - // Train(), since the col() function is not provided. So, - // unfortunately, instead, we'll just extract the non-contiguous - // submatrix. - MatType childData = data.cols(indices[i].subvec(0, counts[i] - 1)); - children[i]->Train(childData, childLabels, true); - } - } - } - else - { - // We aren't training in batch mode; loop through the points. - for (size_t i = 0; i < data.n_cols; ++i) - Train(data.col(i), labels[i]); - } -} - -//! Train on a set of points. -template class NumericSplitType, - template class CategoricalSplitType> -template -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::Train(const MatType& data, - const data::DatasetInfo& info, - const arma::Row& labels, - const bool batchTraining) -{ - // Take over new DatasetInfo. - if (ownsInfo) - delete datasetInfo; - datasetInfo = &info; - ownsInfo = false; - - // Generate mappings. - if (ownsMappings) - delete dimensionMappings; - - const CategoricalSplitType categoricalSplitIn(0, 0); - const NumericSplitType& numericSplitIn(0); - - dimensionMappings = - new std::unordered_map>(); - for (size_t i = 0; i < datasetInfo->Dimensionality(); ++i) - { - if (datasetInfo->Type(i) == data::Datatype::categorical) - { - categoricalSplits.push_back(CategoricalSplitType( - datasetInfo->NumMappings(i), numClasses, categoricalSplitIn)); - (*dimensionMappings)[i] = std::make_pair(data::Datatype::categorical, - categoricalSplits.size() - 1); - } - else - { - numericSplits.push_back(NumericSplitType(numClasses, - numericSplitIn)); - (*dimensionMappings)[i] = std::make_pair(data::Datatype::numeric, - numericSplits.size() - 1); - } - } - - // Remove any old children. - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); - - // Now train. - Train(data, labels, batchTraining); -} - -//! Train on one point. -template class NumericSplitType, - template class CategoricalSplitType> -template -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::Train(const VecType& point, const size_t label) -{ - if (splitDimension == size_t(-1)) - { - ++numSamples; - size_t numericIndex = 0; - size_t categoricalIndex = 0; - for (size_t i = 0; i < point.n_rows; ++i) - { - if (datasetInfo->Type(i) == data::Datatype::categorical) - categoricalSplits[categoricalIndex++].Train(point[i], label); - else if (datasetInfo->Type(i) == data::Datatype::numeric) - numericSplits[numericIndex++].Train(point[i], label); - } - - // Grab majority class from splits. - if (categoricalSplits.size() > 0) - { - majorityClass = categoricalSplits[0].MajorityClass(); - majorityProbability = categoricalSplits[0].MajorityProbability(); - } - else - { - majorityClass = numericSplits[0].MajorityClass(); - majorityProbability = numericSplits[0].MajorityProbability(); - } - - // Check for a split, if we should. - if (numSamples % checkInterval == 0) - { - const size_t numChildren = SplitCheck(); - if (numChildren > 0) - { - // We need to add a bunch of children. - // Delete children, if we have them. - children.clear(); - CreateChildren(); - } - } - } - else - { - // Already split. Pass the training point to the relevant child. - size_t direction = CalculateDirection(point); - children[direction]->Train(point, label); - } -} - -template class NumericSplitType, - template class CategoricalSplitType> -size_t HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::SplitCheck() -{ - // Do nothing if we've already split. - if (splitDimension != size_t(-1)) - return 0; - - // If not enough points have been seen, we cannot split. - if (numSamples <= minSamples) - return 0; - - // Check the fitness of each dimension. Then we'll use a Hoeffding bound - // somehow. - - // Calculate epsilon, the value we need things to be greater than. - const double rSquared = std::pow(FitnessFunction::Range(numClasses), 2.0); - const double epsilon = std::sqrt(rSquared * - std::log(1.0 / (1.0 - successProbability)) / (2 * numSamples)); - - // Find the best and second best possible splits. - double largest = -DBL_MAX; - size_t largestIndex = 0; - double secondLargest = -DBL_MAX; - for (size_t i = 0; i < categoricalSplits.size() + numericSplits.size(); ++i) - { - size_t type = dimensionMappings->at(i).first; - size_t index = dimensionMappings->at(i).second; - - // Some split procedures can split multiple ways, but we only care about the - // best two splits that can be done in every network. - double bestGain = 0.0; - double secondBestGain = 0.0; - if (type == data::Datatype::categorical) - categoricalSplits[index].EvaluateFitnessFunction(bestGain, - secondBestGain); - else if (type == data::Datatype::numeric) - numericSplits[index].EvaluateFitnessFunction(bestGain, secondBestGain); - - // See if these gains are better than the previous. - if (bestGain > largest) - { - secondLargest = largest; - largest = bestGain; - largestIndex = i; - } - else if (bestGain > secondLargest) - { - secondLargest = bestGain; - } - - if (secondBestGain > secondLargest) - { - secondLargest = secondBestGain; - } - } - - // Are these far enough apart to split? - if ((largest > 0.0) && - ((largest - secondLargest > epsilon) || (numSamples > maxSamples) || - (epsilon <= 0.05))) - { - // Split! - splitDimension = largestIndex; - const size_t type = dimensionMappings->at(largestIndex).first; - const size_t index = dimensionMappings->at(largestIndex).second; - if (type == data::Datatype::categorical) - { - // I don't know if this should be here. - majorityClass = categoricalSplits[index].MajorityClass(); - return categoricalSplits[index].NumChildren(); - } - else - { - majorityClass = numericSplits[index].MajorityClass(); - return numericSplits[index].NumChildren(); - } - } - else - { - return 0; // Don't split. - } -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::SuccessProbability(const double successProbability) -{ - this->successProbability = successProbability; - for (size_t i = 0; i < children.size(); ++i) - children[i]->SuccessProbability(successProbability); -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::MinSamples(const size_t minSamples) -{ - this->minSamples = minSamples; - for (size_t i = 0; i < children.size(); ++i) - children[i]->MinSamples(minSamples); -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::MaxSamples(const size_t maxSamples) -{ - this->maxSamples = maxSamples; - for (size_t i = 0; i < children.size(); ++i) - children[i]->MaxSamples(maxSamples); -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::CheckInterval(const size_t checkInterval) -{ - this->checkInterval = checkInterval; - for (size_t i = 0; i < children.size(); ++i) - children[i]->CheckInterval(checkInterval); -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -template -size_t HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::CalculateDirection(const VecType& point) const -{ - // Don't call this before the node is split... - if (datasetInfo->Type(splitDimension) == data::Datatype::numeric) - return numericSplit.CalculateDirection(point[splitDimension]); - else if (datasetInfo->Type(splitDimension) == data::Datatype::categorical) - return categoricalSplit.CalculateDirection(point[splitDimension]); - else - return 0; // Not sure what to do here... -} - -template class NumericSplitType, - template class CategoricalSplitType> -size_t HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::NumDescendants() const -{ - size_t nodes = 0; - std::stack stack; - stack.push(this); // Push the current tree. - while (!stack.empty()) - { - const HoeffdingTree* node = stack.top(); - stack.pop(); - nodes += node->NumChildren(); - for (size_t i = 0; i < node->NumChildren(); ++i) - stack.push(&node->Child(i)); - } - return nodes; -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -template -size_t HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::Classify(const VecType& point) const -{ - if (children.size() == 0) - { - // If we're a leaf (or being considered a leaf), classify based on what we - // know. - return majorityClass; - } - else - { - // Otherwise, pass to the right child and let them classify. - return children[CalculateDirection(point)]->Classify(point); - } -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -template -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::Classify(const VecType& point, - size_t& prediction, - double& probability) const -{ - if (children.size() == 0) - { - // We are a leaf, so classify accordingly. - prediction = majorityClass; - probability = majorityProbability; - } - else - { - // Pass to the right child and let them do the classification. - children[CalculateDirection(point)]->Classify(point, prediction, - probability); - } -} - -//! Batch classification. -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -template -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::Classify(const MatType& data, arma::Row& predictions) const -{ - predictions.set_size(data.n_cols); - for (size_t i = 0; i < data.n_cols; ++i) - predictions[i] = Classify(data.col(i)); -} - -//! Batch classification with probabilities. -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -template -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::Classify(const MatType& data, - arma::Row& predictions, - arma::rowvec& probabilities) const -{ - predictions.set_size(data.n_cols); - probabilities.set_size(data.n_cols); - for (size_t i = 0; i < data.n_cols; ++i) - Classify(data.col(i), predictions[i], probabilities[i]); -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::CreateChildren() -{ - // Create the children. - arma::Col childMajorities; - if (dimensionMappings->at(splitDimension).first == - data::Datatype::categorical) - { - categoricalSplits[dimensionMappings->at(splitDimension).second].Split( - childMajorities, categoricalSplit); - } - else if (dimensionMappings->at(splitDimension).first == - data::Datatype::numeric) - { - numericSplits[dimensionMappings->at(splitDimension).second].Split( - childMajorities, numericSplit); - } - - // We already know what the splitDimension will be. - for (size_t i = 0; i < childMajorities.n_elem; ++i) - { - // We need to also give our split objects to the new children, so that - // parameters for the splits can be passed down. But if we have no - // categorical or numeric features, we can't pass anything but the - // defaults... - if (categoricalSplits.size() == 0) - { - // Pass a default categorical split. - children.push_back(new HoeffdingTree(*datasetInfo, numClasses, - successProbability, maxSamples, checkInterval, minSamples, - CategoricalSplitType(0, numClasses), - numericSplits[0], dimensionMappings)); - } - else if (numericSplits.size() == 0) - { - // Pass a default numeric split. - children.push_back(new HoeffdingTree(*datasetInfo, numClasses, - successProbability, maxSamples, checkInterval, minSamples, - categoricalSplits[0], NumericSplitType(numClasses), - dimensionMappings)); - } - else - { - // Pass both splits that we already have. - children.push_back(new HoeffdingTree(*datasetInfo, numClasses, - successProbability, maxSamples, checkInterval, minSamples, - categoricalSplits[0], numericSplits[0], dimensionMappings)); - } - - children[i]->MajorityClass() = childMajorities[i]; - } - - // Eliminate now-unnecessary split information. - numericSplits.clear(); - categoricalSplits.clear(); -} - -template< - typename FitnessFunction, - template class NumericSplitType, - template class CategoricalSplitType -> -template -void HoeffdingTree< - FitnessFunction, - NumericSplitType, - CategoricalSplitType ->::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(splitDimension); - - // Clear memory for the mappings if necessary. - if (Archive::is_loading::value && ownsMappings && dimensionMappings) - delete dimensionMappings; - - ar & BOOST_SERIALIZATION_NVP(dimensionMappings); - - // Special handling for const object. - data::DatasetInfo* d = NULL; - if (Archive::is_saving::value) - d = const_cast(datasetInfo); - ar & BOOST_SERIALIZATION_NVP(d); - if (Archive::is_loading::value) - { - if (datasetInfo && ownsInfo) - delete datasetInfo; - - datasetInfo = d; - ownsInfo = true; - ownsMappings = true; // We also own the mappings we loaded. - - // Clear the children. - for (size_t i = 0; i < children.size(); ++i) - delete children[i]; - children.clear(); - } - - ar & BOOST_SERIALIZATION_NVP(majorityClass); - ar & BOOST_SERIALIZATION_NVP(majorityProbability); - - // Depending on whether or not we have split yet, we may need to save - // different things. - if (splitDimension == size_t(-1)) - { - // We have not yet split. So we have to serialize the splits. - ar & BOOST_SERIALIZATION_NVP(numSamples); - ar & BOOST_SERIALIZATION_NVP(numClasses); - ar & BOOST_SERIALIZATION_NVP(maxSamples); - ar & BOOST_SERIALIZATION_NVP(successProbability); - - // Serialize the splits, but not if we haven't seen any samples yet (in - // which case we can just reinitialize). - if (Archive::is_loading::value) - { - // Re-initialize all of the splits. - numericSplits.clear(); - categoricalSplits.clear(); - for (size_t i = 0; i < datasetInfo->Dimensionality(); ++i) - { - if (datasetInfo->Type(i) == data::Datatype::categorical) - categoricalSplits.push_back(CategoricalSplitType( - datasetInfo->NumMappings(i), numClasses)); - else - numericSplits.push_back( - NumericSplitType(numClasses)); - } - - // Clear things we don't need. - categoricalSplit = typename CategoricalSplitType:: - SplitInfo(numClasses); - numericSplit = typename NumericSplitType::SplitInfo(); - } - - // There's no need to serialize if there's no information contained in the - // splits. - if (numSamples == 0) - return; - - // Serialize numeric splits. - ar & BOOST_SERIALIZATION_NVP(numericSplits); - - // Serialize categorical splits. - ar & BOOST_SERIALIZATION_NVP(categoricalSplits); - } - else - { - // We have split, so we only need to save the split and the children. - if (datasetInfo->Type(splitDimension) == data::Datatype::categorical) - ar & BOOST_SERIALIZATION_NVP(categoricalSplit); - else - ar & BOOST_SERIALIZATION_NVP(numericSplit); - - // Serialize the children, because we have split. - ar & BOOST_SERIALIZATION_NVP(children); - - if (Archive::is_loading::value) - { - for (size_t i = 0; i < children.size(); ++i) - { - // The child doesn't actually own its own DatasetInfo. We do. The same - // applies for the dimension mappings. - children[i]->ownsInfo = false; - children[i]->ownsMappings = false; - } - - numericSplits.clear(); - categoricalSplits.clear(); - - numSamples = 0; - numClasses = 0; - maxSamples = 0; - successProbability = 0.0; - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree_model.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree_model.hpp deleted file mode 100644 index 7ab8754f3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/hoeffding_tree_model.hpp +++ /dev/null @@ -1,243 +0,0 @@ -/** - * @file hoeffding_tree_model.hpp - * @author Ryan Curtin - * - * A serializable model for the mlpack_hoeffding_tree command-line program. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREE_HOEFFDING_TREE_MODEL_HPP -#define MLPACK_METHODS_HOEFFDING_TREE_HOEFFDING_TREE_MODEL_HPP - -#include "hoeffding_tree.hpp" -#include "binary_numeric_split.hpp" -#include "information_gain.hpp" - -namespace mlpack { -namespace tree { - -/** - * This class is a serializable Hoeffding tree model that can hold four - * different types of Hoeffding trees. It is meant to be used by the - * command-line program for Hoeffding trees. - */ -class HoeffdingTreeModel -{ - public: - //! This enumerates the four types of trees we can hold. - enum TreeType - { - GINI_HOEFFDING, - GINI_BINARY, - INFO_HOEFFDING, - INFO_BINARY - }; - - //! Convenience typedef for GINI_HOEFFDING tree type. - typedef HoeffdingTree GiniHoeffdingTreeType; - //! Convenience typedef for GINI_BINARY tree type. - typedef HoeffdingTree GiniBinaryTreeType; - //! Convenience typedef for INFO_HOEFFDING tree type. - typedef HoeffdingTree InfoHoeffdingTreeType; - //! Convenience typedef for INFO_BINARY tree type. - typedef HoeffdingTree InfoBinaryTreeType; - - /** - * Construct the Hoeffding tree model, but don't initialize any tree. - * - * Be sure to call Train() before doing anything with the model! - * - * @param type Type of tree that will be used. - */ - HoeffdingTreeModel(const TreeType& type = GINI_HOEFFDING); - - /** - * Copy the Hoeffding tree model from the given other model. - * - * @param other Hoeffding tree model to copy. - */ - HoeffdingTreeModel(const HoeffdingTreeModel& other); - - /** - * Move the Hoeffding tree model from the given other model. - * - * @param other Hoeffding tree model to move. - */ - HoeffdingTreeModel(HoeffdingTreeModel&& other); - - /** - * Copy the Hoeffding tree model from the given other model. - * - * @param other Hoeffding tree model to copy. - */ - HoeffdingTreeModel& operator=(const HoeffdingTreeModel& other); - - /** - * Move the Hoeffding tree model from the given other model. - * - * @param other Hoeffding tree model to move. - */ - HoeffdingTreeModel& operator=(HoeffdingTreeModel&& other); - - /** - * Clean up the given model. - */ - ~HoeffdingTreeModel(); - - /** - * Train the model on the given dataset with the given labels. This method - * just passes to the appropriate HoeffdingTree<...> constructor, and will - * train with one pass over the dataset. - * - * @param dataset Dataset to train on. - * @param datasetInfo Information about dimensions of dataset. - * @param labels Labels for training set. - * @param numClasses Number of classes in dataset. - * @param batchTraining Whether or not to train in batch. - * @param successProbability Probability of success required in Hoeffding - * bound before a split can happen. - * @param maxSamples Maximum number of samples before a split is forced. - * @param checkInterval Number of samples required before each split check. - * @param minSamples If the node has seen this many points or fewer, no split - * will be allowed. - * @param bins Number of bins, for Hoeffding numeric split. - * @param observationsBeforeBinning Number of observations before binning, for - * Hoeffding numeric split. - */ - void BuildModel(const arma::mat& dataset, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const bool batchTraining, - const double successProbability, - const size_t maxSamples, - const size_t checkInterval, - const size_t minSamples, - const size_t bins, - const size_t observationsBeforeBinning); - - /** - * Train in streaming mode on the given dataset. This takes one pass. Be - * sure that BuildModel() has been called first! - * - * @param dataset Dataset to train on. - * @param labels Labels for training set. - * @param batchTraining Whether or not to train in batch. - */ - void Train(const arma::mat& dataset, - const arma::Row& labels, - const bool batchTraining); - - /** - * Using the model, classify the given test points. Be sure that BuildModel() - * has been called first! - * - * @param dataset Dataset to classify. - * @param predictions Vector to store predictions for test points in. - */ - void Classify(const arma::mat& dataset, - arma::Row& predictions) const; - - /** - * Using the model, classify the given test points, returning class - * probabilities. - * - * @param dataset Dataset to classify. - * @param predictions Vector to store predictions for test points in. - * @param probabilities Vector to store probabilities for test points in. - */ - void Classify(const arma::mat& dataset, - arma::Row& predictions, - arma::rowvec& probabilities) const; - - /** - * Get the number of nodes in the tree. - */ - size_t NumNodes() const; - - /** - * Serialize the model. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - // Clear memory if needed. - if (Archive::is_loading::value) - { - delete giniHoeffdingTree; - delete giniBinaryTree; - delete infoHoeffdingTree; - delete infoBinaryTree; - - giniHoeffdingTree = NULL; - giniBinaryTree = NULL; - infoHoeffdingTree = NULL; - infoBinaryTree = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(type); - - // Fake dataset info may be needed to create fake trees. - data::DatasetInfo info; - if (type == GINI_HOEFFDING) - { - // Create fake tree to load into if needed. - if (Archive::is_loading::value) - giniHoeffdingTree = new GiniHoeffdingTreeType(info, 1, 1); - ar & BOOST_SERIALIZATION_NVP(giniHoeffdingTree); - } - else if (type == GINI_BINARY) - { - // Create fake tree to load into if needed. - if (Archive::is_loading::value) - giniBinaryTree = new GiniBinaryTreeType(info, 1, 1); - ar & BOOST_SERIALIZATION_NVP(giniBinaryTree); - } - else if (type == INFO_HOEFFDING) - { - // Create fake tree to load into if needed. - if (Archive::is_loading::value) - infoHoeffdingTree = new InfoHoeffdingTreeType(info, 1, 1); - ar & BOOST_SERIALIZATION_NVP(infoHoeffdingTree); - } - else if (type == INFO_BINARY) - { - // Create fake tree to load into if needed. - if (Archive::is_loading::value) - infoBinaryTree = new InfoBinaryTreeType(info, 1, 1); - ar & BOOST_SERIALIZATION_NVP(infoBinaryTree); - } - } - - private: - //! The type of tree we are using. - TreeType type; - - //! This is used if we are using the Gini impurity and the Hoeffding numeric - //! split. - GiniHoeffdingTreeType* giniHoeffdingTree; - - //! This is used if we are using the Gini impurity and the binary numeric - //! split. - GiniBinaryTreeType* giniBinaryTree; - - //! This is used if we are using the information gain and the Hoeffding - //! numeric split. - InfoHoeffdingTreeType* infoHoeffdingTree; - - //! This is used if we are using the information gain and the binary numeric - //! split. - InfoBinaryTreeType* infoBinaryTree; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/information_gain.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/information_gain.hpp deleted file mode 100644 index 880139410..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/information_gain.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file information_gain.hpp - * @author Ryan Curtin - * - * An implementation of information gain, which can be used in place of Gini - * impurity. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_INFORMATION_GAIN_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_INFORMATION_GAIN_HPP - -namespace mlpack { -namespace tree { - -class InformationGain -{ - public: - /** - * Given the sufficient statistics of a proposed split, calculate the - * information gain if that split was to be used. The 'counts' matrix should - * contain the number of points in each class in each column, so the size of - * 'counts' is children x classes, where 'children' is the number of child - * nodes in the proposed split. - * - * @param counts Matrix of sufficient statistics. - */ - static double Evaluate(const arma::Mat& counts) - { - // Calculate the number of elements in the unsplit node and also in each - // proposed child. - size_t numElem = 0; - arma::vec splitCounts(counts.n_elem); - for (size_t i = 0; i < counts.n_cols; ++i) - { - splitCounts[i] = arma::accu(counts.col(i)); - numElem += splitCounts[i]; - } - - // Corner case: if there are no elements, the gain is zero. - if (numElem == 0) - return 0.0; - - arma::Col classCounts = arma::sum(counts, 1); - - // Calculate the gain of the unsplit node. - double gain = 0.0; - for (size_t i = 0; i < classCounts.n_elem; ++i) - { - const double f = ((double) classCounts[i] / (double) numElem); - if (f > 0.0) - gain -= f * std::log2(f); - } - - // Now calculate the impurity of the split nodes and subtract them from the - // overall gain. - for (size_t i = 0; i < counts.n_cols; ++i) - { - if (splitCounts[i] > 0) - { - double splitGain = 0.0; - for (size_t j = 0; j < counts.n_rows; ++j) - { - const double f = ((double) counts(j, i) / (double) splitCounts[i]); - if (f > 0.0) - splitGain += f * std::log2(f); - } - - gain += ((double) splitCounts[i] / (double) numElem) * splitGain; - } - } - - return gain; - } - - /** - * Return the range of the information gain for the given number of classes. - * (That is, the difference between the maximum possible value and the minimum - * possible value.) - */ - static double Range(const size_t numClasses) - { - // The best possible case gives an information gain of 0. The worst - // possible case is even distribution, which gives n * (1/n * log2(1/n)) = - // log2(1/n) = -log2(n). So, the range is log2(n). - return std::log2(numClasses); - } -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/numeric_split_info.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/numeric_split_info.hpp deleted file mode 100644 index 001fd3c90..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/numeric_split_info.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file numeric_split_info.hpp - * @author Ryan Curtin - * - * After a numeric split has been made, this holds information on the split. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_NUMERIC_SPLIT_INFO_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_NUMERIC_SPLIT_INFO_HPP - -#include - -namespace mlpack { -namespace tree { - -template -class NumericSplitInfo -{ - public: - NumericSplitInfo() { /* Nothing to do. */ } - NumericSplitInfo(const arma::Col& splitPoints) : - splitPoints(splitPoints) { /* Nothing to do. */ } - - template - size_t CalculateDirection(const eT& value) const - { - // What bin does the point fall into? - size_t bin = 0; - while (bin < splitPoints.n_elem && value > splitPoints[bin]) - ++bin; - - return bin; - } - - //! Serialize the split (save/load the split points). - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(splitPoints); - } - - private: - arma::Col splitPoints; -}; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/typedef.hpp b/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/typedef.hpp deleted file mode 100644 index 3069190df..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/hoeffding_trees/typedef.hpp +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @file typedef.hpp - * @author Ryan Curtin - * - * Useful typedefs. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_HOEFFDING_TREES_TYPEDEF_HPP -#define MLPACK_METHODS_HOEFFDING_TREES_TYPEDEF_HPP - -#include "streaming_decision_tree.hpp" -#include "hoeffding_tree.hpp" - -namespace mlpack { -namespace tree { - -typedef StreamingDecisionTree> HoeffdingTreeType; - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_pca.hpp b/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_pca.hpp deleted file mode 100644 index 60ef68e94..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_pca.hpp +++ /dev/null @@ -1,133 +0,0 @@ -/** - * @file kernel_pca.hpp - * @author Ajinkya Kale - * @author Marcus Edel - * - * Defines the KernelPCA class to perform Kernel Principal Components Analysis - * on the specified data set. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KERNEL_PCA_KERNEL_PCA_HPP -#define MLPACK_METHODS_KERNEL_PCA_KERNEL_PCA_HPP - -#include -#include - -namespace mlpack { -namespace kpca { - -/** - * This class performs kernel principal components analysis (Kernel PCA), for a - * given kernel. This is a standard machine learning technique and is - * well-documented on the Internet and in standard texts. It is often used as a - * dimensionality reduction technique, and can also be useful in mapping - * linearly inseparable classes of points to different spaces where they are - * linearly separable. - * - * The performance of the method is highly dependent on the kernel choice. - * There are numerous available kernels in the mlpack::kernel namespace (see - * files in mlpack/core/kernels/) and it is easy to write your own; see other - * implementations for examples. - */ -template < - typename KernelType, - typename KernelRule = NaiveKernelRule -> -class KernelPCA -{ - public: - /** - * Construct the KernelPCA object, optionally passing a kernel. Optionally, - * the transformed data can be centered about the origin; to do this, pass - * 'true' for centerTransformedData. This will take slightly longer (but not - * much). - * - * @param kernel Kernel to be used for computation. - * @param centerTransformedData Center transformed data. - */ - KernelPCA(const KernelType kernel = KernelType(), - const bool centerTransformedData = false); - - /** - * Apply Kernel Principal Components Analysis to the provided data set. - * - * @param data Data matrix. - * @param transformedData Matrix to output results into. - * @param eigval KPCA eigenvalues will be written to this vector. - * @param eigvec KPCA eigenvectors will be written to this matrix. - * @param newDimension New dimension for the dataset. - */ - void Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigval, - arma::mat& eigvec, - const size_t newDimension); - - /** - * Apply Kernel Principal Components Analysis to the provided data set. - * - * @param data Data matrix. - * @param transformedData Matrix to output results into. - * @param eigval KPCA eigenvalues will be written to this vector. - * @param eigvec KPCA eigenvectors will be written to this matrix. - */ - void Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigval, - arma::mat& eigvec); - - /** - * Apply Kernel Principal Component Analysis to the provided data set. - * - * @param data Data matrix. - * @param transformedData Matrix to output results into. - * @param eigval KPCA eigenvalues will be written to this vector. - */ - void Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigval); - - /** - * Apply dimensionality reduction using Kernel Principal Component Analysis - * to the provided data set. The data matrix will be modified in-place. Note - * that the dimension can be larger than the existing dimension because KPCA - * works on the kernel matrix, not the covariance matrix. This means the new - * dimension can be as large as the number of points (columns) in the dataset. - * Note that if you specify newDimension to be larger than the current - * dimension of the data (the number of rows), then it's not really - * "dimensionality reduction"... - * - * @param data Data matrix. - * @param newDimension New dimension for the dataset. - */ - void Apply(arma::mat& data, const size_t newDimension); - - //! Get the kernel. - const KernelType& Kernel() const { return kernel; } - //! Modify the kernel. - KernelType& Kernel() { return kernel; } - - //! Return whether or not the transformed data is centered. - bool CenterTransformedData() const { return centerTransformedData; } - //! Return whether or not the transformed data is centered. - bool& CenterTransformedData() { return centerTransformedData; } - - private: - //! The instantiated kernel. - KernelType kernel; - //! If true, the data will be scaled (by standard deviation) when Apply() is - //! run. - bool centerTransformedData; -}; // class KernelPCA - -} // namespace kpca -} // namespace mlpack - -// Include implementation. -#include "kernel_pca_impl.hpp" - -#endif // MLPACK_METHODS_KERNEL_PCA_KERNEL_PCA_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_pca_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_pca_impl.hpp deleted file mode 100644 index 2d106aeb5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_pca_impl.hpp +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @file kernel_pca_impl.hpp - * @author Ajinkya Kale - * @author Marcus Edel - * - * Implementation of Kernel PCA class to perform Kernel Principal Components - * Analysis on the specified data set. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KERNEL_PCA_KERNEL_PCA_IMPL_HPP -#define MLPACK_METHODS_KERNEL_PCA_KERNEL_PCA_IMPL_HPP - -// In case it hasn't already been included. -#include "kernel_pca.hpp" - -namespace mlpack { -namespace kpca { - -template -KernelPCA::KernelPCA(const KernelType kernel, - const bool centerTransformedData) : - kernel(kernel), - centerTransformedData(centerTransformedData) -{ } - -//! Apply Kernel Principal Component Analysis to the provided data set. -template -void KernelPCA::Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigval, - arma::mat& eigvec, - const size_t newDimension) -{ - KernelRule::ApplyKernelMatrix(data, transformedData, eigval, - eigvec, newDimension, kernel); - - // Center the transformed data, if the user asked for it. - if (centerTransformedData) - { - arma::colvec transformedDataMean = arma::mean(transformedData, 1); - transformedData = transformedData - (transformedDataMean * - arma::ones(transformedData.n_cols)); - } -} - -//! Apply Kernel Principal Component Analysis to the provided data set. -template -void KernelPCA::Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigval, - arma::mat& eigvec) -{ - Apply(data, transformedData, eigval, eigvec, data.n_cols); -} - -//! Apply Kernel Principal Component Analysis to the provided data set. -template -void KernelPCA::Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigVal) -{ - arma::mat coeffs; - Apply(data, transformedData, eigVal, coeffs, data.n_cols); -} - -//! Use KPCA for dimensionality reduction. -template -void KernelPCA::Apply(arma::mat& data, - const size_t newDimension) -{ - arma::mat coeffs; - arma::vec eigVal; - - Apply(data, data, eigVal, coeffs, newDimension); - - if (newDimension < coeffs.n_rows && newDimension > 0) - data.shed_rows(newDimension, data.n_rows - 1); -} - -} // namespace kpca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_rules/naive_method.hpp b/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_rules/naive_method.hpp deleted file mode 100644 index 567ab51b8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_rules/naive_method.hpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @file naive_method.hpp - * @author Ajinkya Kale - * - * Use the naive method to construct the kernel matrix. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_KERNEL_PCA_NAIVE_METHOD_HPP -#define MLPACK_METHODS_KERNEL_PCA_NAIVE_METHOD_HPP - -#include - -namespace mlpack { -namespace kpca { - -template -class NaiveKernelRule -{ - public: - /** - * Construct the exact kernel matrix. - * - * @param data Input data points. - * @param transformedData Matrix to output results into. - * @param eigval KPCA eigenvalues will be written to this vector. - * @param eigvec KPCA eigenvectors will be written to this matrix. - * @param rank Rank to be used for matrix approximation. - * @param kernel Kernel to be used for computation. - */ - static void ApplyKernelMatrix(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigval, - arma::mat& eigvec, - const size_t /* unused */, - KernelType kernel = KernelType()) -{ - // Construct the kernel matrix. - arma::mat kernelMatrix; - // Resize the kernel matrix to the right size. - kernelMatrix.set_size(data.n_cols, data.n_cols); - - // Note that we only need to calculate the upper triangular part of the - // kernel matrix, since it is symmetric. This helps minimize the number of - // kernel evaluations. - for (size_t i = 0; i < data.n_cols; ++i) - { - for (size_t j = i; j < data.n_cols; ++j) - { - // Evaluate the kernel on these two points. - kernelMatrix(i, j) = kernel.Evaluate(data.unsafe_col(i), - data.unsafe_col(j)); - } - } - - // Copy to the lower triangular part of the matrix. - for (size_t i = 1; i < data.n_cols; ++i) - for (size_t j = 0; j < i; ++j) - kernelMatrix(i, j) = kernelMatrix(j, i); - - // For PCA the data has to be centered, even if the data is centered. But it - // is not guaranteed that the data, when mapped to the kernel space, is also - // centered. Since we actually never work in the feature space we cannot - // center the data. So, we perform a "psuedo-centering" using the kernel - // matrix. - arma::rowvec rowMean = arma::sum(kernelMatrix, 0) / kernelMatrix.n_cols; - kernelMatrix.each_col() -= arma::sum(kernelMatrix, 1) / kernelMatrix.n_cols; - kernelMatrix.each_row() -= rowMean; - kernelMatrix += arma::sum(rowMean) / kernelMatrix.n_cols; - - // Eigendecompose the centered kernel matrix. - arma::eig_sym(eigval, eigvec, kernelMatrix); - - // Swap the eigenvalues since they are ordered backwards (we need largest to - // smallest). - for (size_t i = 0; i < floor(eigval.n_elem / 2.0); ++i) - eigval.swap_rows(i, (eigval.n_elem - 1) - i); - - // Flip the coefficients to produce the same effect. - eigvec = arma::fliplr(eigvec); - - transformedData = eigvec.t() * kernelMatrix; - transformedData.each_col() /= arma::sqrt(eigval); -} -}; - -} // namespace kpca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_rules/nystroem_method.hpp b/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_rules/nystroem_method.hpp deleted file mode 100644 index 3ee0b0aed..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kernel_pca/kernel_rules/nystroem_method.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file nystroem_method.hpp - * @author Marcus Edel - * - * Use the Nystroem method for approximating a kernel matrix. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_KERNEL_PCA_NYSTROEM_METHOD_HPP -#define MLPACK_METHODS_KERNEL_PCA_NYSTROEM_METHOD_HPP - -#include -#include -#include - -namespace mlpack { -namespace kpca { - -template< - typename KernelType, - typename PointSelectionPolicy = kernel::KMeansSelection<> -> -class NystroemKernelRule -{ - public: - /** - * Construct the kernel matrix approximation using the nystroem method. - * - * @param data Input data points. - * @param transformedData Matrix to output results into. - * @param eigval KPCA eigenvalues will be written to this vector. - * @param eigvec KPCA eigenvectors will be written to this matrix. - * @param rank Rank to be used for matrix approximation. - * @param kernel Kernel to be used for computation. - */ - static void ApplyKernelMatrix(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigval, - arma::mat& eigvec, - const size_t rank, - KernelType kernel = KernelType()) - { - arma::mat G, v; - kernel::NystroemMethod nm(data, kernel, - rank); - nm.Apply(G); - transformedData = G.t() * G; - - // Center the reconstructed approximation. - math::Center(transformedData, transformedData); - - // For PCA the data has to be centered, even if the data is centered. But - // it is not guaranteed that the data, when mapped to the kernel space, is - // also centered. Since we actually never work in the feature space we - // cannot center the data. So, we perform a "psuedo-centering" using the - // kernel matrix. - arma::colvec colMean = arma::sum(G, 1) / G.n_rows; - G.each_row() -= arma::sum(G, 0) / G.n_rows; - G.each_col() -= colMean; - G += arma::sum(colMean) / G.n_rows; - - // Eigendecompose the centered kernel matrix. - arma::eig_sym(eigval, eigvec, transformedData); - - // Swap the eigenvalues since they are ordered backwards (we need largest - // to smallest). - for (size_t i = 0; i < floor(eigval.n_elem / 2.0); ++i) - eigval.swap_rows(i, (eigval.n_elem - 1) - i); - - // Flip the coefficients to produce the same effect. - eigvec = arma::fliplr(eigvec); - - transformedData = eigvec.t() * G.t(); - } -}; - -} // namespace kpca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/allow_empty_clusters.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/allow_empty_clusters.hpp deleted file mode 100644 index 1b8d91330..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/allow_empty_clusters.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @file allow_empty_clusters.hpp - * @author Ryan Curtin - * - * This very simple policy is used when K-Means is allowed to return empty - * clusters. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_ALLOW_EMPTY_CLUSTERS_HPP -#define MLPACK_METHODS_KMEANS_ALLOW_EMPTY_CLUSTERS_HPP - -#include - -namespace mlpack { -namespace kmeans { - -/** - * Policy which allows K-Means to create empty clusters without any error being - * reported. - */ -class AllowEmptyClusters -{ - public: - //! Default constructor required by EmptyClusterPolicy policy. - AllowEmptyClusters() { } - - /** - * This function allows empty clusters to persist simply by leaving the empty - * cluster in its last position. - * - * @tparam MatType Type of data (arma::mat or arma::spmat). - * @param data Dataset on which clustering is being performed. - * @param emptyCluster Index of cluster which is empty. - * @param oldCentroids Centroids of each cluster (one per column) at the start - * of the iteration. - * @param newCentroids Centroids of each cluster (one per column) at the end - * of the iteration. - * @param clusterCounts Number of points in each cluster. - * @param assignments Cluster assignments of each point. - * @param iteration Number of iteration. - * - * @return Number of points changed (0). - */ - template - static inline force_inline void EmptyCluster( - const MatType& /* data */, - const size_t emptyCluster, - const arma::mat& oldCentroids, - arma::mat& newCentroids, - arma::Col& /* clusterCounts */, - MetricType& /* metric */, - const size_t /* iteration */) - { - // Take the last iteration's centroid. - newCentroids.col(emptyCluster) = oldCentroids.col(emptyCluster); - } - - //! Serialize the empty cluster policy (nothing to do). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans.hpp deleted file mode 100644 index 3ad089e3a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans.hpp +++ /dev/null @@ -1,177 +0,0 @@ -/** - * @file dtnn_kmeans.hpp - * @author Ryan Curtin - * - * An implementation of a Lloyd iteration which uses dual-tree nearest neighbor - * search as a black box. The conditions under which this will perform best are - * probably limited to the case where k is close to the number of points in the - * dataset, and the number of iterations of the k-means algorithm will be few. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_HPP -#define MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_HPP - -#include -#include -#include - -#include "dual_tree_kmeans_statistic.hpp" - -namespace mlpack { -namespace kmeans { - -/** - * An algorithm for an exact Lloyd iteration which simply uses dual-tree - * nearest-neighbor search to find the nearest centroid for each point in the - * dataset. The conditions under which this will perform best are probably - * limited to the case where k is close to the number of points in the dataset, - * and the number of iterations of the k-means algorithm will be few. - */ -template< - typename MetricType, - typename MatType, - template - class TreeType = tree::KDTree> -class DualTreeKMeans -{ - public: - //! Convenience typedef. - typedef TreeType Tree; - - template - using NNSTreeType = - TreeType; - - /** - * Construct the DualTreeKMeans object, which will construct a tree on the - * points. - */ - DualTreeKMeans(const MatType& dataset, MetricType& metric); - - /** - * Delete the tree constructed by the DualTreeKMeans object. - */ - ~DualTreeKMeans(); - - /** - * Run a single iteration of the dual-tree nearest neighbor algorithm for - * k-means, updating the given centroids into the newCentroids matrix. - * - * @param centroids Current cluster centroids. - * @param newCentroids New cluster centroids. - * @param counts Current counts, to be overwritten with new counts. - */ - double Iterate(const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts); - - //! Return the number of distance calculations. - size_t DistanceCalculations() const { return distanceCalculations; } - //! Modify the number of distance calculations. - size_t& DistanceCalculations() { return distanceCalculations; } - - private: - //! The original dataset reference. - const MatType& datasetOrig; // Maybe not necessary. - //! The tree built on the points. - Tree* tree; - //! The dataset we are using. - const MatType& dataset; - //! The metric. - MetricType metric; - - //! Track distance calculations. - size_t distanceCalculations; - //! Track iteration number. - size_t iteration; - - //! Upper bounds on nearest centroid. - arma::vec upperBounds; - //! Lower bounds on second closest cluster distance for each point. - arma::vec lowerBounds; - //! Indicator of whether or not the point is pruned. - std::vector prunedPoints; - - arma::Row assignments; - - std::vector visited; // Was the point visited this iteration? - - arma::mat lastIterationCentroids; // For sanity checks. - - arma::vec clusterDistances; // The amount the clusters moved last iteration. - - arma::mat interclusterDistances; // Static storage for intercluster distances. - - //! Update the bounds in the tree before the next iteration. - //! centroids is the current (not yet searched) centroids. - void UpdateTree(Tree& node, - const arma::mat& centroids, - const double parentUpperBound = 0.0, - const double adjustedParentUpperBound = DBL_MAX, - const double parentLowerBound = DBL_MAX, - const double adjustedParentLowerBound = 0.0); - - //! Extract the centroids of the clusters. - void ExtractCentroids(Tree& node, - arma::mat& newCentroids, - arma::Col& newCounts, - const arma::mat& centroids); - - void CoalesceTree(Tree& node, const size_t child = 0); - void DecoalesceTree(Tree& node); -}; - -//! Utility function for hiding children. This actually does something, and is -//! called if the tree is not a binary tree. -template -void HideChild(TreeType& node, - const size_t child, - const typename std::enable_if_t< - !tree::TreeTraits::BinaryTree>* junk = 0); - -//! Utility function for hiding children. This is called when the tree is a -//! binary tree, and does nothing, because we don't hide binary children in this -//! way. -template -void HideChild(TreeType& node, - const size_t child, - const typename std::enable_if_t< - tree::TreeTraits::BinaryTree>* junk = 0); - -//! Utility function for restoring children to a non-binary tree. -template -void RestoreChildren(TreeType& node, - const typename std::enable_if_t::BinaryTree>* junk = 0); - -//! Utility function for restoring children to a binary tree. -template -void RestoreChildren(TreeType& node, - const typename std::enable_if_t::BinaryTree>* junk = 0); - -//! A template typedef for the DualTreeKMeans algorithm with the default tree -//! type (a kd-tree). -template -using DefaultDualTreeKMeans = DualTreeKMeans; - -//! A template typedef for the DualTreeKMeans algorithm with the cover tree -//! type. -template -using CoverTreeDualTreeKMeans = DualTreeKMeans; - -} // namespace kmeans -} // namespace mlpack - -#include "dual_tree_kmeans_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_impl.hpp deleted file mode 100644 index 66b0e6519..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_impl.hpp +++ /dev/null @@ -1,690 +0,0 @@ -/** - * @file dtnn_kmeans_impl.hpp - * @author Ryan Curtin - * - * An implementation of a Lloyd iteration which uses dual-tree nearest neighbor - * search as a black box. The conditions under which this will perform best are - * probably limited to the case where k is close to the number of points in the - * dataset, and the number of iterations of the k-means algorithm will be few. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_DTNN_KMEANS_IMPL_HPP -#define MLPACK_METHODS_KMEANS_DTNN_KMEANS_IMPL_HPP - -// In case it hasn't been included yet. -#include "dual_tree_kmeans.hpp" - -#include "dual_tree_kmeans_rules.hpp" - -namespace mlpack { -namespace kmeans { - -//! Call the tree constructor that does mapping. -template -TreeType* BuildTree( - MatType&& dataset, - std::vector& oldFromNew, - const typename std::enable_if< - tree::TreeTraits::RearrangesDataset>::type* = 0) -{ - // This is a hack. I know this will be BinarySpaceTree, so force a leaf size - // of two. - return new TreeType(std::forward(dataset), oldFromNew, 1); -} - -//! Call the tree constructor that does not do mapping. -template -TreeType* BuildTree( - MatType&& dataset, - const std::vector& /* oldFromNew */, - const typename std::enable_if< - !tree::TreeTraits::RearrangesDataset>::type* = 0) -{ - return new TreeType(std::forward(dataset)); -} - -template class TreeType> -DualTreeKMeans::DualTreeKMeans( - const MatType& dataset, - MetricType& metric) : - datasetOrig(dataset), - tree(new Tree(const_cast(dataset))), - dataset(tree->Dataset()), - metric(metric), - distanceCalculations(0), - iteration(0), - upperBounds(dataset.n_cols), - lowerBounds(dataset.n_cols), - prunedPoints(dataset.n_cols, false), // Fill with false. - assignments(dataset.n_cols), - visited(dataset.n_cols, false) // Fill with false. -{ - for (size_t i = 0; i < dataset.n_cols; ++i) - { - prunedPoints[i] = false; - visited[i] = false; - } - assignments.fill(size_t(-1)); - upperBounds.fill(DBL_MAX); - lowerBounds.fill(DBL_MAX); -} - -template class TreeType> -DualTreeKMeans::~DualTreeKMeans() -{ - if (tree) - delete tree; -} - -// Run a single iteration. -template class TreeType> -double DualTreeKMeans::Iterate( - const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts) -{ - // Build a tree on the centroids. This will make a copy if necessary, which - // is unfortunate, but I don't see a reasonable way around it. - std::vector oldFromNewCentroids; - Tree* centroidTree = BuildTree(centroids, oldFromNewCentroids); - - // Find the nearest neighbors of each of the clusters. We have to make our - // own TreeType, which is a little bit abuse, but we know for sure the - // TreeStatType we have will work. - neighbor::NeighborSearch nns(std::move(*centroidTree)); - - // Reset information in the tree, if we need to. - if (iteration > 0) - { - Timer::Start("knn"); - - // If the tree maps points, we need an intermediate result matrix. - arma::mat* interclusterDistancesTemp = - (tree::TreeTraits::RearrangesDataset) ? - new arma::mat(1, centroids.n_elem) : &interclusterDistances; - - arma::Mat closestClusters; // We don't actually care about these. - nns.Search(1, closestClusters, *interclusterDistancesTemp); - distanceCalculations += nns.BaseCases() + nns.Scores(); - - // We need to do the unmapping ourselves, if the tree does mapping. - if (tree::TreeTraits::RearrangesDataset) - { - for (size_t i = 0; i < interclusterDistances.n_elem; ++i) - interclusterDistances[oldFromNewCentroids[i]] = - (*interclusterDistancesTemp)[i]; - - delete interclusterDistancesTemp; - } - - Timer::Stop("knn"); - - UpdateTree(*tree, centroids); - - for (size_t i = 0; i < dataset.n_cols; ++i) - visited[i] = false; - } - else - { - // Not initialized yet. - clusterDistances.set_size(centroids.n_cols + 1); - interclusterDistances.set_size(1, centroids.n_cols); - } - - // We won't use the KNN class here because we have our own set of rules. - lastIterationCentroids = centroids; - typedef DualTreeKMeansRules RuleType; - RuleType rules(nns.ReferenceTree().Dataset(), dataset, assignments, - upperBounds, lowerBounds, metric, prunedPoints, oldFromNewCentroids, - visited); - - typename Tree::template BreadthFirstDualTreeTraverser - traverser(rules); - - Timer::Start("tree_mod"); - CoalesceTree(*tree); - Timer::Stop("tree_mod"); - - // Set the number of pruned centroids in the root to 0. - tree->Stat().Pruned() = 0; - traverser.Traverse(*tree, nns.ReferenceTree()); - distanceCalculations += rules.BaseCases() + rules.Scores(); - - Timer::Start("tree_mod"); - DecoalesceTree(*tree); - Timer::Stop("tree_mod"); - - // Now we need to extract the clusters. - newCentroids.zeros(centroids.n_rows, centroids.n_cols); - counts.zeros(centroids.n_cols); - ExtractCentroids(*tree, newCentroids, counts, centroids); - - // Now, calculate how far the clusters moved, after normalizing them. - double residual = 0.0; - clusterDistances[centroids.n_cols] = 0.0; - for (size_t c = 0; c < centroids.n_cols; ++c) - { - if (counts[c] == 0) - { - clusterDistances[c] = 0; - } - else - { - newCentroids.col(c) /= counts(c); - const double movement = metric.Evaluate(centroids.col(c), - newCentroids.col(c)); - clusterDistances[c] = movement; - residual += std::pow(movement, 2.0); - - if (movement > clusterDistances[centroids.n_cols]) - clusterDistances[centroids.n_cols] = movement; - } - } - distanceCalculations += centroids.n_cols; - - delete centroidTree; - - ++iteration; - - return std::sqrt(residual); -} - -template class TreeType> -void DualTreeKMeans::UpdateTree( - Tree& node, - const arma::mat& centroids, - const double parentUpperBound, - const double adjustedParentUpperBound, - const double parentLowerBound, - const double adjustedParentLowerBound) -{ - const bool prunedLastIteration = node.Stat().StaticPruned(); - node.Stat().StaticPruned() = false; - - // Grab information from the parent, if we can. - if (node.Parent() != NULL && - node.Parent()->Stat().Pruned() == centroids.n_cols && - node.Parent()->Stat().Owner() < centroids.n_cols) - { - // When taking bounds from the parent, note that the parent has already - // adjusted the bounds according to the cluster movements, so we need to - // de-adjust them since we'll adjust them again. Maybe there is a smarter - // way to do this... - node.Stat().UpperBound() = parentUpperBound; - node.Stat().LowerBound() = parentLowerBound; - node.Stat().Pruned() = node.Parent()->Stat().Pruned(); - node.Stat().Owner() = node.Parent()->Stat().Owner(); - } - const double unadjustedUpperBound = node.Stat().UpperBound(); - double adjustedUpperBound = adjustedParentUpperBound; - const double unadjustedLowerBound = node.Stat().LowerBound(); - double adjustedLowerBound = adjustedParentLowerBound; - - // Exhaustive lower bound check. Sigh. -/* - if (!prunedLastIteration) - { - for (size_t i = 0; i < node.NumDescendants(); ++i) - { - double closest = DBL_MAX; - double secondClosest = DBL_MAX; - arma::vec distances(centroids.n_cols); - for (size_t j = 0; j < centroids.n_cols; ++j) - { - const double dist = metric.Evaluate(dataset.col(node.Descendant(i)), - lastIterationCentroids.col(j)); - distances(j) = dist; - - if (dist < closest) - { - secondClosest = closest; - closest = dist; - } - else if (dist < secondClosest) - secondClosest = dist; - } - if (closest - 1e-10 > node.Stat().UpperBound()) - { - Log::Warn << distances.t(); - Log::Fatal << "Point " << node.Descendant(i) << " in " << node.Point(0) << -"c" << node.NumDescendants() << " invalidates upper bound " << -node.Stat().UpperBound() << " with closest cluster distance " << closest << -".\n"; - } - - if (node.NumChildren() == 0) - { - if (secondClosest + 1e-10 < std::min(lowerBounds[node.Descendant(i)], - node.Stat().LowerBound())) - { - Log::Warn << distances.t(); - Log::Warn << node; - Log::Fatal << "Point " << node.Descendant(i) << " in " << node.Point(0) << -"c" << node.NumDescendants() << " invalidates lower bound " << -std::min(lowerBounds[node.Descendant(i)], node.Stat().LowerBound()) << " (" << -lowerBounds[node.Descendant(i)] << ", " << node.Stat().LowerBound() << ") with " - << "second closest cluster distance " << secondClosest << ". cd " << -closest << "; pruned " << prunedPoints[node.Descendant(i)] << " visited " << -visited[node.Descendant(i)] << ".\n"; - } - } - } - } -*/ - - if ((node.Stat().Pruned() == centroids.n_cols) && - (node.Stat().Owner() < centroids.n_cols)) - { - // Adjust bounds. - node.Stat().UpperBound() += clusterDistances[node.Stat().Owner()]; - node.Stat().LowerBound() -= clusterDistances[centroids.n_cols]; - - if (adjustedParentUpperBound < node.Stat().UpperBound()) - node.Stat().UpperBound() = adjustedParentUpperBound; - - if (adjustedParentLowerBound > node.Stat().LowerBound()) - node.Stat().LowerBound() = adjustedParentLowerBound; - - // Try to use the inter-cluster distances to produce a better lower bound, - // if possible. - const double interclusterBound = interclusterDistances[node.Stat().Owner()] - / 2.0; - if (interclusterBound > node.Stat().LowerBound()) - { - node.Stat().LowerBound() = interclusterBound; - adjustedLowerBound = node.Stat().LowerBound(); - } - - if (node.Stat().UpperBound() < node.Stat().LowerBound()) - { - node.Stat().StaticPruned() = true; - } - else - { - // Tighten bound. - node.Stat().UpperBound() = - std::min(node.Stat().UpperBound(), - node.MaxDistance(centroids.col(node.Stat().Owner()))); - adjustedUpperBound = node.Stat().UpperBound(); - - ++distanceCalculations; - if (node.Stat().UpperBound() < node.Stat().LowerBound()) - node.Stat().StaticPruned() = true; - } - } - else - { - node.Stat().LowerBound() -= clusterDistances[centroids.n_cols]; - } - - // Recurse into children, and if all the children (and all the points) are - // pruned, then we can mark this as statically pruned. - bool allChildrenPruned = true; - for (size_t i = 0; i < node.NumChildren(); ++i) - { - UpdateTree(node.Child(i), centroids, unadjustedUpperBound, - adjustedUpperBound, unadjustedLowerBound, adjustedLowerBound); - if (!node.Child(i).Stat().StaticPruned()) - allChildrenPruned = false; - } - - bool allPointsPruned = true; - if (tree::TreeTraits::HasSelfChildren && node.NumChildren() > 0) - { - // If this tree type has self-children, then we have already adjusted the - // point bounds at a lower level, and we can determine if all of our points - // are pruned simply by seeing if all of the children's points are pruned. - // This particular line below additionally assumes that each node's points - // are all contained in its first child. This is valid for the cover tree, - // but maybe not others. - allPointsPruned = node.Child(0).Stat().StaticPruned(); - } - else if (!node.Stat().StaticPruned()) - { - // Try to prune individual points. - for (size_t i = 0; i < node.NumPoints(); ++i) - { - const size_t index = node.Point(i); - if (!visited[index] && !prunedPoints[index]) - { - upperBounds[index] = DBL_MAX; // Reset the bounds. - lowerBounds[index] = DBL_MAX; - allPointsPruned = false; - continue; // We didn't visit it and we don't have valid bounds -- so we - // can't prune it. - } - - if (prunedLastIteration) - { - // It was pruned last iteration but not this iteration. - // Set the bounds correctly. - upperBounds[index] += node.Stat().StaticUpperBoundMovement(); - lowerBounds[index] -= node.Stat().StaticLowerBoundMovement(); - } - - prunedPoints[index] = false; - const size_t owner = assignments[index]; - const double lowerBound = std::min(lowerBounds[index] - - clusterDistances[centroids.n_cols], node.Stat().LowerBound()); - const double pruningLowerBound = std::max(lowerBound, - interclusterDistances[owner] / 2.0); - if (upperBounds[index] + clusterDistances[owner] < pruningLowerBound) - { - prunedPoints[index] = true; - upperBounds[index] += clusterDistances[owner]; - lowerBounds[index] = pruningLowerBound; - } - else - { - // Attempt to tighten the bound. - upperBounds[index] = metric.Evaluate(dataset.col(index), - centroids.col(owner)); - ++distanceCalculations; - if (upperBounds[index] < pruningLowerBound) - { - prunedPoints[index] = true; - lowerBounds[index] = pruningLowerBound; - } - else - { - // Point cannot be pruned. We may have to inspect the point at a - // lower level, though. If that's the case, then we shouldn't - // invalidate the bounds we've got -- it will happen at the lower - // level. - if (!tree::TreeTraits::HasSelfChildren || - node.NumChildren() == 0) - { - upperBounds[index] = DBL_MAX; - lowerBounds[index] = DBL_MAX; - } - allPointsPruned = false; - } - } - } - } - -/* - if (node.Stat().StaticPruned() && !allChildrenPruned) - { - Log::Warn << node; - for (size_t i = 0; i < node.NumChildren(); ++i) - Log::Warn << "child " << i << ":\n" << node.Child(i); - Log::Fatal << "Node is statically pruned but not all its children are!\n"; - } -*/ - - // If all of the children and points are pruned, we may mark this node as - // pruned. - if (allChildrenPruned && allPointsPruned && !node.Stat().StaticPruned()) - { - node.Stat().StaticPruned() = true; - node.Stat().Owner() = centroids.n_cols; // Invalid owner. - node.Stat().Pruned() = size_t(-1); - } - - if (!node.Stat().StaticPruned()) - { - node.Stat().UpperBound() = DBL_MAX; - node.Stat().LowerBound() = DBL_MAX; - node.Stat().Pruned() = size_t(-1); - node.Stat().Owner() = centroids.n_cols; - node.Stat().StaticPruned() = false; - } - else // The node is now pruned. - { - if (prunedLastIteration) - { - // Track total movement while pruned. - node.Stat().StaticUpperBoundMovement() += - clusterDistances[node.Stat().Owner()]; - node.Stat().StaticLowerBoundMovement() += - clusterDistances[centroids.n_cols]; - } - else - { - node.Stat().StaticUpperBoundMovement() = - clusterDistances[node.Stat().Owner()]; - node.Stat().StaticLowerBoundMovement() = - clusterDistances[centroids.n_cols]; - } - } -} - -template class TreeType> -void DualTreeKMeans::ExtractCentroids( - Tree& node, - arma::mat& newCentroids, - arma::Col& newCounts, - const arma::mat& centroids) -{ - // Does this node own points? - if ((node.Stat().Pruned() == newCentroids.n_cols) || - (node.Stat().StaticPruned() && node.Stat().Owner() < newCentroids.n_cols)) - { - const size_t owner = node.Stat().Owner(); - newCentroids.col(owner) += node.Stat().Centroid() * node.NumDescendants(); - newCounts[owner] += node.NumDescendants(); - - // Perform the sanity check here. -/* - for (size_t i = 0; i < node.NumDescendants(); ++i) - { - const size_t index = node.Descendant(i); - arma::vec trueDistances(centroids.n_cols); - for (size_t j = 0; j < centroids.n_cols; ++j) - { - const double dist = metric.Evaluate(dataset.col(index), - centroids.col(j)); - trueDistances[j] = dist; - } - - arma::uword minIndex; - const double minDist = trueDistances.min(minIndex); - if (size_t(minIndex) != owner) - { - Log::Warn << node; - Log::Warn << trueDistances.t(); - Log::Fatal << "Point " << index << " of node " << node.Point(0) << "c" -<< node.NumDescendants() << " has true minimum cluster " << minIndex << " with " - << "distance " << minDist << " but node is pruned with upper bound " << -node.Stat().UpperBound() << " and owner " << node.Stat().Owner() << ".\n"; - } - } -*/ - } - else - { - // Check each point held in the node. - // Only check at leaves. - if (node.NumChildren() == 0) - { - for (size_t i = 0; i < node.NumPoints(); ++i) - { - const size_t owner = assignments[node.Point(i)]; - newCentroids.col(owner) += dataset.col(node.Point(i)); - ++newCounts[owner]; - -/* - const size_t index = node.Point(i); - arma::vec trueDistances(centroids.n_cols); - for (size_t j = 0; j < centroids.n_cols; ++j) - { - const double dist = metric.Evaluate(dataset.col(index), - centroids.col(j)); - trueDistances[j] = dist; - } - - arma::uword minIndex; - const double minDist = trueDistances.min(minIndex); - if (size_t(minIndex) != owner) - { - Log::Warn << node; - Log::Warn << trueDistances.t(); - Log::Fatal << "Point " << index << " of node " << node.Point(0) << "c" - << node.NumDescendants() << " has true minimum cluster " << minIndex << " with " - << "distance " << minDist << " but was assigned to cluster " << -assignments[node.Point(i)] << " with ub " << upperBounds[node.Point(i)] << -" and lb " << lowerBounds[node.Point(i)] << "; pp " << -(prunedPoints[node.Point(i)] ? "true" : "false") << ", visited " << -(visited[node.Point(i)] ? "true" -: "false") << ".\n"; - } -*/ - } - } - - // The node is not entirely owned by a cluster. Recurse. - for (size_t i = 0; i < node.NumChildren(); ++i) - ExtractCentroids(node.Child(i), newCentroids, newCounts, centroids); - } -} - -template class TreeType> -void DualTreeKMeans::CoalesceTree( - Tree& node, - const size_t child /* Which child are we? */) -{ - // If all children except one are pruned, we can hide this node. - if (node.NumChildren() == 0) - return; // We can't do anything. - - // If this is the root node, we can't coalesce. - if (node.Parent() != NULL) - { - // First, we should coalesce those nodes that aren't statically pruned. - for (size_t i = node.NumChildren() - 1; i > 0; --i) - { - if (node.Child(i).Stat().StaticPruned()) - HideChild(node, i); - else - CoalesceTree(node.Child(i), i); - } - - if (node.Child(0).Stat().StaticPruned()) - HideChild(node, 0); - else - CoalesceTree(node.Child(0), 0); - - // If we've pruned all but one child, then notPrunedIndex will contain the - // index of that child, and we can coalesce this node entirely. Note that - // the case where all children are statically pruned should not happen, - // because then this node should itself be statically pruned. - if (node.NumChildren() == 1) - { - node.Child(0).Parent() = node.Parent(); - node.Parent()->ChildPtr(child) = node.ChildPtr(0); - } - } - else - { - // We can't coalesce the root, so call the children individually and - // coalesce them. - for (size_t i = 0; i < node.NumChildren(); ++i) - CoalesceTree(node.Child(i), i); - } -} - -template class TreeType> -void DualTreeKMeans::DecoalesceTree(Tree& node) -{ - node.Parent() = (Tree*) node.Stat().TrueParent(); - RestoreChildren(node); - - for (size_t i = 0; i < node.NumChildren(); ++i) - DecoalesceTree(node.Child(i)); -} - -//! Utility function for hiding children in a non-binary tree. -template -void HideChild(TreeType& node, - const size_t child, - const typename std::enable_if_t< - !tree::TreeTraits::BinaryTree>*) -{ - // We're going to assume we have a Children() function open to us. If we - // don't, then this won't work, I guess... - node.Children().erase(node.Children().begin() + child); -} - -//! Utility function for hiding children in a binary tree. -template -void HideChild(TreeType& node, - const size_t child, - const typename std::enable_if_t< - tree::TreeTraits::BinaryTree>*) -{ - // If we're hiding the left child, then take the right child as the new left - // child. - if (child == 0) - { - node.ChildPtr(0) = node.ChildPtr(1); - node.ChildPtr(1) = NULL; - } - else - { - node.ChildPtr(1) = NULL; - } -} - -//! Utility function for restoring children in a non-binary tree. -template -void RestoreChildren(TreeType& node, - const typename std::enable_if_t< - !tree::TreeTraits::BinaryTree>*) -{ - node.Children().clear(); - node.Children().resize(node.Stat().NumTrueChildren()); - for (size_t i = 0; i < node.Stat().NumTrueChildren(); ++i) - node.Children()[i] = (TreeType*) node.Stat().TrueChild(i); -} - -//! Utility function for restoring children in a binary tree. -template -void RestoreChildren(TreeType& node, - const typename std::enable_if_t< - tree::TreeTraits::BinaryTree>*) -{ - if (node.Stat().NumTrueChildren() > 0) - { - node.ChildPtr(0) = (TreeType*) node.Stat().TrueChild(0); - node.ChildPtr(1) = (TreeType*) node.Stat().TrueChild(1); - } -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_rules.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_rules.hpp deleted file mode 100644 index 0a1f66c3b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_rules.hpp +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @file dtnn_rules.hpp - * @author Ryan Curtin - * - * A set of rules for the dual-tree k-means algorithm which uses dual-tree - * nearest neighbor search. For the most part we'll call out to - * NeighborSearchRules when we can. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_HPP -#define MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_HPP - -#include - -namespace mlpack { -namespace kmeans { - -template -class DualTreeKMeansRules -{ - public: - DualTreeKMeansRules(const arma::mat& centroids, - const arma::mat& dataset, - arma::Row& assignments, - arma::vec& upperBounds, - arma::vec& lowerBounds, - MetricType& metric, - const std::vector& prunedPoints, - const std::vector& oldFromNewCentroids, - std::vector& visited); - - double BaseCase(const size_t queryIndex, const size_t referenceIndex); - - double Score(const size_t queryIndex, TreeType& referenceNode); - double Score(TreeType& queryNode, TreeType& referenceNode); - double Rescore(const size_t queryIndex, - TreeType& referenceNode, - const double oldScore); - double Rescore(TreeType& queryNode, - TreeType& referenceNode, - const double oldScore); - - typedef typename tree::TraversalInfo TraversalInfoType; - - TraversalInfoType& TraversalInfo() { return traversalInfo; } - const TraversalInfoType& TraversalInfo() const { return traversalInfo; } - - size_t BaseCases() const { return baseCases; } - size_t& BaseCases() { return baseCases; } - - size_t Scores() const { return scores; } - size_t& Scores() { return scores; } - - private: - const arma::mat& centroids; - const arma::mat& dataset; - arma::Row& assignments; - arma::vec& upperBounds; - arma::vec& lowerBounds; - MetricType& metric; - - const std::vector& prunedPoints; - - const std::vector& oldFromNewCentroids; - - std::vector& visited; - - size_t baseCases; - size_t scores; - - TraversalInfoType traversalInfo; - - size_t lastQueryIndex; - size_t lastReferenceIndex; - size_t lastBaseCase; -}; - -} // namespace kmeans -} // namespace mlpack - -#include "dual_tree_kmeans_rules_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_rules_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_rules_impl.hpp deleted file mode 100644 index 8be77cc71..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_rules_impl.hpp +++ /dev/null @@ -1,339 +0,0 @@ -/** - * @file dtnn_rules_impl.hpp - * @author Ryan Curtin - * - * Implementation of DualTreeKMeansRules. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP -#define MLPACK_METHODS_KMEANS_DUAL_TREE_KMEANS_RULES_IMPL_HPP - -#include "dual_tree_kmeans_rules.hpp" - -namespace mlpack { -namespace kmeans { - -template -DualTreeKMeansRules::DualTreeKMeansRules( - const arma::mat& centroids, - const arma::mat& dataset, - arma::Row& assignments, - arma::vec& upperBounds, - arma::vec& lowerBounds, - MetricType& metric, - const std::vector& prunedPoints, - const std::vector& oldFromNewCentroids, - std::vector& visited) : - centroids(centroids), - dataset(dataset), - assignments(assignments), - upperBounds(upperBounds), - lowerBounds(lowerBounds), - metric(metric), - prunedPoints(prunedPoints), - oldFromNewCentroids(oldFromNewCentroids), - visited(visited), - baseCases(0), - scores(0), - lastQueryIndex(dataset.n_cols), - lastReferenceIndex(centroids.n_cols) -{ - // We must set the traversal info last query and reference node pointers to - // something that is both invalid (i.e. not a tree node) and not NULL. We'll - // use the this pointer. - traversalInfo.LastQueryNode() = (TreeType*) this; - traversalInfo.LastReferenceNode() = (TreeType*) this; -} - -template -inline force_inline double DualTreeKMeansRules::BaseCase( - const size_t queryIndex, - const size_t referenceIndex) -{ - if (prunedPoints[queryIndex]) - return 0.0; // Returning 0 shouldn't be a problem. - - // If we have already performed this base case, then do not perform it again. - if ((lastQueryIndex == queryIndex) && (lastReferenceIndex == referenceIndex)) - return lastBaseCase; - - // Any base cases imply that we will get a result. - visited[queryIndex] = true; - - // Calculate the distance. - ++baseCases; - const double distance = metric.Evaluate(dataset.col(queryIndex), - centroids.col(referenceIndex)); - - if (distance < upperBounds[queryIndex]) - { - lowerBounds[queryIndex] = upperBounds[queryIndex]; - upperBounds[queryIndex] = distance; - assignments[queryIndex] = (tree::TreeTraits::RearrangesDataset) ? - oldFromNewCentroids[referenceIndex] : referenceIndex; - } - else if (distance < lowerBounds[queryIndex]) - { - lowerBounds[queryIndex] = distance; - } - - // Cache this information for the next time BaseCase() is called. - lastQueryIndex = queryIndex; - lastReferenceIndex = referenceIndex; - lastBaseCase = distance; - - return distance; -} - -template -inline double DualTreeKMeansRules::Score( - const size_t queryIndex, - TreeType& /* referenceNode */) -{ - // If the query point has already been pruned, then don't recurse further. - if (prunedPoints[queryIndex]) - return DBL_MAX; - - // No pruning at this level; we're not likely to encounter a single query - // point with a reference node.. - return 0; -} - -template -inline double DualTreeKMeansRules::Score( - TreeType& queryNode, - TreeType& referenceNode) -{ - if (queryNode.Stat().StaticPruned() == true) - return DBL_MAX; - - // Pruned() for the root node must never be set to size_t(-1). - if (queryNode.Stat().Pruned() == size_t(-1)) - { - queryNode.Stat().Pruned() = queryNode.Parent()->Stat().Pruned(); - queryNode.Stat().LowerBound() = queryNode.Parent()->Stat().LowerBound(); - queryNode.Stat().Owner() = queryNode.Parent()->Stat().Owner(); - } - - if (queryNode.Stat().Pruned() == centroids.n_cols) - return DBL_MAX; - - // This looks a lot like the hackery used in NeighborSearchRules to avoid - // distance computations. We'll use the traversal info to see if a - // parent-child or parent-parent prune is possible. - const double queryParentDist = queryNode.ParentDistance(); - const double queryDescDist = queryNode.FurthestDescendantDistance(); - const double refParentDist = referenceNode.ParentDistance(); - const double refDescDist = referenceNode.FurthestDescendantDistance(); - const double lastScore = traversalInfo.LastScore(); - double adjustedScore; - double score = 0.0; - - // We want to set adjustedScore to be the distance between the centroid of the - // last query node and last reference node. We will do this by adjusting the - // last score. In some cases, we can just use the last base case. - if (tree::TreeTraits::FirstPointIsCentroid) - { - adjustedScore = traversalInfo.LastBaseCase(); - } - else if (lastScore == 0.0) // Nothing we can do here. - { - adjustedScore = 0.0; - } - else - { - // The last score is equal to the distance between the centroids minus the - // radii of the query and reference bounds along the axis of the line - // between the two centroids. In the best case, these radii are the - // furthest descendant distances, but that is not always true. It would - // take too long to calculate the exact radii, so we are forced to use - // MinimumBoundDistance() as a lower-bound approximation. - const double lastQueryDescDist = - traversalInfo.LastQueryNode()->MinimumBoundDistance(); - const double lastRefDescDist = - traversalInfo.LastReferenceNode()->MinimumBoundDistance(); - adjustedScore = lastScore + lastQueryDescDist; - adjustedScore = lastScore + lastRefDescDist; - } - - // Assemble an adjusted score. For nearest neighbor search, this adjusted - // score is a lower bound on MinDistance(queryNode, referenceNode) that is - // assembled without actually calculating MinDistance(). For furthest - // neighbor search, it is an upper bound on - // MaxDistance(queryNode, referenceNode). If the traversalInfo isn't usable - // then the node should not be pruned by this. - if (traversalInfo.LastQueryNode() == queryNode.Parent()) - { - const double queryAdjust = queryParentDist + queryDescDist; - adjustedScore -= queryAdjust; - } - else if (traversalInfo.LastQueryNode() == &queryNode) - { - adjustedScore -= queryDescDist; - } - else - { - // The last query node wasn't this query node or its parent. So we force - // the adjustedScore to be such that this combination can't be pruned here, - // because we don't really know anything about it. - - // It would be possible to modify this section to try and make a prune based - // on the query descendant distance and the distance between the query node - // and last traversal query node, but this case doesn't actually happen for - // kd-trees or cover trees. - adjustedScore = 0.0; - } - if (traversalInfo.LastReferenceNode() == referenceNode.Parent()) - { - const double refAdjust = refParentDist + refDescDist; - adjustedScore -= refAdjust; - } - else if (traversalInfo.LastReferenceNode() == &referenceNode) - { - adjustedScore -= refDescDist; - } - else - { - // The last reference node wasn't this reference node or its parent. So we - // force the adjustedScore to be such that this combination can't be pruned - // here, because we don't really know anything about it. - - // It would be possible to modify this section to try and make a prune based - // on the reference descendant distance and the distance between the - // reference node and last traversal reference node, but this case doesn't - // actually happen for kd-trees or cover trees. - adjustedScore = 0.0; - } - - // Now, check if we can prune. - if (adjustedScore > queryNode.Stat().UpperBound()) - { - if (!(tree::TreeTraits::FirstPointIsCentroid && score == 0.0)) - { - // There isn't any need to set the traversal information because no - // descendant combinations will be visited, and those are the only - // combinations that would depend on the traversal information. - if (adjustedScore < queryNode.Stat().LowerBound()) - { - // If this might affect the lower bound, make it more exact. - queryNode.Stat().LowerBound() = std::min(queryNode.Stat().LowerBound(), - queryNode.MinDistance(referenceNode)); - ++scores; - } - - queryNode.Stat().Pruned() += referenceNode.NumDescendants(); - score = DBL_MAX; - } - } - - if (score != DBL_MAX) - { - // Get minimum and maximum distances. - const math::Range distances = queryNode.RangeDistance(referenceNode); - - score = distances.Lo(); - ++scores; - if (distances.Lo() > queryNode.Stat().UpperBound()) - { - // The reference node can own no points in this query node. We may - // improve the lower bound on pruned nodes, though. - if (distances.Lo() < queryNode.Stat().LowerBound()) - queryNode.Stat().LowerBound() = distances.Lo(); - - // This assumes that reference clusters don't appear elsewhere in the - // tree. - queryNode.Stat().Pruned() += referenceNode.NumDescendants(); - score = DBL_MAX; - } - else if (distances.Hi() < queryNode.Stat().UpperBound()) - { - // Tighten upper bound. - const double tighterBound = - queryNode.MaxDistance(centroids.col(referenceNode.Descendant(0))); - ++scores; // Count extra distance calculation. - - if (tighterBound <= queryNode.Stat().UpperBound()) - { - // We can improve the best estimate. - queryNode.Stat().UpperBound() = tighterBound; - - // Remember that our upper bound does correspond to a cluster centroid, - // so it does correspond to a cluster. We'll mark the cluster as the - // owner, but note that the node is not truly owned unless - // Stat().Pruned() is centroids.n_cols. - queryNode.Stat().Owner() = - (tree::TreeTraits::RearrangesDataset) ? - oldFromNewCentroids[referenceNode.Descendant(0)] : - referenceNode.Descendant(0); - } - } - } - - // Is everything pruned? - - if (queryNode.Stat().Pruned() == centroids.n_cols - 1) - { - queryNode.Stat().Pruned() = centroids.n_cols; // Owner() is already set. - return DBL_MAX; - } - - - // Set traversal information. - traversalInfo.LastQueryNode() = &queryNode; - traversalInfo.LastReferenceNode() = &referenceNode; - traversalInfo.LastScore() = score; - - return score; -} - -template -inline double DualTreeKMeansRules::Rescore( - const size_t /* queryIndex */, - TreeType& /* referenceNode */, - const double oldScore) -{ - // No rescoring (for now). - return oldScore; -} - -template -inline double DualTreeKMeansRules::Rescore( - TreeType& queryNode, - TreeType& referenceNode, - const double oldScore) -{ - if (oldScore == DBL_MAX) - return DBL_MAX; // It's already pruned. - - // oldScore contains the minimum distance between queryNode and referenceNode. - // In the time since Score() has been called, the upper bound *may* have - // tightened. If it has tightened enough, we may prune this node now. - if (oldScore > queryNode.Stat().UpperBound()) - { - // We may still be able to improve the lower bound on pruned nodes. - if (oldScore < queryNode.Stat().LowerBound()) - queryNode.Stat().LowerBound() = oldScore; - - // This assumes that reference clusters don't appear elsewhere in the tree. - queryNode.Stat().Pruned() += referenceNode.NumDescendants(); - return DBL_MAX; - } - - // Also, check if everything has been pruned. - if (queryNode.Stat().Pruned() == centroids.n_cols - 1) - { - queryNode.Stat().Pruned() = centroids.n_cols; // Owner() is already set. - return DBL_MAX; - } - - return oldScore; -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_statistic.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_statistic.hpp deleted file mode 100644 index ac87b74d0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/dual_tree_kmeans_statistic.hpp +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @file dtnn_statistic.hpp - * @author Ryan Curtin - * - * Statistic for dual-tree nearest neighbor search based k-means clustering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_DTNN_STATISTIC_HPP -#define MLPACK_METHODS_KMEANS_DTNN_STATISTIC_HPP - -#include - -namespace mlpack { -namespace kmeans { - -class DualTreeKMeansStatistic : public - neighbor::NeighborSearchStat -{ - public: - DualTreeKMeansStatistic() : - neighbor::NeighborSearchStat(), - upperBound(DBL_MAX), - lowerBound(DBL_MAX), - owner(size_t(-1)), - pruned(size_t(-1)), - staticPruned(false), - staticUpperBoundMovement(0.0), - staticLowerBoundMovement(0.0), - centroid(), - trueParent(NULL) - { - // Nothing to do. - } - - template - DualTreeKMeansStatistic(TreeType& node) : - neighbor::NeighborSearchStat(), - upperBound(DBL_MAX), - lowerBound(DBL_MAX), - owner(size_t(-1)), - pruned(size_t(-1)), - staticPruned(false), - staticUpperBoundMovement(0.0), - staticLowerBoundMovement(0.0), - trueParent(node.Parent()) - { - // Empirically calculate the centroid. - centroid.zeros(node.Dataset().n_rows); - for (size_t i = 0; i < node.NumPoints(); ++i) - { - // Correct handling of cover tree: don't double-count the point which - // appears in the children. - if (tree::TreeTraits::HasSelfChildren && i == 0 && - node.NumChildren() > 0) - continue; - centroid += node.Dataset().col(node.Point(i)); - } - - for (size_t i = 0; i < node.NumChildren(); ++i) - centroid += node.Child(i).NumDescendants() * - node.Child(i).Stat().Centroid(); - - centroid /= node.NumDescendants(); - - // Set the true children correctly. - trueChildren.resize(node.NumChildren()); - for (size_t i = 0; i < node.NumChildren(); ++i) - trueChildren[i] = &node.Child(i); - } - - double UpperBound() const { return upperBound; } - double& UpperBound() { return upperBound; } - - double LowerBound() const { return lowerBound; } - double& LowerBound() { return lowerBound; } - - const arma::vec& Centroid() const { return centroid; } - arma::vec& Centroid() { return centroid; } - - size_t Owner() const { return owner; } - size_t& Owner() { return owner; } - - size_t Pruned() const { return pruned; } - size_t& Pruned() { return pruned; } - - bool StaticPruned() const { return staticPruned; } - bool& StaticPruned() { return staticPruned; } - - double StaticUpperBoundMovement() const { return staticUpperBoundMovement; } - double& StaticUpperBoundMovement() { return staticUpperBoundMovement; } - - double StaticLowerBoundMovement() const { return staticLowerBoundMovement; } - double& StaticLowerBoundMovement() { return staticLowerBoundMovement; } - - void* TrueParent() const { return trueParent; } - void*& TrueParent() { return trueParent; } - - void* TrueChild(const size_t i) const { return trueChildren[i]; } - void*& TrueChild(const size_t i) { return trueChildren[i]; } - - size_t NumTrueChildren() const { return trueChildren.size(); } - - private: - double upperBound; - double lowerBound; - size_t owner; - size_t pruned; - bool staticPruned; - double staticUpperBoundMovement; - double staticLowerBoundMovement; - arma::vec centroid; - void* trueParent; - std::vector trueChildren; -}; - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/elkan_kmeans.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/elkan_kmeans.hpp deleted file mode 100644 index a28ccd455..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/elkan_kmeans.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @file elkan_kmeans.hpp - * @author Ryan Curtin - * - * An implementation of Elkan's algorithm for exact Lloyd iterations. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_ELKAN_KMEANS_HPP -#define MLPACK_METHODS_KMEANS_ELKAN_KMEANS_HPP - -namespace mlpack { -namespace kmeans { - -template -class ElkanKMeans -{ - public: - /** - * Construct the ElkanKMeans object, which must store several sets of bounds. - */ - ElkanKMeans(const MatType& dataset, MetricType& metric); - - /** - * Run a single iteration of Elkan's algorithm, updating the given centroids - * into the newCentroids matrix. - * - * @param centroids Current cluster centroids. - * @param newCentroids New cluster centroids. - * @param counts Current counts, to be overwritten with new counts. - */ - double Iterate(const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts); - - size_t DistanceCalculations() const { return distanceCalculations; } - - private: - //! The dataset. - const MatType& dataset; - //! The instantiated metric. - MetricType& metric; - - //! Holds intra-cluster distances. - arma::mat clusterDistances; - //! Half the distance from a cluster to its nearest cluster (s(c)). - arma::vec minClusterDistances; - - //! Holds the index of the cluster that owns each point. - arma::Col assignments; - - //! Upper bounds on the distance between each point and its closest cluster. - arma::vec upperBounds; - //! Lower bounds on the distance between each point and each cluster. - arma::mat lowerBounds; - - //! Track distance calculations. - size_t distanceCalculations; -}; - -} // namespace kmeans -} // namespace mlpack - -// Include implementation. -#include "elkan_kmeans_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/elkan_kmeans_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/elkan_kmeans_impl.hpp deleted file mode 100644 index ffed2d87c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/elkan_kmeans_impl.hpp +++ /dev/null @@ -1,189 +0,0 @@ -/** - * @file elkan_kmeans_impl.hpp - * @author Ryan Curtin - * - * An implementation of Elkan's algorithm for exact Lloyd iterations. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_ELKAN_KMEANS_IMPL_HPP -#define MLPACK_METHODS_KMEANS_ELKAN_KMEANS_IMPL_HPP - -// In case it hasn't been included yet. -#include "elkan_kmeans.hpp" - -namespace mlpack { -namespace kmeans { - -template -ElkanKMeans::ElkanKMeans(const MatType& dataset, - MetricType& metric) : - dataset(dataset), - metric(metric), - distanceCalculations(0) -{ - // Nothing to do here. -} - -// Run a single iteration of Elkan's algorithm for Lloyd iterations. -template -double ElkanKMeans::Iterate(const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts) -{ - // Clear new centroids. - newCentroids.zeros(centroids.n_rows, centroids.n_cols); - counts.zeros(centroids.n_cols); - - // At the beginning of the iteration, we must compute the distances between - // all centers. This is O(k^2). - clusterDistances.set_size(centroids.n_cols, centroids.n_cols); - - // Self-distances are always 0, but we set them to DBL_MAX to avoid the self - // being the closest cluster centroid. - clusterDistances.diag().fill(DBL_MAX); - - // Initially set r(x) to true. - std::vector mustRecalculate(dataset.n_cols, true); - - // If this is the first iteration, we must reset all the bounds. - if (lowerBounds.n_rows != centroids.n_cols) - { - lowerBounds.set_size(centroids.n_cols, dataset.n_cols); - assignments.set_size(dataset.n_cols); - upperBounds.set_size(dataset.n_cols); - - lowerBounds.fill(0); - upperBounds.fill(DBL_MAX); - assignments.fill(0); - } - - // Step 1: for all centers, compute between-cluster distances. For all - // centers, compute s(c) = 1/2 min d(c, c'). - for (size_t i = 0; i < centroids.n_cols; ++i) - { - for (size_t j = i + 1; j < centroids.n_cols; ++j) - { - const double distance = metric.Evaluate(centroids.col(i), - centroids.col(j)); - distanceCalculations++; - clusterDistances(i, j) = distance; - clusterDistances(j, i) = distance; - } - } - - // Now find the closest cluster to each other cluster. We multiply by 0.5 so - // that this is equivalent to s(c) for each cluster c. - minClusterDistances = 0.5 * arma::min(clusterDistances).t(); - - // Now loop over all points, and see which ones need to be updated. - for (size_t i = 0; i < dataset.n_cols; ++i) - { - // Step 2: identify all points such that u(x) <= s(c(x)). - if (upperBounds(i) <= minClusterDistances(assignments[i])) - { - // No change needed. This point must still belong to that cluster. - counts(assignments[i])++; - newCentroids.col(assignments[i]) += arma::vec(dataset.col(i)); - continue; - } - else - { - for (size_t c = 0; c < centroids.n_cols; ++c) - { - // Step 3: for all remaining points x and centers c such that c != c(x), - // u(x) > l(x, c) and u(x) > 0.5 d(c(x), c)... - if (assignments[i] == c) - continue; // Pruned because this cluster is already the assignment. - - if (upperBounds(i) <= lowerBounds(c, i)) - continue; // Pruned by triangle inequality on lower bound. - - if (upperBounds(i) <= 0.5 * clusterDistances(assignments[i], c)) - continue; // Pruned by triangle inequality on cluster distances. - - // Step 3a: if r(x) then compute d(x, c(x)) and assign r(x) = false. - // Otherwise, d(x, c(x)) = u(x). - double dist; - if (mustRecalculate[i]) - { - mustRecalculate[i] = false; - dist = metric.Evaluate(dataset.col(i), centroids.col(assignments[i])); - lowerBounds(assignments[i], i) = dist; - upperBounds(i) = dist; - distanceCalculations++; - - // Check if we can prune again. - if (upperBounds(i) <= lowerBounds(c, i)) - continue; // Pruned by triangle inequality on lower bound. - - if (upperBounds(i) <= 0.5 * clusterDistances(assignments[i], c)) - continue; // Pruned by triangle inequality on cluster distances. - } - else - { - dist = upperBounds(i); // This is equivalent to d(x, c(x)). - } - - // Step 3b: if d(x, c(x)) > l(x, c) or d(x, c(x)) > 0.5 d(c(x), c)... - if (dist > lowerBounds(c, i) || - dist > 0.5 * clusterDistances(assignments[i], c)) - { - // Compute d(x, c). If d(x, c) < d(x, c(x)) then assign c(x) = c. - const double pointDist = metric.Evaluate(dataset.col(i), - centroids.col(c)); - lowerBounds(c, i) = pointDist; - distanceCalculations++; - if (pointDist < dist) - { - upperBounds(i) = pointDist; - assignments[i] = c; - } - } - } - } - - // At this point, we know the new cluster assignment. - // Step 4: for each center c, let m(c) be the mean of the points assigned to - // c. - newCentroids.col(assignments[i]) += arma::vec(dataset.col(i)); - counts[assignments[i]]++; - } - - // Now, normalize and calculate the distance each cluster has moved. - arma::vec moveDistances(centroids.n_cols); - double cNorm = 0.0; // Cluster movement for residual. - for (size_t c = 0; c < centroids.n_cols; ++c) - { - if (counts[c] > 0) - newCentroids.col(c) /= counts[c]; - - moveDistances(c) = metric.Evaluate(newCentroids.col(c), centroids.col(c)); - cNorm += std::pow(moveDistances(c), 2.0); - distanceCalculations++; - } - - for (size_t i = 0; i < dataset.n_cols; ++i) - { - // Step 5: for each point x and center c, assign - // l(x, c) = max { l(x, c) - d(c, m(c)), 0 }. - // But it doesn't actually matter if l(x, c) is positive. - for (size_t c = 0; c < centroids.n_cols; ++c) - lowerBounds(c, i) -= moveDistances(c); - - // Step 6: for each point x, assign - // u(x) = u(x) + d(m(c(x)), c(x)) - // r(x) = true (we are setting that at the start of every iteration). - upperBounds(i) += moveDistances(assignments[i]); - } - - return std::sqrt(cNorm); -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/hamerly_kmeans.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/hamerly_kmeans.hpp deleted file mode 100644 index 9dede8109..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/hamerly_kmeans.hpp +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @file hamerly_kmeans.hpp - * @author Ryan Curtin - * - * An implementation of Greg Hamerly's algorithm for k-means clustering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_HAMERLY_KMEANS_HPP -#define MLPACK_METHODS_KMEANS_HAMERLY_KMEANS_HPP - -namespace mlpack { -namespace kmeans { - -template -class HamerlyKMeans -{ - public: - /** - * Construct the HamerlyKMeans object, which must store several sets of - * bounds. - */ - HamerlyKMeans(const MatType& dataset, MetricType& metric); - - /** - * Run a single iteration of Hamerly's algorithm, updating the given centroids - * into the newCentroids matrix. - * - * @param centroids Current cluster centroids. - * @param newCentroids New cluster centroids. - * @param counts Current counts, to be overwritten with new counts. - */ - double Iterate(const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts); - - size_t DistanceCalculations() const { return distanceCalculations; } - - private: - //! The dataset. - const MatType& dataset; - //! The instantiated metric. - MetricType& metric; - - //! Minimum cluster distances from each cluster. - arma::vec minClusterDistances; - - //! Upper bounds for each point. - arma::vec upperBounds; - //! Lower bounds for each point. - arma::vec lowerBounds; - //! Assignments for each point. - arma::Col assignments; - - //! Track distance calculations. - size_t distanceCalculations; -}; - -} // namespace kmeans -} // namespace mlpack - -// Include implementation. -#include "hamerly_kmeans_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/hamerly_kmeans_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/hamerly_kmeans_impl.hpp deleted file mode 100644 index 7b867b16e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/hamerly_kmeans_impl.hpp +++ /dev/null @@ -1,178 +0,0 @@ -/** - * @file hamerly_kmeans_impl.hpp - * @author Ryan Curtin - * - * An implementation of Greg Hamerly's algorithm for k-means clustering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_HAMERLY_KMEANS_IMPL_HPP -#define MLPACK_METHODS_KMEANS_HAMERLY_KMEANS_IMPL_HPP - -// In case it hasn't been included yet. -#include "hamerly_kmeans.hpp" - -namespace mlpack { -namespace kmeans { - -template -HamerlyKMeans::HamerlyKMeans(const MatType& dataset, - MetricType& metric) : - dataset(dataset), - metric(metric), - distanceCalculations(0) -{ - // Nothing to do. -} - -template -double HamerlyKMeans::Iterate(const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts) -{ - size_t hamerlyPruned = 0; - - // If this is the first iteration, we need to set all the bounds. - if (minClusterDistances.n_elem != centroids.n_cols) - { - upperBounds.set_size(dataset.n_cols); - upperBounds.fill(DBL_MAX); - lowerBounds.zeros(dataset.n_cols); - assignments.zeros(dataset.n_cols); - minClusterDistances.set_size(centroids.n_cols); - } - - // Reset new centroids. - newCentroids.zeros(centroids.n_rows, centroids.n_cols); - counts.zeros(centroids.n_cols); - - // Calculate minimum intra-cluster distance for each cluster. - minClusterDistances.fill(DBL_MAX); - for (size_t i = 0; i < centroids.n_cols; ++i) - { - for (size_t j = i + 1; j < centroids.n_cols; ++j) - { - const double dist = metric.Evaluate(centroids.col(i), centroids.col(j)) / - 2.0; - ++distanceCalculations; - - // Update bounds, if this intra-cluster distance is smaller. - if (dist < minClusterDistances(i)) - minClusterDistances(i) = dist; - if (dist < minClusterDistances(j)) - minClusterDistances(j) = dist; - } - } - - for (size_t i = 0; i < dataset.n_cols; ++i) - { - const double m = std::max(minClusterDistances(assignments[i]), - lowerBounds(i)); - - // First bound test. - if (upperBounds(i) <= m) - { - ++hamerlyPruned; - newCentroids.col(assignments[i]) += dataset.col(i); - ++counts(assignments[i]); - continue; - } - - // Tighten upper bound. - upperBounds(i) = metric.Evaluate(dataset.col(i), - centroids.col(assignments[i])); - ++distanceCalculations; - - // Second bound test. - if (upperBounds(i) <= m) - { - newCentroids.col(assignments[i]) += dataset.col(i); - ++counts(assignments[i]); - continue; - } - - // The bounds failed. So test against all other clusters. - // This is Hamerly's Point-All-Ctrs() function from the paper. - // We have to reset the lower bound first. - lowerBounds(i) = DBL_MAX; - for (size_t c = 0; c < centroids.n_cols; ++c) - { - if (c == assignments[i]) - continue; - - const double dist = metric.Evaluate(dataset.col(i), centroids.col(c)); - - // Is this a better cluster? At this point, upperBounds[i] = d(i, c(i)). - if (dist < upperBounds(i)) - { - // lowerBounds holds the second closest cluster. - lowerBounds(i) = upperBounds(i); - upperBounds(i) = dist; - assignments[i] = c; - } - else if (dist < lowerBounds(i)) - { - // This is a closer second-closest cluster. - lowerBounds(i) = dist; - } - } - distanceCalculations += centroids.n_cols - 1; - - // Update new centroids. - newCentroids.col(assignments[i]) += dataset.col(i); - ++counts(assignments[i]); - } - - // Normalize centroids and calculate cluster movement (contains parts of - // Move-Centers() and Update-Bounds()). - double furthestMovement = 0.0; - double secondFurthestMovement = 0.0; - size_t furthestMovingCluster = 0; - arma::vec centroidMovements(centroids.n_cols); - double centroidMovement = 0.0; - for (size_t c = 0; c < centroids.n_cols; ++c) - { - if (counts(c) > 0) - newCentroids.col(c) /= counts(c); - - // Calculate movement. - const double movement = metric.Evaluate(centroids.col(c), - newCentroids.col(c)); - centroidMovements(c) = movement; - centroidMovement += std::pow(movement, 2.0); - ++distanceCalculations; - - if (movement > furthestMovement) - { - secondFurthestMovement = furthestMovement; - furthestMovement = movement; - furthestMovingCluster = c; - } - else if (movement > secondFurthestMovement) - { - secondFurthestMovement = movement; - } - } - - // Now update bounds (lines 3-8 of Update-Bounds()). - for (size_t i = 0; i < dataset.n_cols; ++i) - { - upperBounds(i) += centroidMovements(assignments[i]); - if (assignments[i] == furthestMovingCluster) - lowerBounds(i) -= secondFurthestMovement; - else - lowerBounds(i) -= furthestMovement; - } - - Log::Info << "Hamerly prunes: " << hamerlyPruned << ".\n"; - - return std::sqrt(centroidMovement); -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/kill_empty_clusters.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/kill_empty_clusters.hpp deleted file mode 100644 index ba64e7452..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/kill_empty_clusters.hpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file allow_empty_clusters.hpp - * @author Ryan Curtin - * - * This very simple policy is used when K-Means is allowed to return empty - * clusters. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef __MLPACK_METHODS_KMEANS_KILL_EMPTY_CLUSTERS_HPP -#define __MLPACK_METHODS_KMEANS_KILL_EMPTY_CLUSTERS_HPP - -#include - -namespace mlpack { -namespace kmeans { - -/** - * Policy which allows K-Means to "kill" empty clusters without any error being - * reported. This means the centroids will be filled with DBL_MAX. - */ -class KillEmptyClusters -{ - public: - //! Default constructor required by EmptyClusterPolicy policy. - KillEmptyClusters() { } - - /** - * This function sets an empty cluster found during k-means to all DBL_MAX - * (i.e. an invalid "dead" cluster). - * - * @tparam MatType Type of data (arma::mat or arma::spmat). - * @param data Dataset on which clustering is being performed. - * @param emptyCluster Index of cluster which is empty. - * @param oldCentroids Centroids of each cluster (one per column) at the start - * of the iteration. - * @param newCentroids Centroids of each cluster (one per column) at the end - * of the iteration. - * @param clusterCounts Number of points in each cluster. - * @param assignments Cluster assignments of each point. - * @param iteration Number of iteration. - * - * @return Number of points changed (0). - */ - template - static inline force_inline void EmptyCluster( - const MatType& /* data */, - const size_t emptyCluster, - const arma::mat& /* oldCentroids */, - arma::mat& newCentroids, - arma::Col& clusterCounts, - MetricType& /* metric */, - const size_t /* iteration */) -{ - // Remove the empty cluster. - if (emptyCluster < newCentroids.n_cols) - { - newCentroids.shed_col(emptyCluster); - clusterCounts.shed_row(emptyCluster); - } -} - - //! Serialize the empty cluster policy (nothing to do). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/kmeans.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/kmeans.hpp deleted file mode 100644 index d79d7fb64..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/kmeans.hpp +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @file kmeans.hpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * - * K-Means clustering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_KMEANS_HPP -#define MLPACK_METHODS_KMEANS_KMEANS_HPP - -#include - -#include -#include "sample_initialization.hpp" -#include "max_variance_new_cluster.hpp" -#include "naive_kmeans.hpp" - -#include - -namespace mlpack { -namespace kmeans /** K-Means clustering. */ { - -/** - * This class implements K-Means clustering, using a variety of possible - * implementations of Lloyd's algorithm. - * - * Four template parameters can (optionally) be supplied: the distance metric to - * use, the policy for how to find the initial partition of the data, the - * actions to be taken when an empty cluster is encountered, and the - * implementation of a single Lloyd step to use. - * - * A simple example of how to run K-Means clustering is shown below. - * - * @code - * extern arma::mat data; // Dataset we want to run K-Means on. - * arma::Row assignments; // Cluster assignments. - * arma::mat centroids; // Cluster centroids. - * - * KMeans<> k; // Default options. - * k.Cluster(data, 3, assignments, centroids); // 3 clusters. - * - * // Cluster using the Manhattan distance, 100 iterations maximum, saving only - * // the centroids. - * KMeans k(100); - * k.Cluster(data, 6, centroids); // 6 clusters. - * @endcode - * - * @tparam MetricType The distance metric to use for this KMeans; see - * metric::LMetric for an example. - * @tparam InitialPartitionPolicy Initial partitioning policy; must implement a - * default constructor and either 'void Cluster(const arma::mat&, const - * size_t, arma::Row&)' or 'void Cluster(const arma::mat&, const - * size_t, arma::mat&)'. - * @tparam EmptyClusterPolicy Policy for what to do on an empty cluster; must - * implement a default constructor and 'void EmptyCluster(const arma::mat& - * data, const size_t emptyCluster, const arma::mat& oldCentroids, - * arma::mat& newCentroids, arma::Col& counts, MetricType& metric, - * const size_t iteration)'. - * @tparam LloydStepType Implementation of single Lloyd step to use. - * - * @see RandomPartition, SampleInitialization, RefinedStart, AllowEmptyClusters, - * MaxVarianceNewCluster, NaiveKMeans, ElkanKMeans - */ -template class LloydStepType = NaiveKMeans, - typename MatType = arma::mat> -class KMeans -{ - public: - /** - * Create a K-Means object and (optionally) set the parameters which K-Means - * will be run with. - * - * @param maxIterations Maximum number of iterations allowed before giving up - * (0 is valid, but the algorithm may never terminate). - * @param metric Optional MetricType object; for when the metric has state - * it needs to store. - * @param partitioner Optional InitialPartitionPolicy object; for when a - * specially initialized partitioning policy is required. - * @param emptyClusterAction Optional EmptyClusterPolicy object; for when a - * specially initialized empty cluster policy is required. - */ - KMeans(const size_t maxIterations = 1000, - const MetricType metric = MetricType(), - const InitialPartitionPolicy partitioner = InitialPartitionPolicy(), - const EmptyClusterPolicy emptyClusterAction = EmptyClusterPolicy()); - - - /** - * Perform k-means clustering on the data, returning a list of cluster - * assignments. Optionally, the vector of assignments can be set to an - * initial guess of the cluster assignments; to do this, set initialGuess to - * true. - * - * @tparam MatType Type of matrix (arma::mat or arma::sp_mat). - * @param data Dataset to cluster. - * @param clusters Number of clusters to compute. - * @param assignments Vector to store cluster assignments in. - * @param initialGuess If true, then it is assumed that assignments has a list - * of initial cluster assignments. - */ - void Cluster(const MatType& data, - const size_t clusters, - arma::Row& assignments, - const bool initialGuess = false); - - /** - * Perform k-means clustering on the data, returning the centroids of each - * cluster in the centroids matrix. Optionally, the initial centroids can be - * specified by filling the centroids matrix with the initial centroids and - * specifying initialGuess = true. - * - * @tparam MatType Type of matrix (arma::mat or arma::sp_mat). - * @param data Dataset to cluster. - * @param clusters Number of clusters to compute. - * @param centroids Matrix in which centroids are stored. - * @param initialGuess If true, then it is assumed that centroids contains the - * initial cluster centroids. - */ - void Cluster(const MatType& data, - size_t clusters, - arma::mat& centroids, - const bool initialGuess = false); - - /** - * Perform k-means clustering on the data, returning a list of cluster - * assignments and also the centroids of each cluster. Optionally, the vector - * of assignments can be set to an initial guess of the cluster assignments; - * to do this, set initialAssignmentGuess to true. Another way to set initial - * cluster guesses is to fill the centroids matrix with the centroid guesses, - * and then set initialCentroidGuess to true. initialAssignmentGuess - * supersedes initialCentroidGuess, so if both are set to true, the - * assignments vector is used. - * - * @tparam MatType Type of matrix (arma::mat or arma::sp_mat). - * @param data Dataset to cluster. - * @param clusters Number of clusters to compute. - * @param assignments Vector to store cluster assignments in. - * @param centroids Matrix in which centroids are stored. - * @param initialAssignmentGuess If true, then it is assumed that assignments - * has a list of initial cluster assignments. - * @param initialCentroidGuess If true, then it is assumed that centroids - * contains the initial centroids of each cluster. - */ - void Cluster(const MatType& data, - const size_t clusters, - arma::Row& assignments, - arma::mat& centroids, - const bool initialAssignmentGuess = false, - const bool initialCentroidGuess = false); - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Set the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - //! Get the distance metric. - const MetricType& Metric() const { return metric; } - //! Modify the distance metric. - MetricType& Metric() { return metric; } - - //! Get the initial partitioning policy. - const InitialPartitionPolicy& Partitioner() const { return partitioner; } - //! Modify the initial partitioning policy. - InitialPartitionPolicy& Partitioner() { return partitioner; } - - //! Get the empty cluster policy. - const EmptyClusterPolicy& EmptyClusterAction() const - { return emptyClusterAction; } - //! Modify the empty cluster policy. - EmptyClusterPolicy& EmptyClusterAction() { return emptyClusterAction; } - - //! Serialize the k-means object. - template - void serialize(Archive& ar, const unsigned int version); - - private: - //! Maximum number of iterations before giving up. - size_t maxIterations; - //! Instantiated distance metric. - MetricType metric; - //! Instantiated initial partitioning policy. - InitialPartitionPolicy partitioner; - //! Instantiated empty cluster policy. - EmptyClusterPolicy emptyClusterAction; -}; - -} // namespace kmeans -} // namespace mlpack - -// Include implementation. -#include "kmeans_impl.hpp" - -#endif // MLPACK_METHODS_KMEANS_KMEANS_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/kmeans_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/kmeans_impl.hpp deleted file mode 100644 index cdbfccdc4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/kmeans_impl.hpp +++ /dev/null @@ -1,359 +0,0 @@ -/** - * @file kmeans_impl.hpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * @author Ryan Curtin - * - * Implementation for the K-means method for getting an initial point. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#include "kmeans.hpp" - -#include -#include - -namespace mlpack { -namespace kmeans { - -/** - * This gives us a GivesCentroids object that we can use to tell whether or not - * an InitialPartitionPolicy returns centroids or point assignments. - */ -HAS_MEM_FUNC(Cluster, GivesCentroidsCheck); - -/** - * 'value' is true if the InitialPartitionPolicy class has a member - * Cluster(const arma::mat& data, const size_t clusters, arma::mat& centroids). - */ -template -struct GivesCentroids -{ - static const bool value = - // Non-static version. - GivesCentroidsCheck::value || - // Static version. - GivesCentroidsCheck::value; -}; - -//! Call the initial partition policy, if it returns assignments. This returns -//! 'true' to indicate that assignments were given. -template -bool GetInitialAssignmentsOrCentroids( - InitialPartitionPolicy& ipp, - const MatType& data, - const size_t clusters, - arma::Row& assignments, - arma::mat& /* centroids */, - const typename std::enable_if_t< - !GivesCentroids::value>* = 0) -{ - ipp.Cluster(data, clusters, assignments); - - return true; -} - -//! Call the initial partition policy, if it returns centroids. This returns -//! 'false' to indicate that assignments were not given. -template -bool GetInitialAssignmentsOrCentroids( - InitialPartitionPolicy& ipp, - const MatType& data, - const size_t clusters, - arma::Row& /* assignments */, - arma::mat& centroids, - const typename std::enable_if_t< - GivesCentroids::value>* = 0) -{ - ipp.Cluster(data, clusters, centroids); - - return false; -} - -/** - * Construct the K-Means object. - */ -template class LloydStepType, - typename MatType> -KMeans< - MetricType, - InitialPartitionPolicy, - EmptyClusterPolicy, - LloydStepType, - MatType>:: -KMeans(const size_t maxIterations, - const MetricType metric, - const InitialPartitionPolicy partitioner, - const EmptyClusterPolicy emptyClusterAction) : - maxIterations(maxIterations), - metric(metric), - partitioner(partitioner), - emptyClusterAction(emptyClusterAction) -{ - // Nothing to do. -} - -/** - * Perform k-means clustering on the data, returning a list of cluster - * assignments. This just forward to the other function, which returns the - * centroids too. If this is properly inlined, there shouldn't be any - * performance penalty whatsoever. - */ -template class LloydStepType, - typename MatType> -inline void KMeans< - MetricType, - InitialPartitionPolicy, - EmptyClusterPolicy, - LloydStepType, - MatType>:: -Cluster(const MatType& data, - const size_t clusters, - arma::Row& assignments, - const bool initialGuess) -{ - arma::mat centroids(data.n_rows, clusters); - Cluster(data, clusters, assignments, centroids, initialGuess); -} - -/** - * Perform k-means clustering on the data, returning a list of cluster - * assignments and the centroids of each cluster. - */ -template class LloydStepType, - typename MatType> -void KMeans< - MetricType, - InitialPartitionPolicy, - EmptyClusterPolicy, - LloydStepType, - MatType>:: -Cluster(const MatType& data, - const size_t clusters, - arma::mat& centroids, - const bool initialGuess) -{ - // Make sure we have more points than clusters. - if (clusters > data.n_cols) - Log::Warn << "KMeans::Cluster(): more clusters requested than points given." - << std::endl; - else if (clusters == 0) - Log::Warn << "KMeans::Cluster(): zero clusters requested. This probably " - << "isn't going to work. Brace for crash." << std::endl; - - // Check validity of initial guess. - if (initialGuess) - { - if (centroids.n_cols != clusters) - Log::Fatal << "KMeans::Cluster(): wrong number of initial cluster " - << "centroids (" << centroids.n_cols << ", should be " << clusters - << ")!" << std::endl; - - if (centroids.n_rows != data.n_rows) - Log::Fatal << "KMeans::Cluster(): initial cluster centroids have wrong " - << " dimensionality (" << centroids.n_rows << ", should be " - << data.n_rows << ")!" << std::endl; - } - - // Use the partitioner to come up with the partition assignments and calculate - // the initial centroids. - if (!initialGuess) - { - // The GetInitialAssignmentsOrCentroids() function will call the appropriate - // function in the InitialPartitionPolicy to return either assignments or - // centroids. We prefer centroids, but if assignments are returned, then we - // have to calculate the initial centroids for the first iteration. - arma::Row assignments; - bool gotAssignments = GetInitialAssignmentsOrCentroids(partitioner, data, - clusters, assignments, centroids); - if (gotAssignments) - { - // The partitioner gives assignments, so we need to calculate centroids - // from those assignments. - arma::Row counts; - counts.zeros(clusters); - centroids.zeros(data.n_rows, clusters); - for (size_t i = 0; i < data.n_cols; ++i) - { - centroids.col(assignments[i]) += arma::vec(data.col(i)); - counts[assignments[i]]++; - } - - for (size_t i = 0; i < clusters; ++i) - if (counts[i] != 0) - centroids.col(i) /= counts[i]; - } - } - - // Counts of points in each cluster. - arma::Col counts(clusters); - - size_t iteration = 0; - - LloydStepType lloydStep(data, metric); - arma::mat centroidsOther; - double cNorm; - - do - { - // We have two centroid matrices. We don't want to copy anything, so, - // depending on the iteration number, we use a different centroid matrix... - if (iteration % 2 == 0) - cNorm = lloydStep.Iterate(centroids, centroidsOther, counts); - else - cNorm = lloydStep.Iterate(centroidsOther, centroids, counts); - - // If we are not allowing empty clusters, then check that all of our - // clusters have points. - for (size_t i = 0; i < counts.n_elem; i++) - { - if (counts[i] == 0) - { - Log::Info << "Cluster " << i << " is empty.\n"; - if (iteration % 2 == 0) - emptyClusterAction.EmptyCluster(data, i, centroids, centroidsOther, - counts, metric, iteration); - else - emptyClusterAction.EmptyCluster(data, i, centroidsOther, centroids, - counts, metric, iteration); - } - } - - iteration++; - Log::Info << "KMeans::Cluster(): iteration " << iteration << ", residual " - << cNorm << ".\n"; - if (std::isnan(cNorm) || std::isinf(cNorm)) - cNorm = 1e-4; // Keep iterating. - } while (cNorm > 1e-5 && iteration != maxIterations); - - // If we ended on an even iteration, then the centroids are in the - // centroidsOther matrix, and we need to steal its memory (steal_mem() avoids - // a copy if possible). - if ((iteration - 1) % 2 == 0) - centroids.steal_mem(centroidsOther); - - if (iteration != maxIterations) - { - Log::Info << "KMeans::Cluster(): converged after " << iteration - << " iterations." << std::endl; - } - else - { - Log::Info << "KMeans::Cluster(): terminated after limit of " << iteration - << " iterations." << std::endl; - } - Log::Info << lloydStep.DistanceCalculations() << " distance calculations." - << std::endl; -} - -/** - * Perform k-means clustering on the data, returning a list of cluster - * assignments and the centroids of each cluster. - */ -template class LloydStepType, - typename MatType> -void KMeans< - MetricType, - InitialPartitionPolicy, - EmptyClusterPolicy, - LloydStepType, - MatType>:: -Cluster(const MatType& data, - const size_t clusters, - arma::Row& assignments, - arma::mat& centroids, - const bool initialAssignmentGuess, - const bool initialCentroidGuess) -{ - // Now, the initial assignments. First determine if they are necessary. - if (initialAssignmentGuess) - { - if (assignments.n_elem != data.n_cols) - Log::Fatal << "KMeans::Cluster(): initial cluster assignments (length " - << assignments.n_elem << ") not the same size as the dataset (size " - << data.n_cols << ")!" << std::endl; - - // Calculate initial centroids. - arma::Row counts; - counts.zeros(clusters); - centroids.zeros(data.n_rows, clusters); - for (size_t i = 0; i < data.n_cols; ++i) - { - centroids.col(assignments[i]) += arma::vec(data.col(i)); - counts[assignments[i]]++; - } - - for (size_t i = 0; i < clusters; ++i) - if (counts[i] != 0) - centroids.col(i) /= counts[i]; - } - - Cluster(data, clusters, centroids, - initialAssignmentGuess || initialCentroidGuess); - - // Calculate final assignments in parallel over the entire dataset. - assignments.set_size(data.n_cols); - - #pragma omp parallel for - for (omp_size_t i = 0; i < (omp_size_t) data.n_cols; ++i) - { - // Find the closest centroid to this point. - double minDistance = std::numeric_limits::infinity(); - size_t closestCluster = centroids.n_cols; // Invalid value. - - for (size_t j = 0; j < centroids.n_cols; j++) - { - const double distance = metric.Evaluate(data.col(i), centroids.col(j)); - - if (distance < minDistance) - { - minDistance = distance; - closestCluster = j; - } - } - - Log::Assert(closestCluster != centroids.n_cols); - assignments[i] = closestCluster; - } -} - -template class LloydStepType, - typename MatType> -template -void KMeans::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(maxIterations); - ar & BOOST_SERIALIZATION_NVP(metric); - ar & BOOST_SERIALIZATION_NVP(partitioner); - ar & BOOST_SERIALIZATION_NVP(emptyClusterAction); -} - -} // namespace kmeans -} // namespace mlpack diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/max_variance_new_cluster.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/max_variance_new_cluster.hpp deleted file mode 100644 index 7395258b5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/max_variance_new_cluster.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @file max_variance_new_cluster.hpp - * @author Ryan Curtin - * - * An implementation of the EmptyClusterPolicy policy class for K-Means. When - * an empty cluster is detected, the point furthest from the centroid of the - * cluster with maximum variance is taken to be a new cluster. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_MAX_VARIANCE_NEW_CLUSTER_HPP -#define MLPACK_METHODS_KMEANS_MAX_VARIANCE_NEW_CLUSTER_HPP - -#include - -namespace mlpack { -namespace kmeans { - -/** - * When an empty cluster is detected, this class takes the point furthest from - * the centroid of the cluster with maximum variance as a new cluster. - */ -class MaxVarianceNewCluster -{ - public: - //! Default constructor required by EmptyClusterPolicy. - MaxVarianceNewCluster() : iteration(size_t(-1)) { } - - /** - * Take the point furthest from the centroid of the cluster with maximum - * variance to be a new cluster. - * - * @tparam MatType Type of data (arma::mat or arma::sp_mat). - * @param data Dataset on which clustering is being performed. - * @param emptyCluster Index of cluster which is empty. - * @param oldCentroids Centroids of each cluster (one per column), at the - * start of the iteration. - * @param newCentroids Centroids of each cluster (one per column), at the end - * of the iteration. This will be modified! - * @param clusterCounts Number of points in each cluster. - * @param assignments Cluster assignments of each point. - * - * @return Number of points changed. - */ - template - void EmptyCluster(const MatType& data, - const size_t emptyCluster, - const arma::mat& oldCentroids, - arma::mat& newCentroids, - arma::Col& clusterCounts, - MetricType& metric, - const size_t iteration); - - //! Serialize the object. - template - void serialize(Archive& ar, const unsigned int version); - - private: - //! Index of iteration for which variance is cached. - size_t iteration; - //! Cached variances for each cluster. - arma::vec variances; - //! Cached assignments for each point. - arma::Row assignments; - - //! Called when we are on a new iteration. - template - void Precalculate(const MatType& data, - const arma::mat& oldCentroids, - arma::Col& clusterCounts, - MetricType& metric); -}; - -} // namespace kmeans -} // namespace mlpack - -// Include implementation. -#include "max_variance_new_cluster_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/max_variance_new_cluster_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/max_variance_new_cluster_impl.hpp deleted file mode 100644 index ac17fb813..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/max_variance_new_cluster_impl.hpp +++ /dev/null @@ -1,163 +0,0 @@ -/** - * @file max_variance_new_cluster_impl.hpp - * @author Ryan Curtin - * - * Implementation of MaxVarianceNewCluster class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_MAX_VARIANCE_NEW_CLUSTER_IMPL_HPP -#define MLPACK_METHODS_KMEANS_MAX_VARIANCE_NEW_CLUSTER_IMPL_HPP - -// Just in case it has not been included. -#include "max_variance_new_cluster.hpp" - -namespace mlpack { -namespace kmeans { - -/** - * Take action about an empty cluster. - */ -template -void MaxVarianceNewCluster::EmptyCluster(const MatType& data, - const size_t emptyCluster, - const arma::mat& oldCentroids, - arma::mat& newCentroids, - arma::Col& clusterCounts, - MetricType& metric, - const size_t iteration) -{ - // If necessary, calculate the variances and assignments. - if (iteration != this->iteration || assignments.n_elem != data.n_cols) - Precalculate(data, oldCentroids, clusterCounts, metric); - this->iteration = iteration; - - // Now find the cluster with maximum variance. - arma::uword maxVarCluster = 0; - variances.max(maxVarCluster); - - // If the cluster with maximum variance has variance of 0, then we can't - // continue. All the points are the same. - if (variances[maxVarCluster] == 0.0) - return; - - // Now, inside this cluster, find the point which is furthest away. - size_t furthestPoint = data.n_cols; - double maxDistance = -DBL_MAX; - for (size_t i = 0; i < data.n_cols; ++i) - { - if (assignments[i] == maxVarCluster) - { - const double distance = std::pow(metric.Evaluate(data.col(i), - newCentroids.col(maxVarCluster)), 2.0); - - if (distance > maxDistance) - { - maxDistance = distance; - furthestPoint = i; - } - } - } - - // Take that point and add it to the empty cluster. - newCentroids.col(maxVarCluster) *= (double(clusterCounts[maxVarCluster]) / - double(clusterCounts[maxVarCluster] - 1)); - newCentroids.col(maxVarCluster) -= (1.0 / (clusterCounts[maxVarCluster] - - 1.0)) * arma::vec(data.col(furthestPoint)); - clusterCounts[maxVarCluster]--; - clusterCounts[emptyCluster]++; - newCentroids.col(emptyCluster) = arma::vec(data.col(furthestPoint)); - assignments[furthestPoint] = emptyCluster; - - // Modify the variances, as necessary. - variances[emptyCluster] = 0; - // One has already been subtracted from clusterCounts[maxVarCluster]. If - // EmptyCluster() is called again, we can't pull another point from - // maxVarCluster (we'd be making an empty cluster), so force a call to - // Precalculate() if EmptyCluster() is called again by changing - // this->iteration. - if (clusterCounts[maxVarCluster] <= 1) - { - variances[maxVarCluster] = 0; - --this->iteration; - } - else - { - variances[maxVarCluster] = (1.0 / clusterCounts[maxVarCluster]) * - ((clusterCounts[maxVarCluster] + 1) * variances[maxVarCluster] - - maxDistance); - } - - // Output some debugging information. - Log::Debug << "Point " << furthestPoint << " assigned to empty cluster " << - emptyCluster << ".\n"; -} - -//! Serialize the object. -template -void MaxVarianceNewCluster::serialize(Archive& /* ar */, - const unsigned int /* version */) -{ - // Serialization is useless here, because the only thing we store is - // precalculated quantities, and if we're serializing, our precalculations are - // likely to be useless when we deserialize (because the user will be running - // a different clustering, probably). So there is no need to store anything, - // and if we are loading, we just reset the assignments array so - // precalculation will happen next time EmptyCluster() is called. - if (Archive::is_loading::value) - assignments.set_size(0); -} - -template -void MaxVarianceNewCluster::Precalculate(const MatType& data, - const arma::mat& oldCentroids, - arma::Col& clusterCounts, - MetricType& metric) -{ - // We have to calculate the variances of each cluster and the assignments of - // each point. This is most easily done by iterating through the entire - // dataset. - variances.zeros(oldCentroids.n_cols); - assignments.set_size(data.n_cols); - - // Add the variance of each point's distance away from the cluster. I think - // this is the sensible thing to do. - for (size_t i = 0; i < data.n_cols; ++i) - { - // Find the closest centroid to this point. - double minDistance = std::numeric_limits::infinity(); - size_t closestCluster = oldCentroids.n_cols; // Invalid value. - - for (size_t j = 0; j < oldCentroids.n_cols; j++) - { - const double distance = metric.Evaluate(data.col(i), oldCentroids.col(j)); - - if (distance < minDistance) - { - minDistance = distance; - closestCluster = j; - } - } - - assignments[i] = closestCluster; - variances[closestCluster] += std::pow(metric.Evaluate(data.col(i), - oldCentroids.col(closestCluster)), 2.0); - } - - // Divide by the number of points in the cluster to produce the variance, - // unless the cluster is empty or contains only one point, in which case we - // set the variance to 0. - for (size_t i = 0; i < clusterCounts.n_elem; ++i) - if (clusterCounts[i] <= 1) - variances[i] = 0; - else - variances[i] /= clusterCounts[i]; -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/naive_kmeans.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/naive_kmeans.hpp deleted file mode 100644 index abca0bcee..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/naive_kmeans.hpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file naive_kmeans.hpp - * @author Ryan Curtin - * - * An implementation of a naively-implemented step of the Lloyd algorithm for - * k-means clustering, using OpenMP for parallelization over multiple threads. - * This may still be the best choice for small datasets or datasets with very - * high dimensionality. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_NAIVE_KMEANS_HPP -#define MLPACK_METHODS_KMEANS_NAIVE_KMEANS_HPP -#include - -namespace mlpack { -namespace kmeans { - -/** - * This is an implementation of a single iteration of Lloyd's algorithm for - * k-means. If your intention is to run the full k-means algorithm, you are - * looking for the mlpack::kmeans::KMeans class instead of this one. This class - * is used by KMeans as the actual implementation of the Lloyd iteration. - * - * @param MetricType Type of metric used with this implementation. - * @param MatType Matrix type (arma::mat or arma::sp_mat). - */ -template -class NaiveKMeans -{ - public: - /** - * Construct the NaiveKMeans object with the given dataset and metric. - * - * @param dataset Dataset. - * @param metric Instantiated metric. - */ - NaiveKMeans(const MatType& dataset, MetricType& metric); - - /** - * Run a single iteration of the Lloyd algorithm, updating the given centroids - * into the newCentroids matrix. If any cluster is empty (that is, if any - * cluster has no points assigned to it), then the centroid associated with - * that cluster may be filled with invalid data (it will be corrected later). - * - * @param centroids Current cluster centroids. - * @param newCentroids New cluster centroids. - * @param counts Number of points in each cluster at the end of the iteration. - */ - double Iterate(const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts); - - size_t DistanceCalculations() const { return distanceCalculations; } - - private: - //! The dataset. - const MatType& dataset; - //! The instantiated metric. - MetricType& metric; - - //! Number of distance calculations. - size_t distanceCalculations; -}; - -} // namespace kmeans -} // namespace mlpack - -// Include implementation. -#include "naive_kmeans_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/naive_kmeans_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/naive_kmeans_impl.hpp deleted file mode 100644 index d04ed48f8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/naive_kmeans_impl.hpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file naive_kmeans_impl.hpp - * @author Ryan Curtin - * @author Shikhar Bhardwaj - * - * An implementation of a naively-implemented step of the Lloyd algorithm for - * k-means clustering, using OpenMP for parallelization over multiple threads. - * This may still be the best choice for small datasets or datasets with very - * high dimensionality. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_NAIVE_KMEANS_IMPL_HPP -#define MLPACK_METHODS_KMEANS_NAIVE_KMEANS_IMPL_HPP - -// In case it hasn't been included yet. -#include "naive_kmeans.hpp" - -namespace mlpack { -namespace kmeans { - -template -NaiveKMeans::NaiveKMeans(const MatType& dataset, - MetricType& metric) : - dataset(dataset), - metric(metric), - distanceCalculations(0) -{ /* Nothing to do. */ } - -// Run a single iteration. -template -double NaiveKMeans::Iterate(const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts) -{ - newCentroids.zeros(centroids.n_rows, centroids.n_cols); - counts.zeros(centroids.n_cols); - - // Find the closest centroid to each point and update the new centroids. - // Computed in parallel over the complete dataset - #pragma omp parallel - { - // The current state of the K-means is private for each thread - arma::mat localCentroids(centroids.n_rows, centroids.n_cols, - arma::fill::zeros); - arma::Col localCounts(centroids.n_cols, arma::fill::zeros); - - #pragma omp for - for (omp_size_t i = 0; i < (omp_size_t) dataset.n_cols; ++i) - { - // Find the closest centroid to this point. - double minDistance = std::numeric_limits::infinity(); - size_t closestCluster = centroids.n_cols; // Invalid value. - - for (size_t j = 0; j < centroids.n_cols; j++) - { - const double distance = metric.Evaluate(dataset.col(i), - centroids.unsafe_col(j)); - if (distance < minDistance) - { - minDistance = distance; - closestCluster = j; - } - } - - Log::Assert(closestCluster != centroids.n_cols); - - // We now have the minimum distance centroid index. Update that centroid. - localCentroids.unsafe_col(closestCluster) += dataset.col(i); - localCounts(closestCluster)++; - } - // Combine calculated state from each thread - #pragma omp critical - { - newCentroids += localCentroids; - counts += localCounts; - } - } - - // Now normalize the centroid. - for (size_t i = 0; i < centroids.n_cols; ++i) - if (counts(i) != 0) - newCentroids.col(i) /= counts(i); - - distanceCalculations += centroids.n_cols * dataset.n_cols; - - // Calculate cluster distortion for this iteration. - double cNorm = 0.0; - for (size_t i = 0; i < centroids.n_cols; ++i) - { - cNorm += std::pow(metric.Evaluate(centroids.col(i), newCentroids.col(i)), - 2.0); - } - distanceCalculations += centroids.n_cols; - - return std::sqrt(cNorm); -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans.hpp deleted file mode 100644 index 67af38cbf..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @file pelleg_moore_kmeans.hpp - * @author Ryan Curtin - * - * An implementation of Pelleg-Moore's 'blacklist' algorithm for k-means - * clustering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_HPP -#define MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_HPP - -#include -#include "pelleg_moore_kmeans_statistic.hpp" - -namespace mlpack { -namespace kmeans { - -/** - * An implementation of Pelleg-Moore's 'blacklist' algorithm for k-means - * clustering. This algorithm builds a kd-tree on the data points and traverses - * it in order to determine the closest clusters to each point. - * - * For more information on the algorithm, see - * - * @code - * @inproceedings{pelleg1999accelerating, - * title={Accelerating exact k-means algorithms with geometric reasoning}, - * author={Pelleg, Dan and Moore, Andrew W.}, - * booktitle={Proceedings of the Fifth ACM SIGKDD International Conference - * on Knowledge Discovery and Data Mining (KDD '99)}, - * pages={277--281}, - * year={1999}, - * organization={ACM} - * } - * @endcode - */ -template -class PellegMooreKMeans -{ - public: - /** - * Construct the PellegMooreKMeans object, which must construct a tree. - */ - PellegMooreKMeans(const MatType& dataset, MetricType& metric); - - /** - * Delete the tree constructed by the PellegMooreKMeans object. - */ - ~PellegMooreKMeans(); - - /** - * Run a single iteration of the Pelleg-Moore blacklist algorithm, updating - * the given centroids into the newCentroids matrix. - * - * @param centroids Current cluster centroids. - * @param newCentroids New cluster centroids. - * @param counts Current counts, to be overwritten with new counts. - */ - double Iterate(const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts); - - //! Return the number of distance calculations. - size_t DistanceCalculations() const { return distanceCalculations; } - //! Modify the number of distance calculations. - size_t& DistanceCalculations() { return distanceCalculations; } - - //! Convenience typedef for the tree. - typedef tree::KDTree - TreeType; - - private: - //! The original dataset reference. - const MatType& datasetOrig; // Maybe not necessary. - //! The tree built on the points. - TreeType* tree; - //! The dataset we are using. - const MatType& dataset; - //! The metric. - MetricType& metric; - - //! Track distance calculations. - size_t distanceCalculations; -}; - -} // namespace kmeans -} // namespace mlpack - -#include "pelleg_moore_kmeans_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_impl.hpp deleted file mode 100644 index de5914f6a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_impl.hpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file pelleg_moore_kmeans_impl.hpp - * @author Ryan Curtin - * - * An implementation of Pelleg-Moore's 'blacklist' algorithm for k-means - * clustering. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_IMPL_HPP -#define MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_IMPL_HPP - -#include "pelleg_moore_kmeans.hpp" -#include "pelleg_moore_kmeans_rules.hpp" - -namespace mlpack { -namespace kmeans { - -template -PellegMooreKMeans::PellegMooreKMeans( - const MatType& dataset, - MetricType& metric) : - datasetOrig(dataset), - tree(new TreeType(const_cast(datasetOrig))), - dataset(tree->Dataset()), - metric(metric), - distanceCalculations(0) -{ - // Nothing to do. -} - -template -PellegMooreKMeans::~PellegMooreKMeans() -{ - if (tree) - delete tree; -} - -// Run a single iteration. -template -double PellegMooreKMeans::Iterate( - const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts) -{ - newCentroids.zeros(centroids.n_rows, centroids.n_cols); - counts.zeros(centroids.n_cols); - - // Create rules object. - typedef PellegMooreKMeansRules RulesType; - RulesType rules(dataset, centroids, newCentroids, counts, metric); - - // Use single-tree traverser. - typename TreeType::template SingleTreeTraverser traverser(rules); - - // Now, do a traversal with a fake query index (since the query index is - // irrelevant; we are checking each node with all clusters. - traverser.Traverse(0, *tree); - - distanceCalculations += rules.DistanceCalculations(); - - // Now, calculate how far the clusters moved, after normalizing them. - double residual = 0.0; - for (size_t c = 0; c < centroids.n_cols; ++c) - { - if (counts[c] > 0) - { - newCentroids.col(c) /= counts(c); - residual += std::pow(metric.Evaluate(centroids.col(c), - newCentroids.col(c)), 2.0); - } - } - distanceCalculations += centroids.n_cols; - - return std::sqrt(residual); -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_rules.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_rules.hpp deleted file mode 100644 index c3025995f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_rules.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file kmeans_rules.hpp - * @author Ryan Curtin - * - * Defines the pruning rules and base cases rules necessary to perform - * single-tree k-means clustering using the Pelleg-Moore fast k-means algorithm, - * which has been shoehorned to fit into the mlpack tree abstractions. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_RULES_HPP -#define MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_RULES_HPP - -namespace mlpack { -namespace kmeans { - -/** - * The rules class for the single-tree Pelleg-Moore kd-tree traversal for - * k-means clustering. Although TreeType is a free template parameter, this - * particular implementation is specialized to trees with hyper-rectangle bounds - * due to the pruning rule used to determine if one cluster dominates a node - * with respect to another cluster. - * - * Our implementation here abuses the single-tree algorithm abstractions a - * little bit. Instead of doing a traversal for a particular query point, in - * this case we consider all clusters at once---so the query point is entirely - * ignored during in BaseCase() and Score(). - */ -template -class PellegMooreKMeansRules -{ - public: - /** - * Create the PellegMooreKMeansRules object. - * - * @param dataset The dataset that the tree is built on. - * @param centroids The current centroids. - * @param newCentroids New centroids after this iteration (output). - * @param counts Current cluster counts, to be replaced with new cluster - * counts. - * @param metric Instantiated metric. - */ - PellegMooreKMeansRules(const typename TreeType::Mat& dataset, - const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts, - MetricType& metric); - - /** - * The BaseCase() function for this single-tree algorithm does nothing. - * Instead, point-to-cluster comparisons are handled as necessary in Score(). - * - * @param queryIndex Index of query point (fake, will be ignored). - * @param referenceIndex Index of reference point. - */ - double BaseCase(const size_t queryIndex, const size_t referenceIndex); - - /** - * Determine if a cluster can be pruned, and if not, perform point-to-cluster - * comparisons. The point-to-cluster comparisons are performed here and not - * in BaseCase() because of the complexity of managing the blacklist. - * - * @param queryIndex Index of query point (fake, will be ignored). - * @param referenceNode Node containing points in the dataset. - */ - double Score(const size_t queryIndex, TreeType& referenceNode); - - /** - * Rescore to determine if a node can be pruned. In this case, a node can - * never be pruned during rescoring, so this just returns oldScore. - * - * @param queryIndex Index of query point (fake, will be ignored). - * @param referenceNode Node containing points in the dataset. - * @param oldScore Resulting score from Score(). - */ - double Rescore(const size_t queryIndex, - TreeType& referenceNode, - const double oldScore); - - //! Get the number of distance calculations that have been performed. - size_t DistanceCalculations() const { return distanceCalculations; } - //! Modify the number of distance calculations that have been performed. - size_t& DistanceCalculations() { return distanceCalculations; } - - private: - //! The dataset. - const typename TreeType::Mat& dataset; - //! The clusters. - const arma::mat& centroids; - //! The new centroids. - arma::mat& newCentroids; - //! The counts of points in each cluster. - arma::Col& counts; - //! Instantiated metric. - MetricType& metric; - - //! The number of O(d) distance calculations that have been performed. - size_t distanceCalculations; -}; - -} // namespace kmeans -} // namespace mlpack - -// Include implementation. -#include "pelleg_moore_kmeans_rules_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_rules_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_rules_impl.hpp deleted file mode 100644 index 3a0fb9793..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_rules_impl.hpp +++ /dev/null @@ -1,183 +0,0 @@ -/** - * @file pelleg_moore_kmeans_rules_impl.hpp - * @author Ryan Curtin - * - * Implementation of the pruning rules and base cases necessary to perform - * single-tree k-means clustering using the fast Pelleg-Moore k-means algorithm, - * which has been shoehorned into the mlpack tree abstractions. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_RULES_IMPL_HPP -#define MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_RULES_IMPL_HPP - -// In case it hasn't been included yet. -#include "pelleg_moore_kmeans_rules.hpp" - -namespace mlpack { -namespace kmeans { - -template -PellegMooreKMeansRules::PellegMooreKMeansRules( - const typename TreeType::Mat& dataset, - const arma::mat& centroids, - arma::mat& newCentroids, - arma::Col& counts, - MetricType& metric) : - dataset(dataset), - centroids(centroids), - newCentroids(newCentroids), - counts(counts), - metric(metric), - distanceCalculations(0) -{ - // Nothing to do. -} - -template -inline force_inline -double PellegMooreKMeansRules::BaseCase( - const size_t /* queryIndex */, - const size_t /* referenceIndex */) -{ - return 0.0; -} - -template -double PellegMooreKMeansRules::Score( - const size_t /* queryIndex */, - TreeType& referenceNode) -{ - // Obtain the parent's blacklist. If this is the root node, we'll start with - // an empty blacklist. This means that after each iteration, we don't need to - // reset any statistics. - if (referenceNode.Parent() == NULL || - referenceNode.Parent()->Stat().Blacklist().n_elem == 0) - referenceNode.Stat().Blacklist().zeros(centroids.n_cols); - else - referenceNode.Stat().Blacklist() = - referenceNode.Parent()->Stat().Blacklist(); - - // The query index is a fake index that we won't use, and the reference node - // holds all of the points in the dataset. Our goal is to determine whether - // or not this node is dominated by a single cluster. - const size_t whitelisted = centroids.n_cols - - arma::accu(referenceNode.Stat().Blacklist()); - - distanceCalculations += whitelisted; - - // Which cluster has minimum distance to the node? - size_t closestCluster = centroids.n_cols; - double minMinDistance = DBL_MAX; - for (size_t i = 0; i < centroids.n_cols; ++i) - { - if (referenceNode.Stat().Blacklist()[i] == 0) - { - const double minDistance = referenceNode.MinDistance(centroids.col(i)); - if (minDistance < minMinDistance) - { - minMinDistance = minDistance; - closestCluster = i; - } - } - } - - // Now, for every other whitelisted cluster, determine if the closest cluster - // owns the point. This calculation is specific to hyperrectangle trees (but, - // this implementation is specific to kd-trees, so that's okay). For - // circular-bound trees, the condition should be simpler and can probably be - // expressed as a comparison between minimum and maximum distances. - size_t newBlacklisted = 0; - for (size_t c = 0; c < centroids.n_cols; ++c) - { - if (referenceNode.Stat().Blacklist()[c] == 1 || c == closestCluster) - continue; - - // This algorithm comes from the proof of Lemma 4 in the extended version - // of the Pelleg-Moore paper (the CMU tech report, that is). It has been - // adapted for speed. - arma::vec cornerPoint(centroids.n_rows); - for (size_t d = 0; d < referenceNode.Bound().Dim(); ++d) - { - if (centroids(d, c) > centroids(d, closestCluster)) - cornerPoint(d) = referenceNode.Bound()[d].Hi(); - else - cornerPoint(d) = referenceNode.Bound()[d].Lo(); - } - - const double closestDist = metric.Evaluate(cornerPoint, - centroids.col(closestCluster)); - const double otherDist = metric.Evaluate(cornerPoint, centroids.col(c)); - - distanceCalculations += 3; // One for cornerPoint, then two distances. - - if (closestDist < otherDist) - { - // The closest cluster dominates the node with respect to the cluster c. - // So we can blacklist c. - referenceNode.Stat().Blacklist()[c] = 1; - ++newBlacklisted; - } - } - - if (whitelisted - newBlacklisted == 1) - { - // This node is dominated by the closest cluster. - counts[closestCluster] += referenceNode.NumDescendants(); - newCentroids.col(closestCluster) += referenceNode.NumDescendants() * - referenceNode.Stat().Centroid(); - - return DBL_MAX; - } - - // Perform the base case here. - for (size_t i = 0; i < referenceNode.NumPoints(); ++i) - { - size_t bestCluster = centroids.n_cols; - double bestDistance = DBL_MAX; - for (size_t c = 0; c < centroids.n_cols; ++c) - { - if (referenceNode.Stat().Blacklist()[c] == 1) - continue; - - ++distanceCalculations; - - // The reference index is the index of the data point. - const double distance = metric.Evaluate(centroids.col(c), - dataset.col(referenceNode.Point(i))); - - if (distance < bestDistance) - { - bestDistance = distance; - bestCluster = c; - } - } - - // Add to resulting centroid. - newCentroids.col(bestCluster) += dataset.col(referenceNode.Point(i)); - ++counts(bestCluster); - } - - // Otherwise, we're not sure, so we can't prune. Recursion order doesn't make - // a difference, so we'll just return a score of 0. - return 0.0; -} - -template -double PellegMooreKMeansRules::Rescore( - const size_t /* queryIndex */, - TreeType& /* referenceNode */, - const double oldScore) -{ - // There's no possible way that calling Rescore() can produce a prune now when - // it couldn't before. - return oldScore; -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_statistic.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_statistic.hpp deleted file mode 100644 index 8e875acd2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/pelleg_moore_kmeans_statistic.hpp +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @file pelleg_moore_kmeans_statistic.hpp - * @author Ryan Curtin - * - * A StatisticType for trees which holds the blacklist for various k-means - * clusters. See the Pelleg and Moore paper for more details. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_STATISTIC_HPP -#define MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_STATISTIC_HPP - -namespace mlpack { -namespace kmeans { - -/** - * A statistic for trees which holds the blacklist for Pelleg-Moore k-means - * clustering (which represents the clusters that cannot possibly own any points - * in a node). - */ -class PellegMooreKMeansStatistic -{ - public: - //! Initialize the statistic without a node (this does nothing). - PellegMooreKMeansStatistic() { } - - //! Initialize the statistic for a node; this calculates the centroid and - //! caches it. - template - PellegMooreKMeansStatistic(TreeType& node) - { - centroid.zeros(node.Dataset().n_rows); - - // Hope it's a depth-first build procedure. Also, this won't work right for - // trees that have self-children or stuff like that. - for (size_t i = 0; i < node.NumChildren(); ++i) - { - centroid += node.Child(i).NumDescendants() * - node.Child(i).Stat().Centroid(); - } - - for (size_t i = 0; i < node.NumPoints(); ++i) - { - centroid += node.Dataset().col(node.Point(i)); - } - - if (node.NumDescendants() > 0) - centroid /= node.NumDescendants(); - else - centroid.fill(DBL_MAX); // Invalid centroid. What else can we do? - } - - //! Get the cluster blacklist. - const arma::uvec& Blacklist() const { return blacklist; } - //! Modify the cluster blacklist. - arma::uvec& Blacklist() { return blacklist; } - - //! Get the node's centroid. - const arma::vec& Centroid() const { return centroid; } - //! Modify the node's centroid (be careful!). - arma::vec& Centroid() { return centroid; } - - private: - //! The cluster blacklist for the node. - arma::uvec blacklist; - //! The centroid of the node, cached for use during prunes. - arma::vec centroid; -}; - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/random_partition.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/random_partition.hpp deleted file mode 100644 index 23ff9bd58..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/random_partition.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @file random_partition.hpp - * @author Ryan Curtin - * - * Very simple partitioner which partitions the data randomly into the number of - * desired clusters. Used as the default InitialPartitionPolicy for KMeans. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_RANDOM_PARTITION_HPP -#define MLPACK_METHODS_KMEANS_RANDOM_PARTITION_HPP - -#include - -namespace mlpack { -namespace kmeans { - -/** - * A very simple partitioner which partitions the data randomly into the number - * of desired clusters. It has no parameters, and so an instance of the class - * is not even necessary. - */ -class RandomPartition -{ - public: - //! Empty constructor, required by the InitialPartitionPolicy policy. - RandomPartition() { } - - /** - * Partition the given dataset into the given number of clusters. Assignments - * are random, and the number of points in each cluster should be equal (or - * approximately equal). - * - * @tparam MatType Type of data (arma::mat or arma::sp_mat). - * @param data Dataset to partition. - * @param clusters Number of clusters to split dataset into. - * @param assignments Vector to store cluster assignments into. Values will - * be between 0 and (clusters - 1). - */ - template - inline static void Cluster(const MatType& data, - const size_t clusters, - arma::Row& assignments) - { - // Implementation is so simple we'll put it here in the header file. - assignments = arma::shuffle(arma::linspace>(0, - (clusters - 1), data.n_cols)); - } - - //! Serialize the partitioner (nothing to do). - template - void serialize(Archive& /* ar */, const unsigned int /* version */) { } -}; - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/refined_start.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/refined_start.hpp deleted file mode 100644 index 827103d0a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/refined_start.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file refined_start.hpp - * @author Ryan Curtin - * - * An implementation of Bradley and Fayyad's "Refining Initial Points for - * K-Means clustering". This class is meant to provide better initial points - * for the k-means algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_REFINED_START_HPP -#define MLPACK_METHODS_KMEANS_REFINED_START_HPP - -#include - -namespace mlpack { -namespace kmeans { - -/** - * A refined approach for choosing initial points for k-means clustering. This - * approach runs k-means several times on random subsets of the data, and then - * clusters those solutions to select refined initial cluster assignments. It - * is an implementation of the following paper: - * - * @inproceedings{bradley1998refining, - * title={Refining initial points for k-means clustering}, - * author={Bradley, Paul S and Fayyad, Usama M}, - * booktitle={Proceedings of the Fifteenth International Conference on Machine - * Learning (ICML 1998)}, - * volume={66}, - * year={1998} - * } - */ -class RefinedStart -{ - public: - /** - * Create the RefinedStart object, optionally specifying parameters for the - * number of samplings to perform and the percentage of the dataset to use in - * each sampling. - */ - RefinedStart(const size_t samplings = 100, - const double percentage = 0.02) : - samplings(samplings), percentage(percentage) { } - - /** - * Partition the given dataset into the given number of clusters according to - * the random sampling scheme outlined in Bradley and Fayyad's paper, and - * return centroids. - * - * @tparam MatType Type of data (arma::mat or arma::sp_mat). - * @param data Dataset to partition. - * @param clusters Number of clusters to split dataset into. - * @param centroids Matrix to store centroids into. - */ - template - void Cluster(const MatType& data, - const size_t clusters, - arma::mat& centroids) const; - - /** - * Partition the given dataset into the given number of clusters according to - * the random sampling scheme outlined in Bradley and Fayyad's paper, and - * return point assignments. - * - * @tparam MatType Type of data (arma::mat or arma::sp_mat). - * @param data Dataset to partition. - * @param clusters Number of clusters to split dataset into. - * @param assignments Vector to store cluster assignments into. Values will - * be between 0 and (clusters - 1). - */ - template - void Cluster(const MatType& data, - const size_t clusters, - arma::Row& assignments) const; - - //! Get the number of samplings that will be performed. - size_t Samplings() const { return samplings; } - //! Modify the number of samplings that will be performed. - size_t& Samplings() { return samplings; } - - //! Get the percentage of the data used by each subsampling. - double Percentage() const { return percentage; } - //! Modify the percentage of the data used by each subsampling. - double& Percentage() { return percentage; } - - //! Serialize the object. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(samplings); - ar & BOOST_SERIALIZATION_NVP(percentage); - } - - private: - //! The number of samplings to perform. - size_t samplings; - //! The percentage of the data to use for each subsampling. - double percentage; -}; - -} // namespace kmeans -} // namespace mlpack - -// Include implementation. -#include "refined_start_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/refined_start_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/refined_start_impl.hpp deleted file mode 100644 index 3822ad25f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/refined_start_impl.hpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @file refined_start_impl.hpp - * @author Ryan Curtin - * - * An implementation of Bradley and Fayyad's "Refining Initial Points for - * K-Means clustering". This class is meant to provide better initial points - * for the k-means algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_KMEANS_REFINED_START_IMPL_HPP -#define MLPACK_METHODS_KMEANS_REFINED_START_IMPL_HPP - -// In case it hasn't been included yet. -#include "refined_start.hpp" - -namespace mlpack { -namespace kmeans { - -//! Partition the given dataset according to Bradley and Fayyad's algorithm. -template -void RefinedStart::Cluster(const MatType& data, - const size_t clusters, - arma::mat& centroids) const -{ - // This will hold the sampled datasets. - const size_t numPoints = size_t(percentage * data.n_cols); - MatType sampledData(data.n_rows, numPoints); - // vector is packed so each bool is 1 bit. - std::vector pointsUsed(data.n_cols, false); - arma::mat sampledCentroids(data.n_rows, samplings * clusters); - - for (size_t i = 0; i < samplings; ++i) - { - // First, assemble the sampled dataset. - size_t curSample = 0; - while (curSample < numPoints) - { - // Pick a random point in [0, numPoints). - size_t sample = (size_t) math::RandInt(data.n_cols); - - if (!pointsUsed[sample]) - { - // This point isn't used yet. So we'll put it in our sample. - pointsUsed[sample] = true; - sampledData.col(curSample) = data.col(sample); - ++curSample; - } - } - - // Now, using the sampled dataset, run k-means. In the case of an empty - // cluster, we re-initialize that cluster as the point furthest away from - // the cluster with maximum variance. This is not *exactly* what the paper - // implements, but it is quite similar, and we'll call it "good enough". - KMeans<> kmeans; - kmeans.Cluster(sampledData, clusters, centroids); - - // Store the sampled centroids. - sampledCentroids.cols(i * clusters, (i + 1) * clusters - 1) = centroids; - - pointsUsed.assign(data.n_cols, false); - } - - // Now, we run k-means on the sampled centroids to get our final clusters. - KMeans<> kmeans; - kmeans.Cluster(sampledCentroids, clusters, centroids); -} - -template -void RefinedStart::Cluster(const MatType& data, - const size_t clusters, - arma::Row& assignments) const -{ - // Perform the Bradley-Fayyad refined start algorithm, and get initial - // centroids back. - arma::mat centroids; - Cluster(data, clusters, centroids); - - // Turn the final centroids into assignments. - assignments.set_size(data.n_cols); - for (size_t i = 0; i < data.n_cols; ++i) - { - // Find the closest centroid to this point. - double minDistance = std::numeric_limits::infinity(); - size_t closestCluster = clusters; - - for (size_t j = 0; j < clusters; ++j) - { - // This is restricted to the L2 distance, and unfortunately it would take - // a lot of refactoring and redesign to make this more general... we would - // probably need to have KMeans take a template template parameter for the - // initial partition policy. It's not clear how to best do this. - const double distance = metric::EuclideanDistance::Evaluate(data.col(i), - centroids.col(j)); - - if (distance < minDistance) - { - minDistance = distance; - closestCluster = j; - } - } - - // Assign the point to its closest cluster. - assignments[i] = closestCluster; - } -} - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/kmeans/sample_initialization.hpp b/src/sdk/mlpack/include/mlpack/methods/kmeans/sample_initialization.hpp deleted file mode 100644 index 9c8d47a46..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/kmeans/sample_initialization.hpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @file sample_initialization.hpp - * @author Ryan Curtin - * - * In order to construct initial centroids, randomly sample points from the - * dataset. This tends to give better results than the RandomPartition - * strategy. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef __MLPACK_METHODS_KMEANS_SAMPLE_INITIALIZATION_HPP -#define __MLPACK_METHODS_KMEANS_SAMPLE_INITIALIZATION_HPP - -#include -#include - -namespace mlpack { -namespace kmeans { - -class SampleInitialization -{ - public: - //! Empty constructor, required by the InitialPartitionPolicy type definition. - SampleInitialization() { } - - /** - * Initialize the centroids matrix by randomly sampling points from the data - * matrix. - * - * @param data Dataset. - * @param clusters Number of clusters. - * @param centroids Matrix to put initial centroids into. - */ - template - inline static void Cluster(const MatType& data, - const size_t clusters, - arma::mat& centroids) - { - centroids.set_size(data.n_rows, clusters); - for (size_t i = 0; i < clusters; ++i) - { - // Randomly sample a point. - const size_t index = math::RandInt(0, data.n_cols); - centroids.col(i) = data.col(index); - } - } -}; - -} // namespace kmeans -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/lars/lars.hpp b/src/sdk/mlpack/include/mlpack/methods/lars/lars.hpp deleted file mode 100644 index c34cec438..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/lars/lars.hpp +++ /dev/null @@ -1,337 +0,0 @@ -/** - * @file lars.hpp - * @author Nishant Mehta (niche) - * - * Definition of the LARS class, which performs Least Angle Regression and the - * LASSO. - * - * Only minor modifications of LARS are necessary to handle the constrained - * version of the problem: - * - * \f[ - * \min_{\beta} 0.5 || X \beta - y ||_2^2 + 0.5 \lambda_2 || \beta ||_2^2 - * \f] - * subject to \f$ ||\beta||_1 <= \tau \f$ - * - * Although this option currently is not implemented, it will be implemented - * very soon. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LARS_LARS_HPP -#define MLPACK_METHODS_LARS_LARS_HPP - -#include - -namespace mlpack { -namespace regression { - -// beta is the estimator -// yHat is the prediction from the current estimator - -/** - * An implementation of LARS, a stage-wise homotopy-based algorithm for - * l1-regularized linear regression (LASSO) and l1+l2 regularized linear - * regression (Elastic Net). - * - * Let \f$ X \f$ be a matrix where each row is a point and each column is a - * dimension and let \f$ y \f$ be a vector of responses. - * - * The Elastic Net problem is to solve - * - * \f[ \min_{\beta} 0.5 || X \beta - y ||_2^2 + \lambda_1 || \beta ||_1 + - * 0.5 \lambda_2 || \beta ||_2^2 \f] - * - * where \f$ \beta \f$ is the vector of regression coefficients. - * - * If \f$ \lambda_1 > 0 \f$ and \f$ \lambda_2 = 0 \f$, the problem is the LASSO. - * If \f$ \lambda_1 > 0 \f$ and \f$ \lambda_2 > 0 \f$, the problem is the - * elastic net. - * If \f$ \lambda_1 = 0 \f$ and \f$ \lambda_2 > 0 \f$, the problem is ridge - * regression. - * If \f$ \lambda_1 = 0 \f$ and \f$ \lambda_2 = 0 \f$, the problem is - * unregularized linear regression. - * - * Note: This algorithm is not recommended for use (in terms of efficiency) - * when \f$ \lambda_1 \f$ = 0. - * - * For more details, see the following papers: - * - * @code - * @article{efron2004least, - * title={Least angle regression}, - * author={Efron, B. and Hastie, T. and Johnstone, I. and Tibshirani, R.}, - * journal={The Annals of statistics}, - * volume={32}, - * number={2}, - * pages={407--499}, - * year={2004}, - * publisher={Institute of Mathematical Statistics} - * } - * @endcode - * - * @code - * @article{zou2005regularization, - * title={Regularization and variable selection via the elastic net}, - * author={Zou, H. and Hastie, T.}, - * journal={Journal of the Royal Statistical Society Series B}, - * volume={67}, - * number={2}, - * pages={301--320}, - * year={2005}, - * publisher={Royal Statistical Society} - * } - * @endcode - */ -class LARS -{ - public: - /** - * Set the parameters to LARS. Both lambda1 and lambda2 default to 0. - * - * @param useCholesky Whether or not to use Cholesky decomposition when - * solving linear system (as opposed to using the full Gram matrix). - * @param lambda1 Regularization parameter for l1-norm penalty. - * @param lambda2 Regularization parameter for l2-norm penalty. - * @param tolerance Run until the maximum correlation of elements in (X^T y) - * is less than this. - */ - LARS(const bool useCholesky = false, - const double lambda1 = 0.0, - const double lambda2 = 0.0, - const double tolerance = 1e-16); - - /** - * Set the parameters to LARS, and pass in a precalculated Gram matrix. Both - * lambda1 and lambda2 default to 0. - * - * @param useCholesky Whether or not to use Cholesky decomposition when - * solving linear system (as opposed to using the full Gram matrix). - * @param gramMatrix Gram matrix. - * @param lambda1 Regularization parameter for l1-norm penalty. - * @param lambda2 Regularization parameter for l2-norm penalty. - * @param tolerance Run until the maximum correlation of elements in (X^T y) - * is less than this. - */ - LARS(const bool useCholesky, - const arma::mat& gramMatrix, - const double lambda1 = 0.0, - const double lambda2 = 0.0, - const double tolerance = 1e-16); - - /** - * Set the parameters to LARS and run training. Both lambda1 and lambda2 - * are set by default to 0. - * - * @param data Input data. - * @param responses A vector of targets. - * @param transposeData Should be true if the input data is column-major and - * false otherwise. - * @param useCholesky Whether or not to use Cholesky decomposition when - * solving linear system (as opposed to using the full Gram matrix). - * @param lambda1 Regularization parameter for l1-norm penalty. - * @param lambda2 Regularization parameter for l2-norm penalty. - * @param tolerance Run until the maximum correlation of elements in (X^T y) - * is less than this. - */ - LARS(const arma::mat& data, - const arma::rowvec& responses, - const bool transposeData = true, - const bool useCholesky = false, - const double lambda1 = 0.0, - const double lambda2 = 0.0, - const double tolerance = 1e-16); - - /** - * Set the parameters to LARS, pass in a precalculated Gram matrix, and run - * training. Both lambda1 and lambda2 are set by default to 0. - * - * @param data Input data. - * @param responses A vector of targets. - * @param transposeData Should be true if the input data is column-major and - * false otherwise. - * @param useCholesky Whether or not to use Cholesky decomposition when - * solving linear system (as opposed to using the full Gram matrix). - * @param gramMatrix Gram matrix. - * @param lambda1 Regularization parameter for l1-norm penalty. - * @param lambda2 Regularization parameter for l2-norm penalty. - * @param tolerance Run until the maximum correlation of elements in (X^T y) - * is less than this. - */ - LARS(const arma::mat& data, - const arma::rowvec& responses, - const bool transposeData, - const bool useCholesky, - const arma::mat& gramMatrix, - const double lambda1 = 0.0, - const double lambda2 = 0.0, - const double tolerance = 1e-16); - - /** - * Run LARS. The input matrix (like all mlpack matrices) should be - * column-major -- each column is an observation and each row is a dimension. - * However, because LARS is more efficient on a row-major matrix, this method - * will (internally) transpose the matrix. If this transposition is not - * necessary (i.e., you want to pass in a row-major matrix), pass 'false' for - * the transposeData parameter. - * - * @param data Column-major input data (or row-major input data if rowMajor = - * true). - * @param responses A vector of targets. - * @param beta Vector to store the solution (the coefficients) in. - * @param transposeData Set to false if the data is row-major. - */ - void Train(const arma::mat& data, - const arma::rowvec& responses, - arma::vec& beta, - const bool transposeData = true); - - /** - * Run LARS. The input matrix (like all mlpack matrices) should be - * column-major -- each column is an observation and each row is a dimension. - * However, because LARS is more efficient on a row-major matrix, this method - * will (internally) transpose the matrix. If this transposition is not - * necessary (i.e., you want to pass in a row-major matrix), pass 'false' for - * the transposeData parameter. - * - * @param data Input data. - * @param responses A vector of targets. - * @param transposeData Should be true if the input data is column-major and - * false otherwise. - */ - void Train(const arma::mat& data, - const arma::rowvec& responses, - const bool transposeData = true); - - /** - * Predict y_i for each data point in the given data matrix using the - * currently-trained LARS model. - * - * @param points The data points to regress on. - * @param predictions y, which will contained calculated values on completion. - * @param rowMajor Should be true if the data points matrix is row-major and - * false otherwise. - */ - void Predict(const arma::mat& points, - arma::rowvec& predictions, - const bool rowMajor = false) const; - - //! Access the set of active dimensions. - const std::vector& ActiveSet() const { return activeSet; } - - //! Access the set of coefficients after each iteration; the solution is the - //! last element. - const std::vector& BetaPath() const { return betaPath; } - - //! Access the solution coefficients - const arma::vec& Beta() const { return betaPath.back(); } - - //! Access the set of values for lambda1 after each iteration; the solution is - //! the last element. - const std::vector& LambdaPath() const { return lambdaPath; } - - //! Access the upper triangular cholesky factor. - const arma::mat& MatUtriCholFactor() const { return matUtriCholFactor; } - - /** - * Serialize the LARS model. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Gram matrix. - arma::mat matGramInternal; - - //! Pointer to the Gram matrix we will use. - const arma::mat* matGram; - - //! Upper triangular cholesky factor; initially 0x0 matrix. - arma::mat matUtriCholFactor; - - //! Whether or not to use Cholesky decomposition when solving linear system. - bool useCholesky; - - //! True if this is the LASSO problem. - bool lasso; - //! Regularization parameter for l1 penalty. - double lambda1; - - //! True if this is the elastic net problem. - bool elasticNet; - //! Regularization parameter for l2 penalty. - double lambda2; - - //! Tolerance for main loop. - double tolerance; - - //! Solution path. - std::vector betaPath; - - //! Value of lambda_1 for each solution in solution path. - std::vector lambdaPath; - - //! Active set of dimensions. - std::vector activeSet; - - //! Active set membership indicator (for each dimension). - std::vector isActive; - - // Set of variables that are ignored (if any). - - //! Set of ignored variables (for dimensions in span{active set dimensions}). - std::vector ignoreSet; - - //! Membership indicator for set of ignored variables. - std::vector isIgnored; - - /** - * Remove activeVarInd'th element from active set. - * - * @param activeVarInd Index of element to remove from active set. - */ - void Deactivate(const size_t activeVarInd); - - /** - * Add dimension varInd to active set. - * - * @param varInd Dimension to add to active set. - */ - void Activate(const size_t varInd); - - /** - * Add dimension varInd to ignores set (never removed). - * - * @param varInd Dimension to add to ignores set. - */ - void Ignore(const size_t varInd); - - // compute "equiangular" direction in output space - void ComputeYHatDirection(const arma::mat& matX, - const arma::vec& betaDirection, - arma::vec& yHatDirection); - - // interpolate to compute last solution vector - void InterpolateBeta(); - - void CholeskyInsert(const arma::vec& newX, const arma::mat& X); - - void CholeskyInsert(double sqNormNewX, const arma::vec& newGramCol); - - void GivensRotate(const arma::vec::fixed<2>& x, - arma::vec::fixed<2>& rotatedX, - arma::mat& G); - - void CholeskyDelete(const size_t colToKill); -}; - -} // namespace regression -} // namespace mlpack - -// Include implementation of serialize(). -#include "lars_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/lars/lars_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/lars/lars_impl.hpp deleted file mode 100644 index cee321fa3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/lars/lars_impl.hpp +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @file lars_impl.hpp - * @author Ryan Curtin - * - * Implementation of templated LARS functions. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LARS_LARS_IMPL_HPP -#define MLPACK_METHODS_LARS_LARS_IMPL_HPP - -//! In case it hasn't been included yet. -#include "lars.hpp" - -namespace mlpack { -namespace regression { - -/** - * Serialize the LARS model. - */ -template -void LARS::serialize(Archive& ar, const unsigned int /* version */) -{ - // If we're loading, we have to use the internal storage. - if (Archive::is_loading::value) - { - matGram = &matGramInternal; - ar & BOOST_SERIALIZATION_NVP(matGramInternal); - } - else - { - ar & boost::serialization::make_nvp("matGramInternal", - (const_cast(*matGram))); - } - - ar & BOOST_SERIALIZATION_NVP(matUtriCholFactor); - ar & BOOST_SERIALIZATION_NVP(useCholesky); - ar & BOOST_SERIALIZATION_NVP(lasso); - ar & BOOST_SERIALIZATION_NVP(lambda1); - ar & BOOST_SERIALIZATION_NVP(elasticNet); - ar & BOOST_SERIALIZATION_NVP(lambda2); - ar & BOOST_SERIALIZATION_NVP(tolerance); - ar & BOOST_SERIALIZATION_NVP(betaPath); - ar & BOOST_SERIALIZATION_NVP(lambdaPath); - ar & BOOST_SERIALIZATION_NVP(activeSet); - ar & BOOST_SERIALIZATION_NVP(isActive); - ar & BOOST_SERIALIZATION_NVP(ignoreSet); - ar & BOOST_SERIALIZATION_NVP(isIgnored); -} - -} // namespace regression -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/linear_regression/linear_regression.hpp b/src/sdk/mlpack/include/mlpack/methods/linear_regression/linear_regression.hpp deleted file mode 100644 index 76823f89f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/linear_regression/linear_regression.hpp +++ /dev/null @@ -1,168 +0,0 @@ -/** - * @file linear_regression.hpp - * @author James Cline - * @author Michael Fox - * - * Simple least-squares linear regression. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LINEAR_REGRESSION_LINEAR_REGRESSION_HPP -#define MLPACK_METHODS_LINEAR_REGRESSION_LINEAR_REGRESSION_HPP - -#include - -namespace mlpack { -namespace regression /** Regression methods. */ { - -/** - * A simple linear regression algorithm using ordinary least squares. - * Optionally, this class can perform ridge regression, if the lambda parameter - * is set to a number greater than zero. - */ -class LinearRegression -{ - public: - /** - * Creates the model. - * - * @param predictors X, matrix of data points. - * @param responses y, the measured data for each point in X. - * @param lambda Regularization constant for ridge regression. - * @param intercept Whether or not to include an intercept term. - */ - LinearRegression(const arma::mat& predictors, - const arma::rowvec& responses, - const double lambda = 0, - const bool intercept = true); - - /** - * Creates the model with weighted learning. - * - * @param predictors X, matrix of data points. - * @param responses y, the measured data for each point in X. - * @param weights Observation weights (for boosting). - * @param lambda Regularization constant for ridge regression. - * @param intercept Whether or not to include an intercept term. - */ - LinearRegression(const arma::mat& predictors, - const arma::rowvec& responses, - const arma::rowvec& weights, - const double lambda = 0, - const bool intercept = true); - - /** - * Empty constructor. This gives a non-working model, so make sure Train() is - * called (or make sure the model parameters are set) before calling - * Predict()! - */ - LinearRegression() : lambda(0.0), intercept(true) { } - - /** - * Train the LinearRegression model on the given data. Careful! This will - * completely ignore and overwrite the existing model. This particular - * implementation does not have an incremental training algorithm. To set the - * regularization parameter lambda, call Lambda() or set a different value in - * the constructor. - * - * @param predictors X, the matrix of data points to train the model on. - * @param responses y, the responses to the data points. - * @param intercept Whether or not to fit an intercept term. - */ - void Train(const arma::mat& predictors, - const arma::rowvec& responses, - const bool intercept = true); - - /** - * Train the LinearRegression model on the given data and weights. Careful! - * This will completely ignore and overwrite the existing model. This - * particular implementation does not have an incremental training algorithm. - * To set the regularization parameter lambda, call Lambda() or set a - * different value in the constructor. - * - * @param predictors X, the matrix of data points to train the model on. - * @param responses y, the responses to the data points. - * @param intercept Whether or not to fit an intercept term. - * @param weights Observation weights (for boosting). - */ - void Train(const arma::mat& predictors, - const arma::rowvec& responses, - const arma::rowvec& weights, - const bool intercept = true); - - /** - * Calculate y_i for each data point in points. - * - * @param points the data points to calculate with. - * @param predictions y, will contain calculated values on completion. - */ - void Predict(const arma::mat& points, arma::rowvec& predictions) const; - - /** - * Calculate the L2 squared error on the given predictors and responses using - * this linear regression model. This calculation returns - * - * \f[ - * (1 / n) * \| y - X B \|^2_2 - * \f] - * - * where \f$ y \f$ is the responses vector, \f$ X \f$ is the matrix of - * predictors, and \f$ B \f$ is the parameters of the trained linear - * regression model. - * - * As this number decreases to 0, the linear regression fit is better. - * - * @param points Matrix of predictors (X). - * @param responses Transposed vector of responses (y^T). - */ - double ComputeError(const arma::mat& points, - const arma::rowvec& responses) const; - - //! Return the parameters (the b vector). - const arma::vec& Parameters() const { return parameters; } - //! Modify the parameters (the b vector). - arma::vec& Parameters() { return parameters; } - - //! Return the Tikhonov regularization parameter for ridge regression. - double Lambda() const { return lambda; } - //! Modify the Tikhonov regularization parameter for ridge regression. - double& Lambda() { return lambda; } - - //! Return whether or not an intercept term is used in the model. - bool Intercept() const { return intercept; } - - /** - * Serialize the model. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(parameters); - ar & BOOST_SERIALIZATION_NVP(lambda); - ar & BOOST_SERIALIZATION_NVP(intercept); - } - - private: - /** - * The calculated B. - * Initialized and filled by constructor to hold the least squares solution. - */ - arma::vec parameters; - - /** - * The Tikhonov regularization parameter for ridge regression (0 for linear - * regression). - */ - double lambda; - - //! Indicates whether first parameter is intercept. - bool intercept; -}; - -} // namespace regression -} // namespace mlpack - -#endif // MLPACK_METHODS_LINEAR_REGRESSION_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/local_coordinate_coding/lcc.hpp b/src/sdk/mlpack/include/mlpack/methods/local_coordinate_coding/lcc.hpp deleted file mode 100644 index baa0d8f74..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/local_coordinate_coding/lcc.hpp +++ /dev/null @@ -1,224 +0,0 @@ -/** - * @file lcc.hpp - * @author Nishant Mehta - * - * Definition of the LocalCoordinateCoding class, which performs the Local - * Coordinate Coding algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LOCAL_COORDINATE_CODING_LCC_HPP -#define MLPACK_METHODS_LOCAL_COORDINATE_CODING_LCC_HPP - -#include -#include - -// Include three simple dictionary initializers from sparse coding. -#include "../sparse_coding/nothing_initializer.hpp" -#include "../sparse_coding/data_dependent_random_initializer.hpp" -#include "../sparse_coding/random_initializer.hpp" - -namespace mlpack { -namespace lcc { - -/** - * An implementation of Local Coordinate Coding (LCC) that codes data which - * approximately lives on a manifold using a variation of l1-norm regularized - * sparse coding; in LCC, the penalty on the absolute value of each point's - * coefficient for each atom is weighted by the squared distance of that point - * to that atom. - * - * Let d be the number of dimensions in the original space, m the number of - * training points, and k the number of atoms in the dictionary (the dimension - * of the learned feature space). The training data X is a d-by-m matrix where - * each column is a point and each row is a dimension. The dictionary D is a - * d-by-k matrix, and the sparse codes matrix Z is a k-by-m matrix. - * This program seeks to minimize the objective: - * min_{D,Z} ||X - D Z||_{Fro}^2 - * + lambda sum_{i=1}^m sum_{j=1}^k dist(X_i,D_j)^2 Z_i^j - * where lambda > 0. - * - * This problem is solved by an algorithm that alternates between a dictionary - * learning step and a sparse coding step. The dictionary learning step updates - * the dictionary D by solving a linear system (note that the objective is a - * positive definite quadratic program). The sparse coding step involves - * solving a large number of weighted l1-norm regularized linear regression - * problems problems; this can be done efficiently using LARS, an algorithm - * that can solve the LASSO (paper below). - * - * The papers are listed below. - * - * @code - * @incollection{NIPS2009_0719, - * title = {Nonlinear Learning using Local Coordinate Coding}, - * author = {Kai Yu and Tong Zhang and Yihong Gong}, - * booktitle = {Advances in Neural Information Processing Systems 22}, - * editor = {Y. Bengio and D. Schuurmans and J. Lafferty and C. K. I. Williams - * and A. Culotta}, - * pages = {2223--2231}, - * year = {2009} - * } - * @endcode - * - * @code - * @article{efron2004least, - * title={Least angle regression}, - * author={Efron, B. and Hastie, T. and Johnstone, I. and Tibshirani, R.}, - * journal={The Annals of statistics}, - * volume={32}, - * number={2}, - * pages={407--499}, - * year={2004}, - * publisher={Institute of Mathematical Statistics} - * } - * @endcode - */ -class LocalCoordinateCoding -{ - public: - /** - * Set the parameters to LocalCoordinateCoding, and train the dictionary. - * This constructor will also initialize the dictionary using the given - * DictionaryInitializer before training. - * - * If you want to initialize the dictionary to a custom matrix, consider - * either writing your own DictionaryInitializer class (with void - * Initialize(const arma::mat& data, arma::mat& dictionary) function), or call - * the constructor that does not take a data matrix, then call Dictionary() to - * set the dictionary matrix to a matrix of your choosing, and then call - * Train() with sparse_coding::NothingInitializer (i.e. - * Train(data)). - * - * @param data Data matrix. - * @param atoms Number of atoms in dictionary. - * @param lambda Regularization parameter for weighted l1-norm penalty. - * @param maxIterations Maximum number of iterations for training (0 runs - * until convergence). - * @param tolerance Tolerance for the objective function. - */ - template< - typename DictionaryInitializer = - sparse_coding::DataDependentRandomInitializer - > - LocalCoordinateCoding(const arma::mat& data, - const size_t atoms, - const double lambda, - const size_t maxIterations = 0, - const double tolerance = 0.01, - const DictionaryInitializer& initializer = - DictionaryInitializer()); - - /** - * Set the parameters to LocalCoordinateCoding. This constructor will not - * train the model, and a subsequent call to Train() will be required before - * the model can encode points with Encode(). The default values for atoms - * and lambda should be changed if you intend to train the model! - * - * @param atoms Number of atoms in dictionary. - * @param lambda Regularization parameter for weighted l1-norm penalty. - * @param maxIterations Maximum number of iterations for training (0 runs - * until convergence). - * @param tolerance Tolerance for the objective function. - */ - LocalCoordinateCoding(const size_t atoms = 0, - const double lambda = 0.0, - const size_t maxIterations = 0, - const double tolerance = 0.01); - - /** - * Run local coordinate coding. - * - * @param nIterations Maximum number of iterations to run algorithm. - * @param objTolerance Tolerance of objective function. When the objective - * function changes by a value lower than this tolerance, the optimization - * terminates. - */ - template< - typename DictionaryInitializer = - sparse_coding::DataDependentRandomInitializer - > - void Train(const arma::mat& data, - const DictionaryInitializer& initializer = - DictionaryInitializer()); - - /** - * Code each point via distance-weighted LARS. - * - * @param data Matrix containing points to encode. - * @param codes Output matrix to store codes in. - */ - void Encode(const arma::mat& data, arma::mat& codes); - - /** - * Learn dictionary by solving linear system. - * - * @param adjacencies Indices of entries (unrolled column by column) of - * the coding matrix Z that are non-zero (the adjacency matrix for the - * bipartite graph of points and atoms) - */ - void OptimizeDictionary(const arma::mat& data, - const arma::mat& codes, - const arma::uvec& adjacencies); - - /** - * Compute objective function given the list of adjacencies. - */ - double Objective(const arma::mat& data, - const arma::mat& codes, - const arma::uvec& adjacencies) const; - - //! Get the number of atoms. - size_t Atoms() const { return atoms; } - //! Modify the number of atoms. - size_t& Atoms() { return atoms; } - - //! Accessor for dictionary. - const arma::mat& Dictionary() const { return dictionary; } - //! Mutator for dictionary. - arma::mat& Dictionary() { return dictionary; } - - //! Get the L1 regularization parameter. - double Lambda() const { return lambda; } - //! Modify the L1 regularization parameter. - double& Lambda() { return lambda; } - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - //! Get the objective tolerance. - double Tolerance() const { return tolerance; } - //! Modify the objective tolerance. - double& Tolerance() { return tolerance; } - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Number of atoms in dictionary. - size_t atoms; - - //! Dictionary (columns are atoms). - arma::mat dictionary; - - //! l1 regularization term. - double lambda; - - //! Maximum number of iterations during training. - size_t maxIterations; - //! Tolerance for main objective. - double tolerance; -}; - -} // namespace lcc -} // namespace mlpack - -// Include implementation. -#include "lcc_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/local_coordinate_coding/lcc_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/local_coordinate_coding/lcc_impl.hpp deleted file mode 100644 index 621674759..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/local_coordinate_coding/lcc_impl.hpp +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @file lcc_impl.hpp - * @author Nishant Mehta - * - * Implementation of Local Coordinate Coding - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LOCAL_COORDINATE_CODING_LCC_IMPL_HPP -#define MLPACK_METHODS_LOCAL_COORDINATE_CODING_LCC_IMPL_HPP - -// In case it hasn't been included yet. -#include "lcc.hpp" - -namespace mlpack { -namespace lcc { - -template -LocalCoordinateCoding::LocalCoordinateCoding( - const arma::mat& data, - const size_t atoms, - const double lambda, - const size_t maxIterations, - const double tolerance, - const DictionaryInitializer& initializer) : - atoms(atoms), - lambda(lambda), - maxIterations(maxIterations), - tolerance(tolerance) -{ - // Train the model. - Train(data, initializer); -} - -template -void LocalCoordinateCoding::Train( - const arma::mat& data, - const DictionaryInitializer& initializer) -{ - Timer::Start("local_coordinate_coding"); - - // Initialize the dictionary. - initializer.Initialize(data, atoms, dictionary); - - double lastObjVal = DBL_MAX; - - // Take the initial coding step, which has to happen before entering the main - // loop. - Log::Info << "Initial Coding Step." << std::endl; - - arma::mat codes; - Encode(data, codes); - arma::uvec adjacencies = find(codes); - - Log::Info << " Sparsity level: " << 100.0 * ((double)(adjacencies.n_elem)) / - ((double)(atoms * data.n_cols)) << "%.\n"; - Log::Info << " Objective value: " << Objective(data, codes, adjacencies) - << "." << std::endl; - - for (size_t t = 1; t != maxIterations; t++) - { - Log::Info << "Iteration " << t << " of " << maxIterations << "." - << std::endl; - - // First step: optimize the dictionary. - Log::Info << "Performing dictionary step..." << std::endl; - OptimizeDictionary(data, codes, adjacencies); - double dsObjVal = Objective(data, codes, adjacencies); - Log::Info << " Objective value: " << dsObjVal << "." << std::endl; - - // Second step: perform the coding. - Log::Info << "Performing coding step..." << std::endl; - Encode(data, codes); - adjacencies = find(codes); - Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem)) - / ((double)(atoms * data.n_cols)) << "%.\n"; - - // Terminate if the objective increased in the coding step. - double curObjVal = Objective(data, codes, adjacencies); - if (curObjVal > dsObjVal) - { - Log::Warn << "Objective increased in coding step! Terminating." - << std::endl; - break; - } - - // Find the new objective value and improvement so we can check for - // convergence. - double improvement = lastObjVal - curObjVal; - Log::Info << "Objective value: " << curObjVal << " (improvement " - << std::scientific << improvement << ")." << std::endl; - - if (improvement < tolerance) - { - Log::Info << "Converged within tolerance " << tolerance << ".\n"; - break; - } - - lastObjVal = curObjVal; - } - - Timer::Stop("local_coordinate_coding"); -} - -template -void LocalCoordinateCoding::serialize(Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(atoms); - ar & BOOST_SERIALIZATION_NVP(dictionary); - ar & BOOST_SERIALIZATION_NVP(lambda); - ar & BOOST_SERIALIZATION_NVP(maxIterations); - ar & BOOST_SERIALIZATION_NVP(tolerance); -} - -} // namespace lcc -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression.hpp b/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression.hpp deleted file mode 100644 index 11ea3ca41..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression.hpp +++ /dev/null @@ -1,251 +0,0 @@ -/** - * @file logistic_regression.hpp - * @author Sumedh Ghaisas - * @author Arun Reddy - * - * The LogisticRegression class, which implements logistic regression. This - * implements supports L2-regularization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_HPP -#define MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_HPP - -#include -#include - -#include "logistic_regression_function.hpp" - -namespace mlpack { -namespace regression { - -/** - * The LogisticRegression class implements an L2-regularized logistic regression - * model, and supports training with multiple optimizers and classification. - * The class supports different observation types via the MatType template - * parameter; for instance, logistic regression can be performed on sparse - * datasets by specifying arma::sp_mat as the MatType parameter. - * - * LogisticRegression can be used for general classification tasks, but the - * class is restricted to support only two classes. For multiclass logistic - * regression, see mlpack::regression::SoftmaxRegression. - * - * @tparam MatType Type of data matrix. - */ -template -class LogisticRegression -{ - public: - /** - * Construct the LogisticRegression class with the given labeled training - * data. This will train the model. Optionally, specify lambda, which is the - * penalty parameter for L2-regularization. If not specified, it is set to 0, - * which results in standard (unregularized) logistic regression. - * - * It is not possible to set a custom optimizer with this constructor. Either - * use a constructor that does not train and call Train() with a custom - * optimizer type, or use the constructor that takes an instantiated - * optimizer. (This unfortunate situation is a language restriction of C++.) - * - * @param predictors Input training variables. - * @param responses Outputs resulting from input training variables. - * @param lambda L2-regularization parameter. - */ - LogisticRegression(const MatType& predictors, - const arma::Row& responses, - const double lambda = 0); - - /** - * Construct the LogisticRegression class with the given labeled training - * data. This will train the model. Optionally, specify lambda, which is the - * penalty parameter for L2-regularization. If not specified, it is set to 0, - * which results in standard (unregularized) logistic regression. - * - * It is not possible to set a custom optimizer with this constructor. Either - * use a constructor that does not train and call Train() with a custom - * optimizer type, or use the constructor that takes an instantiated - * optimizer. (This unfortunate situation is a language restriction of C++.) - * - * @param predictors Input training variables. - * @param responses Outputs results from input training variables. - * @param initialPoint Initial model to train with. - * @param lambda L2-regularization parameter. - */ - LogisticRegression(const MatType& predictors, - const arma::Row& responses, - const arma::rowvec& initialPoint, - const double lambda = 0); - - /** - * Construct the LogisticRegression class without performing any training. - * The dimensionality of the data (which will be used to set the size of the - * parameters vector) must be specified, and all of the parameters in the - * model will be set to 0. Note that the dimensionality may be changed later - * by directly modifying the parameters vector (using Parameters()). - * - * @param dimensionality Dimensionality of the data. - * @param lambda L2-regularization parameter. - */ - LogisticRegression(const size_t dimensionality = 0, - const double lambda = 0); - - /** - * Construct the LogisticRegression class with the given labeled training - * data. This will train the model. This overload takes an already - * instantiated optimizer (which holds the LogisticRegressionFunction error - * function, which must also be instantiated), so that the optimizer can be - * configured before the training is run by this constructor. The update - * policy of the optimizer can be set through the policy argument. The - * predictors and responses and initial point are all taken from the error - * function contained in the optimizer. - * - * @param predictors Input training variables. - * @param responses Outputs results from input training variables. - * @param optimizer Instantiated optimizer with instantiated error function. - * @param lambda L2-regularization parameter. - */ - template - LogisticRegression(const MatType& predictors, - const arma::Row& responses, - OptimizerType& optimizer, - const double lambda); - - /** - * Train the LogisticRegression model on the given input data. By default, - * the L-BFGS optimization algorithm is used, but others can be specified - * (such as mlpack::optimization::SGD). - * - * This will use the existing model parameters as a starting point for the - * optimization. If this is not what you want, then you should access the - * parameters vector directly with Parameters() and modify it as desired. - * - * @tparam OptimizerType Type of optimizer to use to train the model. - * @param predictors Input training variables. - * @param responses Outputs results from input training variables. - * @return The final objective of the trained model (NaN or Inf on error) - */ - template - double Train(const MatType& predictors, - const arma::Row& responses); - - /** - * Train the LogisticRegression model with the given instantiated optimizer. - * Using this overload allows configuring the instantiated optimizer before - * training is performed. - * - * Note that the initial point of the optimizer - * (optimizer.Function().GetInitialPoint()) will be used as the initial point - * of the optimization, overwriting any existing trained model. If you don't - * want to overwrite the existing model, set - * optimizer.Function().GetInitialPoint() to the current parameters vector, - * accessible via Parameters(). - * - * @param predictors Input training variables. - * @param responses Outputs results from input training variables. - * @param optimizer Instantiated optimizer with instantiated error function. - * @return The final objective of the trained model (NaN or Inf on error) - */ - template - double Train(const MatType& predictors, - const arma::Row& responses, - OptimizerType& optimizer); - - //! Return the parameters (the b vector). - const arma::rowvec& Parameters() const { return parameters; } - //! Modify the parameters (the b vector). - arma::rowvec& Parameters() { return parameters; } - - //! Return the lambda value for L2-regularization. - const double& Lambda() const { return lambda; } - //! Modify the lambda value for L2-regularization. - double& Lambda() { return lambda; } - - /** - * Classify the given point. The predicted label is returned. Optionally, - * specify the decision boundary; logistic regression returns a value between - * 0 and 1. If the value is greater than the decision boundary, the response - * is taken to be 1; otherwise, it is 0. By default the decision boundary is - * 0.5. - * - * @param point Point to classify. - * @param decisionBoundary Decision boundary (default 0.5). - * @return Predicted label of point. - */ - template - size_t Classify(const VecType& point, - const double decisionBoundary = 0.5) const; - - /** - * Classify the given points, returning the predicted labels for each point. - * Optionally, specify the decision boundary; logistic regression returns a - * value between 0 and 1. If the value is greater than the decision boundary, - * the response is taken to be 1; otherwise, it is 0. By default the decision - * boundary is 0.5. - * - * @param dataset Set of points to classify. - * @param labels Predicted labels for each point. - * @param decisionBoundary Decision boundary (default 0.5). - */ - void Classify(const MatType& dataset, - arma::Row& labels, - const double decisionBoundary = 0.5) const; - - /** - * Classify the given points, returning class probabilities for each point. - * - * @param dataset Set of points to classify. - * @param probabilities Class probabilities for each point (output). - */ - void Classify(const MatType& dataset, - arma::mat& probabilities) const; - - /** - * Compute the accuracy of the model on the given predictors and responses, - * optionally using the given decision boundary. The responses should be - * either 0 or 1. Logistic regression returns a value between 0 and 1. If - * the value is greater than the decision boundary, the response is taken to - * be 1; otherwise, it is 0. By default, the decision boundary is 0.5. - * - * The accuracy is returned as a percentage, between 0 and 100. - * - * @param predictors Input predictors. - * @param responses Vector of responses. - * @param decisionBoundary Decision boundary (default 0.5). - * @return Percentage of responses that are predicted correctly. - */ - double ComputeAccuracy(const MatType& predictors, - const arma::Row& responses, - const double decisionBoundary = 0.5) const; - - /** - * Compute the error of the model. This returns the negative objective - * function of the logistic regression log-likelihood function. For the model - * to be optimal, the negative log-likelihood function should be minimized. - * - * @param predictors Input predictors. - * @param responses Vector of responses. - */ - double ComputeError(const MatType& predictors, - const arma::Row& responses) const; - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Vector of trained parameters (size: dimensionality plus one). - arma::rowvec parameters; - //! L2-regularization penalty parameter. - double lambda; -}; - -} // namespace regression -} // namespace mlpack - -// Include implementation. -#include "logistic_regression_impl.hpp" - -#endif // MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_function.hpp b/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_function.hpp deleted file mode 100644 index e53193090..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_function.hpp +++ /dev/null @@ -1,179 +0,0 @@ -/** - * @file logistic_regression_function.hpp - * @author Sumedh Ghaisas - * - * Implementation of the logistic regression function, which is meant to be - * optimized by a separate optimizer class that takes LogisticRegressionFunction - * as its FunctionType class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_FUNCTION_HPP -#define MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_FUNCTION_HPP - -#include - -namespace mlpack { -namespace regression { - -/** - * The log-likelihood function for the logistic regression objective function. - * This is used by various mlpack optimizers to train a logistic regression - * model. - */ -template -class LogisticRegressionFunction -{ - public: - LogisticRegressionFunction(const MatType& predictors, - const arma::Row& responses, - const double lambda = 0); - - LogisticRegressionFunction(const MatType& predictors, - const arma::Row& responses, - const arma::vec& initialPoint, - const double lambda = 0); - - //! Return the initial point for the optimization. - const arma::mat& InitialPoint() const { return initialPoint; } - //! Modify the initial point for the optimization. - arma::mat& InitialPoint() { return initialPoint; } - - //! Return the regularization parameter (lambda). - const double& Lambda() const { return lambda; } - //! Modify the regularization parameter (lambda). - double& Lambda() { return lambda; } - - //! Return the matrix of predictors. - const MatType& Predictors() const { return predictors; } - //! Return the vector of responses. - const arma::Row& Responses() const { return responses; } - - /** - * Shuffle the order of function visitation. This may be called by the optimizer. - */ - void Shuffle(); - - /** - * Evaluate the logistic regression log-likelihood function with the given - * parameters. Note that if a point has 0 probability of being classified - * directly with the given parameters, then Evaluate() will return nan (this - * is kind of a corner case and should not happen for reasonable models). - * - * The optimum (minimum) of this function is 0.0, and occurs when each point - * is classified correctly with very high probability. - * - * @param parameters Vector of logistic regression parameters. - */ - double Evaluate(const arma::mat& parameters) const; - - /** - * Evaluate the logistic regression log-likelihood function with the given - * parameters using the given batch size from the given point index. This is - * useful for optimizers such as SGD, which require a separable objective - * function. Note that if the points have 0 probability of being classified - * correctly with the given parameters, then Evaluate() will return nan (this - * is kind of a corner case and should not happen for reasonable models). - * - * The optimum (minimum) of this function is 0.0, and occurs when the points are - * classified correctly with very high probability. - * - * @param parameters Vector of logistic regression parameters. - * @param begin Index of the starting point to use for objective function - * evaluation. - * @param batchSize Number of points to be passed at a time to use for - * objective function evaluation. - */ - double Evaluate(const arma::mat& parameters, - const size_t begin, - const size_t batchSize = 1) const; - - /** - * Evaluate the gradient of the logistic regression log-likelihood function - * with the given parameters. - * - * @param parameters Vector of logistic regression parameters. - * @param gradient Vector to output gradient into. - */ - void Gradient(const arma::mat& parameters, arma::mat& gradient) const; - - /** - * Evaluate the gradient of the logistic regression log-likelihood function - * with the given parameters, for the given batch size from a given point the - * in dataset. This is useful for optimizers such as SGD, which require a - * separable objective function. - * - * @param parameters Vector of logistic regression parameters. - * @param begin Index of the starting point to use for objective function - * gradient evaluation. - * @param gradient Vector to output gradient into. - * @param batchSize Number of points to be processed as a batch for objective - * function gradient evaluation. - */ - template - void Gradient(const arma::mat& parameters, - const size_t begin, - GradType& gradient, - const size_t batchSize = 1) const; - - /** - * Evaluate the gradient of the logistic regression log-likelihood function - * with the given parameters, and with respect to only one feature in the - * dataset. This is useful for optimizers such as SCD, which require - * partial gradients. - * - * @param parameters Vector of logistic regression parameters. - * @param j Index of the feature with respect to which the gradient is to - * be computed. - * @param gradient Sparse matrix to output gradient into. - */ - void PartialGradient(const arma::mat& parameters, - const size_t j, - arma::sp_mat& gradient) const; - - /** - * Evaluate the objective function and gradient of the logistic regression - * log-likelihood function simultaneously with the given parameters. - */ - template - double EvaluateWithGradient(const arma::mat& parameters, - GradType& gradient) const; - - template - double EvaluateWithGradient(const arma::mat& parameters, - const size_t begin, - GradType& gradient, - const size_t batchSize = 1) const; - - //! Return the initial point for the optimization. - const arma::mat& GetInitialPoint() const { return initialPoint; } - - //! Return the number of separable functions (the number of predictor points). - size_t NumFunctions() const { return predictors.n_cols; } - - //! Return the number of features(add 1 for the intercept term). - size_t NumFeatures() const { return predictors.n_rows + 1; } - - private: - //! The initial point, from which to start the optimization. - arma::mat initialPoint; - //! The matrix of data points (predictors). This is an alias until shuffling - //! is done. - MatType predictors; - //! The vector of responses to the input data points. This is an alias until - //! shuffling is done. - arma::Row responses; - //! The regularization parameter for L2-regularization. - double lambda; -}; - -} // namespace regression -} // namespace mlpack - -// Include implementation. -#include "logistic_regression_function_impl.hpp" - -#endif // MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_function_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_function_impl.hpp deleted file mode 100644 index ab67543fd..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_function_impl.hpp +++ /dev/null @@ -1,303 +0,0 @@ -/** - * @file logistic_regression_function.cpp - * @author Sumedh Ghaisas - * - * Implementation of the LogisticRegressionFunction class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LOGISTIC_REGRESSION_FUNCTION_IMPL_HPP -#define MLPACK_METHODS_LOGISTIC_REGRESSION_FUNCTION_IMPL_HPP - -// In case it hasn't been included yet. -#include "logistic_regression_function.hpp" - -namespace mlpack { -namespace regression { - -template -LogisticRegressionFunction::LogisticRegressionFunction( - const MatType& predictors, - const arma::Row& responses, - const double lambda) : - // We promise to be well-behaved... the elements won't be modified. - predictors(math::MakeAlias(const_cast(predictors), false)), - responses(math::MakeAlias(const_cast&>(responses), - false)), - lambda(lambda) -{ - initialPoint = arma::rowvec(predictors.n_rows + 1, arma::fill::zeros); - - // Sanity check. - if (responses.n_elem != predictors.n_cols) - { - Log::Fatal << "LogisticRegressionFunction::LogisticRegressionFunction(): " - << "predictors matrix has " << predictors.n_cols << " points, but " - << "responses vector has " << responses.n_elem << " elements (should be" - << " " << predictors.n_cols << ")!" << std::endl; - } -} - -template -LogisticRegressionFunction::LogisticRegressionFunction( - const MatType& predictors, - const arma::Row& responses, - const arma::vec& initialPoint, - const double lambda) : - initialPoint(initialPoint), - // We promise to be well-behaved... the elements won't be modified. - predictors(math::MakeAlias(const_cast(predictors), false)), - responses(math::MakeAlias(const_cast&>(responses), - false)), - lambda(lambda) -{ - // To check if initialPoint is compatible with predictors. - if (initialPoint.n_rows != (predictors.n_rows + 1) || - initialPoint.n_cols != 1) - this->initialPoint = arma::rowvec(predictors.n_rows + 1, arma::fill::zeros); -} - -/** - * Shuffle the datapoints. - */ -template -void LogisticRegressionFunction::Shuffle() -{ - MatType newPredictors; - arma::Row newResponses; - - math::ShuffleData(predictors, responses, newPredictors, newResponses); - - // If we are an alias, make sure we don't write to the original data. - math::ClearAlias(predictors); - math::ClearAlias(responses); - - // Take ownership of the new data. - predictors = std::move(newPredictors); - responses = std::move(newResponses); -} - -/** - * Evaluate the logistic regression objective function given the estimated - * parameters. - */ -template -double LogisticRegressionFunction::Evaluate( - const arma::mat& parameters) const -{ - // The objective function is the log-likelihood function (w is the parameters - // vector for the model; y is the responses; x is the predictors; sig() is the - // sigmoid function): - // f(w) = sum(y log(sig(w'x)) + (1 - y) log(sig(1 - w'x))). - // We want to minimize this function. L2-regularization is just lambda - // multiplied by the squared l2-norm of the parameters then divided by two. - - // For the regularization, we ignore the first term, which is the intercept - // term and take every term except the last one in the decision variable. - const double regularization = 0.5 * lambda * - arma::dot(parameters.tail_cols(parameters.n_elem - 1), - parameters.tail_cols(parameters.n_elem - 1)); - - // Calculate vectors of sigmoids. The intercept term is parameters(0, 0) and - // does not need to be multiplied by any of the predictors. - const arma::rowvec sigmoid = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + - parameters.tail_cols(parameters.n_elem - 1) * predictors))); - - // Assemble full objective function. Often the objective function and the - // regularization as given are divided by the number of features, but this - // doesn't actually affect the optimization result, so we'll just ignore those - // terms for computational efficiency. Note that the conversion causes some - // copy and slowdown, but this is so negligible compared to the rest of the - // calculation it is not worth optimizing for. - const double result = arma::accu(arma::log(1.0 - - arma::conv_to::from(responses) + sigmoid % - (2 * arma::conv_to::from(responses) - 1.0))); - - // Invert the result, because it's a minimization. - return regularization - result; -} - -/** - * Evaluate the logistic regression objective function given the estimated - * parameters for a given batch from a given point. - */ -template -double LogisticRegressionFunction::Evaluate( - const arma::mat& parameters, - const size_t begin, - const size_t batchSize) const -{ - // Calculate the regularization term. - const double regularization = lambda * - (batchSize / (2.0 * predictors.n_cols)) * - arma::dot(parameters.tail_cols(parameters.n_elem - 1), - parameters.tail_cols(parameters.n_elem - 1)); - - // Calculate the sigmoid function values. - const arma::rowvec sigmoid = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + - parameters.tail_cols(parameters.n_elem - 1) * - predictors.cols(begin, begin + batchSize - 1)))); - - // Compute the objective for the given batch size from a given point. - arma::rowvec respD = arma::conv_to::from(responses.subvec(begin, - begin + batchSize - 1)); - const double result = arma::accu(arma::log(1.0 - respD + sigmoid % - (2 * respD - 1.0))); - - // Invert the result, because it's a minimization. - return regularization - result; -} - -//! Evaluate the gradient of the logistic regression objective function. -template -void LogisticRegressionFunction::Gradient( - const arma::mat& parameters, - arma::mat& gradient) const -{ - // Regularization term. - arma::mat regularization; - regularization = lambda * parameters.tail_cols(parameters.n_elem - 1); - - const arma::rowvec sigmoids = (1 / (1 + arma::exp(-parameters(0, 0) - - parameters.tail_cols(parameters.n_elem - 1) * predictors))); - - gradient.set_size(arma::size(parameters)); - gradient[0] = -arma::accu(responses - sigmoids); - gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses) * - predictors.t() + regularization; -} - -//! Evaluate the gradient of the logistic regression objective function for a -//! given batch size. -template -template -void LogisticRegressionFunction::Gradient( - const arma::mat& parameters, - const size_t begin, - GradType& gradient, - const size_t batchSize) const -{ - // Regularization term. - arma::mat regularization; - regularization = lambda * parameters.tail_cols(parameters.n_elem - 1) - / predictors.n_cols * batchSize; - - const arma::rowvec exponents = parameters(0, 0) + - parameters.tail_cols(parameters.n_elem - 1) * - predictors.cols(begin, begin + batchSize - 1); - // Calculating the sigmoid function values. - const arma::rowvec sigmoids = 1.0 / (1.0 + arma::exp(-exponents)); - - gradient.set_size(parameters.n_rows, parameters.n_cols); - gradient[0] = -arma::accu(responses.subvec(begin, begin + batchSize - 1) - - sigmoids); - gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - - responses.subvec(begin, begin + batchSize - 1)) * - predictors.cols(begin, begin + batchSize - 1).t() + regularization; -} - -/** - * Evaluate the partial gradient of the logistic regression objective - * function with respect to the individual features in the parameter. - */ -template -void LogisticRegressionFunction::PartialGradient( - const arma::mat& parameters, - const size_t j, - arma::sp_mat& gradient) const -{ - const arma::rowvec diffs = responses - (1 / (1 + arma::exp(-parameters(0, 0) - - parameters.tail_cols(parameters.n_elem - 1) * predictors))); - - gradient.set_size(arma::size(parameters)); - - if (j == 0) - { - gradient[j] = -arma::accu(diffs); - } - else - { - gradient[j] = arma::dot(-predictors.row(j - 1), diffs) + lambda * - parameters(0, j); - } -} - -template -template -double LogisticRegressionFunction::EvaluateWithGradient( - const arma::mat& parameters, - GradType& gradient) const -{ - // Regularization term. - arma::mat regularization = lambda * - parameters.tail_cols(parameters.n_elem - 1); - - const double objectiveRegularization = lambda / 2.0 * - arma::dot(parameters.tail_cols(parameters.n_elem - 1), - parameters.tail_cols(parameters.n_elem - 1)); - - // Calculate the sigmoid function values. - const arma::rowvec sigmoids = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + - parameters.tail_cols(parameters.n_elem - 1) * predictors))); - - gradient.set_size(arma::size(parameters)); - gradient[0] = -arma::accu(responses - sigmoids); - gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - responses) * - predictors.t() + regularization; - - // Now compute the objective function using the sigmoids. - double result = arma::accu(arma::log(1.0 - - arma::conv_to::from(responses) + sigmoids % - (2 * arma::conv_to::from(responses) - 1.0))); - - // Invert the result, because it's a minimization. - return objectiveRegularization - result; -} - -template -template -double LogisticRegressionFunction::EvaluateWithGradient( - const arma::mat& parameters, - const size_t begin, - GradType& gradient, - const size_t batchSize) const -{ - // Regularization term. - arma::mat regularization = - lambda * parameters.tail_cols(parameters.n_elem - 1) / predictors.n_cols * - batchSize; - - const double objectiveRegularization = lambda * - (batchSize / (2.0 * predictors.n_cols)) * - arma::dot(parameters.tail_cols(parameters.n_elem - 1), - parameters.tail_cols(parameters.n_elem - 1)); - - // Calculate the sigmoid function values. - const arma::rowvec sigmoids = 1.0 / (1.0 + arma::exp(-(parameters(0, 0) + - parameters.tail_cols(parameters.n_elem - 1) * - predictors.cols(begin, begin + batchSize - 1)))); - - gradient.set_size(parameters.n_rows, parameters.n_cols); - gradient[0] = -arma::accu(responses.subvec(begin, begin + batchSize - 1) - - sigmoids); - gradient.tail_cols(parameters.n_elem - 1) = (sigmoids - - responses.subvec(begin, begin + batchSize - 1)) * - predictors.cols(begin, begin + batchSize - 1).t() + regularization; - - // Now compute the objective function using the sigmoids. - arma::rowvec respD = arma::conv_to::from(responses.subvec(begin, - begin + batchSize - 1)); - const double result = arma::accu(arma::log(1.0 - respD + sigmoids % - (2 * respD - 1.0))); - - // Invert the result, because it's a minimization. - return objectiveRegularization - result; -} - -} // namespace regression -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_impl.hpp deleted file mode 100644 index 1973806fa..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/logistic_regression/logistic_regression_impl.hpp +++ /dev/null @@ -1,182 +0,0 @@ -/** - * @file logistic_regression_impl.hpp - * @author Sumedh Ghaisas - * @author Arun Reddy - * - * Implementation of the LogisticRegression class. This implementation supports - * L2-regularization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP -#define MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP - -// In case it hasn't been included yet. -#include "logistic_regression.hpp" - -namespace mlpack { -namespace regression { - -template -LogisticRegression::LogisticRegression( - const MatType& predictors, - const arma::Row& responses, - const double lambda) : - parameters(arma::rowvec(predictors.n_rows + 1, arma::fill::zeros)), - lambda(lambda) -{ - Train(predictors, responses); -} - -template -LogisticRegression::LogisticRegression( - const MatType& predictors, - const arma::Row& responses, - const arma::rowvec& initialPoint, - const double lambda) : - parameters(initialPoint), - lambda(lambda) -{ - Train(predictors, responses); -} - -template -LogisticRegression::LogisticRegression( - const size_t dimensionality, - const double lambda) : - parameters(arma::rowvec(dimensionality + 1, arma::fill::zeros)), - lambda(lambda) -{ - // No training to do here. -} - -template -template -LogisticRegression::LogisticRegression( - const MatType& predictors, - const arma::Row& responses, - OptimizerType& optimizer, - const double lambda) : - parameters(arma::rowvec(predictors.n_rows + 1, arma::fill::zeros)), - lambda(lambda) -{ - Train(predictors, responses, optimizer); -} - -template -template -double LogisticRegression::Train(const MatType& predictors, - const arma::Row& responses) -{ - OptimizerType optimizer; - return Train(predictors, responses, optimizer); -} - -template -template -double LogisticRegression::Train( - const MatType& predictors, - const arma::Row& responses, - OptimizerType& optimizer) -{ - LogisticRegressionFunction errorFunction(predictors, - responses, - lambda); - errorFunction.InitialPoint() = parameters; - - Timer::Start("logistic_regression_optimization"); - const double out = optimizer.Optimize(errorFunction, parameters); - Timer::Stop("logistic_regression_optimization"); - - Log::Info << "LogisticRegression::LogisticRegression(): final objective of " - << "trained model is " << out << "." << std::endl; - - return out; -} - -template -template -size_t LogisticRegression::Classify(const VecType& point, - const double decisionBoundary) - const -{ - return size_t(1.0 / (1.0 + std::exp(-parameters(0) - arma::dot(point, - parameters.tail_cols(parameters.n_elem - 1)))) + - (1.0 - decisionBoundary)); -} - -template -void LogisticRegression::Classify(const MatType& dataset, - arma::Row& labels, - const double decisionBoundary) const -{ - // Calculate sigmoid function for each point. The (1.0 - decisionBoundary) - // term correctly sets an offset so that floor() returns 0 or 1 correctly. - labels = arma::conv_to>::from((1.0 / - (1.0 + arma::exp(-parameters(0) - - parameters.tail_cols(parameters.n_elem - 1) * dataset))) + - (1.0 - decisionBoundary)); -} - -template -void LogisticRegression::Classify(const MatType& dataset, - arma::mat& probabilities) const -{ - // Set correct size of output matrix. - probabilities.set_size(2, dataset.n_cols); - - probabilities.row(1) = 1.0 / (1.0 + arma::exp(-parameters(0) - - parameters.tail_cols(parameters.n_elem - 1) * dataset)); - probabilities.row(0) = 1.0 - probabilities.row(1); -} - -template -double LogisticRegression::ComputeError( - const MatType& predictors, - const arma::Row& responses) const -{ - // Construct a new error function. - LogisticRegressionFunction<> newErrorFunction(predictors, responses, - lambda); - - return newErrorFunction.Evaluate(parameters); -} - -template -double LogisticRegression::ComputeAccuracy( - const MatType& predictors, - const arma::Row& responses, - const double decisionBoundary) const -{ - // Predict responses using the current model. - arma::Row tempResponses; - Classify(predictors, tempResponses, decisionBoundary); - - // Count the number of responses that were correct. - size_t count = 0; - for (size_t i = 0; i < responses.n_elem; i++) - { - if (responses(i) == tempResponses(i)) - count++; - } - - return (double) (count * 100) / responses.n_elem; -} - -template -template -void LogisticRegression::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(parameters); - ar & BOOST_SERIALIZATION_NVP(lambda); -} - -} // namespace regression -} // namespace mlpack - -#endif // MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/lsh/lsh_search.hpp b/src/sdk/mlpack/include/mlpack/methods/lsh/lsh_search.hpp deleted file mode 100644 index d906db147..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/lsh/lsh_search.hpp +++ /dev/null @@ -1,484 +0,0 @@ -/** - * @file lsh_search.hpp - * @author Parikshit Ram - * - * Defines the LSHSearch class, which performs an approximate - * nearest neighbor search for a queries in a query set - * over a given dataset using Locality-sensitive hashing - * with 2-stable distributions. - * - * The details of this method can be found in the following paper: - * - * @inproceedings{datar2004locality, - * title={Locality-sensitive hashing scheme based on p-stable distributions}, - * author={Datar, M. and Immorlica, N. and Indyk, P. and Mirrokni, V.S.}, - * booktitle= - * {Proceedings of the 12th Annual Symposium on Computational Geometry}, - * pages={253--262}, - * year={2004}, - * organization={ACM} - * } - * - * Additionally, the class implements Multiprobe LSH, which improves - * approximation results during the search for approximate nearest neighbors. - * The Multiprobe LSH algorithm was presented in the paper: - * - * @inproceedings{Lv2007multiprobe, - * tile={Multi-probe LSH: efficient indexing for high-dimensional similarity - * search}, - * author={Lv, Qin and Josephson, William and Wang, Zhe and Charikar, Moses and - * Li, Kai}, - * booktitle={Proceedings of the 33rd international conference on Very large - * data bases}, - * year={2007}, - * pages={950--961} - * } - * - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_LSH_SEARCH_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_LSH_SEARCH_HPP - -#include - -#include -#include - -#include - -namespace mlpack { -namespace neighbor { - -/** - * The LSHSearch class; this class builds a hash on the reference set and uses - * this hash to compute the distance-approximate nearest-neighbors of the given - * queries. - * - * @tparam SortPolicy The sort policy for distances; see NearestNeighborSort. - */ -template -class LSHSearch -{ - public: - /** - * This function initializes the LSH class. It builds the hash on the - * reference set with 2-stable distributions. See the individual functions - * performing the hashing for details on how the hashing is done. In order to - * avoid copying the reference set, it is suggested to pass that parameter - * with std::move(). - * - * @param referenceSet Set of reference points and the set of queries. - * @param projections Cube of projection tables. For a cube of size (a, b, c) - * we set numProj = a, numTables = c. b is the reference set - * dimensionality. - * @param hashWidth The width of hash for every table. If 0 (the default) is - * provided, then the hash width is automatically obtained by computing - * the average pairwise distance of 25 pairs. This should be a reasonable - * upper bound on the nearest-neighbor distance in general. - * @param secondHashSize The size of the second hash table. This should be a - * large prime number. - * @param bucketSize The size of the bucket in the second hash table. This is - * the maximum number of points that can be hashed into single bucket. A - * value of 0 indicates that there is no limit (so the second hash table - * can be arbitrarily large---be careful!). - */ - LSHSearch(arma::mat referenceSet, - const arma::cube& projections, - const double hashWidth = 0.0, - const size_t secondHashSize = 99901, - const size_t bucketSize = 500); - - /** - * This function initializes the LSH class. It builds the hash one the - * reference set using the provided projections. See the individual functions - * performing the hashing for details on how the hashing is done. In order to - * avoid copying the reference set, consider passing the set with std::move(). - * - * @param referenceSet Set of reference points and the set of queries. - * @param numProj Number of projections in each hash table (anything between - * 10-50 might be a decent choice). - * @param numTables Total number of hash tables (anything between 10-20 - * should suffice). - * @param hashWidth The width of hash for every table. If 0 (the default) is - * provided, then the hash width is automatically obtained by computing - * the average pairwise distance of 25 pairs. This should be a reasonable - * upper bound on the nearest-neighbor distance in general. - * @param secondHashSize The size of the second hash table. This should be a - * large prime number. - * @param bucketSize The size of the bucket in the second hash table. This is - * the maximum number of points that can be hashed into single bucket. A - * value of 0 indicates that there is no limit (so the second hash table - * can be arbitrarily large---be careful!). - */ - LSHSearch(arma::mat referenceSet, - const size_t numProj, - const size_t numTables, - const double hashWidth = 0.0, - const size_t secondHashSize = 99901, - const size_t bucketSize = 500); - - /** - * Create an untrained LSH model. Be sure to call Train() before calling - * Search(); otherwise, an exception will be thrown when Search() is called. - */ - LSHSearch(); - - /** - * Copy the given LSH model. - * - * @param other Other LSH model to copy. - */ - LSHSearch(const LSHSearch& other); - - /** - * Take ownership of the given LSH model. - * - * @param other Other LSH model to take ownership of. - */ - LSHSearch(LSHSearch&& other); - - /** - * Copy the given LSH model. - * - * @param other Other LSH model to copy. - */ - LSHSearch& operator=(const LSHSearch& other); - - /** - * Take ownership of the given LSH model. - * - * @param other Other LSH model to take ownership of. - */ - LSHSearch& operator=(LSHSearch&& other); - - /** - * Train the LSH model on the given dataset. If a correctly-sized projection - * cube is not provided, this means building new hash tables. Otherwise, we - * use the projections provided by the user. In order to avoid copying the - * reference set, consider passing that parameter with std::move(). - * - * @param referenceSet Set of reference points and the set of queries. - * @param numProj Number of projections in each hash table (anything between - * 10-50 might be a decent choice). - * @param numTables Total number of hash tables (anything between 10-20 - * should suffice). - * @param hashWidth The width of hash for every table. If 0 (the default) is - * provided, then the hash width is automatically obtained by computing - * the average pairwise distance of 25 pairs. This should be a reasonable - * upper bound on the nearest-neighbor distance in general. - * @param secondHashSize The size of the second hash table. This should be a - * large prime number. - * @param bucketSize The size of the bucket in the second hash table. This is - * the maximum number of points that can be hashed into single bucket. A - * value of 0 indicates that there is no limit (so the second hash table - * can be arbitrarily large---be careful!). - * @param projections Cube of projection tables. For a cube of size (a, b, c) - * we set numProj = a, numTables = c. b is the reference set - * dimensionality. - */ - void Train(arma::mat referenceSet, - const size_t numProj, - const size_t numTables, - const double hashWidth = 0.0, - const size_t secondHashSize = 99901, - const size_t bucketSize = 500, - const arma::cube& projection = arma::cube()); - - /** - * Compute the nearest neighbors of the points in the given query set and - * store the output in the given matrices. The matrices will be set to the - * size of n columns by k rows, where n is the number of points in the query - * dataset and k is the number of neighbors being searched for. - * - * @param querySet Set of query points. - * @param k Number of neighbors to search for. - * @param resultingNeighbors Matrix storing lists of neighbors for each query - * point. - * @param distances Matrix storing distances of neighbors for each query - * point. - * @param numTablesToSearch This parameter allows the user to have control - * over the number of hash tables to be searched. This allows - * the user to pick the number of tables it can afford for the time - * available without having to build hashing for every table size. - * By default, this is set to zero in which case all tables are - * considered. - * @param T The number of additional probing bins to examine with multiprobe - * LSH. If T = 0, classic single-probe LSH is run (default). - */ - void Search(const arma::mat& querySet, - const size_t k, - arma::Mat& resultingNeighbors, - arma::mat& distances, - const size_t numTablesToSearch = 0, - const size_t T = 0); - - /** - * Compute the nearest neighbors and store the output in the given matrices. - * The matrices will be set to the size of n columns by k rows, where n is - * the number of points in the query dataset and k is the number of neighbors - * being searched for. - * - * @param k Number of neighbors to search for. - * @param resultingNeighbors Matrix storing lists of neighbors for each query - * point. - * @param distances Matrix storing distances of neighbors for each query - * point. - * @param numTablesToSearch This parameter allows the user to have control - * over the number of hash tables to be searched. This allows - * the user to pick the number of tables it can afford for the time - * available without having to build hashing for every table size. - * By default, this is set to zero in which case all tables are - * considered. - */ - void Search(const size_t k, - arma::Mat& resultingNeighbors, - arma::mat& distances, - const size_t numTablesToSearch = 0, - size_t T = 0); - - /** - * Compute the recall (% of neighbors found) given the neighbors returned by - * LSHSearch::Search and a "ground truth" set of neighbors. The recall - * returned will be in the range [0, 1]. - * - * @param foundNeighbors Set of neighbors to compute recall of. - * @param realNeighbors Set of "ground truth" neighbors to compute recall - * against. - */ - static double ComputeRecall(const arma::Mat& foundNeighbors, - const arma::Mat& realNeighbors); - - /** - * Serialize the LSH model. - * - * @param ar Archive to serialize to. - */ - template - void serialize(Archive& ar, const unsigned int version); - - //! Return the number of distance evaluations performed. - size_t DistanceEvaluations() const { return distanceEvaluations; } - //! Modify the number of distance evaluations performed. - size_t& DistanceEvaluations() { return distanceEvaluations; } - - //! Return the reference dataset. - const arma::mat& ReferenceSet() const { return referenceSet; } - - //! Get the number of projections. - size_t NumProjections() const { return projections.n_slices; } - - //! Get the offsets 'b' for each of the projections. (One 'b' per column.) - const arma::mat& Offsets() const { return offsets; } - - //! Get the weights of the second hash. - const arma::vec& SecondHashWeights() const { return secondHashWeights; } - - //! Get the bucket size of the second hash. - size_t BucketSize() const { return bucketSize; } - - //! Get the second hash table. - const std::vector>& SecondHashTable() const - { return secondHashTable; } - - //! Get the projection tables. - const arma::cube& Projections() { return projections; } - - //! Change the projection tables (this retrains the LSH model). - void Projections(const arma::cube& projTables) - { - // Simply call Train() with the given projection tables. - Train(referenceSet, numProj, numTables, hashWidth, secondHashSize, - bucketSize, projTables); - } - - private: - /** - * This function takes a query and hashes it into each of the hash tables to - * get keys for the query and then the key is hashed to a bucket of the second - * hash table and all the points (if any) in those buckets are collected as - * the potential neighbor candidates. - * - * @param queryPoint The query point currently being processed. - * @param referenceIndices The list of neighbor candidates obtained from - * hashing the query into all the hash tables and eventually into - * multiple buckets of the second hash table. - * @param numTablesToSearch The number of tables to perform the search in. If - * 0, all tables are searched. - * @param T The number of additional probing bins for multiprobe LSH. If 0, - * single-probe is used. - */ - template - void ReturnIndicesFromTable(const VecType& queryPoint, - arma::uvec& referenceIndices, - size_t numTablesToSearch, - const size_t T) const; - - /** - * This is a helper function that computes the distance of the query to the - * neighbor candidates and appropriately stores the best 'k' candidates. This - * is specific to the monochromatic search case, where the query set is the - * reference set. - * - * @param queryIndex The index of the query in question - * @param referenceIndices The vector of indices of candidate neighbors for - * the query. - * @param k Number of neighbors to search for. - * @param neighbors Matrix holding output neighbors. - * @param distances Matrix holding output distances. - */ - void BaseCase(const size_t queryIndex, - const arma::uvec& referenceIndices, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) const; - - /** - * This is a helper function that computes the distance of the query to the - * neighbor candidates and appropriately stores the best 'k' candidates. This - * is specific to bichromatic search, where the query set is not the same as - * the reference set. - * - * @param queryIndex The index of the query in question - * @param referenceIndices The vector of indices of candidate neighbors for - * the query. - * @param k Number of neighbors to search for. - * @param querySet Set of query points. - * @param neighbors Matrix holding output neighbors. - * @param distances Matrix holding output distances. - */ - void BaseCase(const size_t queryIndex, - const arma::uvec& referenceIndices, - const size_t k, - const arma::mat& querySet, - arma::Mat& neighbors, - arma::mat& distances) const; - - /** - * This function implements the core idea behind Multiprobe LSH. It is called - * by ReturnIndicesFromTables when T > 0. Given a query's code and its - * projection location, GetAdditionalProbingBins will calculate the T most - * likely alternative bin codes (other than queryCode) where a query's - * neighbors might be found in. - * - * @param queryCode vector containing the numProj-dimensional query code. - * @param queryCodeNotFloored vector containing the projection location of the - * query. - * @param T number of additional probing bins. - * @param additionalProbingBins matrix. Each column will hold one additional - * bin. - */ - void GetAdditionalProbingBins(const arma::vec& queryCode, - const arma::vec& queryCodeNotFloored, - const size_t T, - arma::mat& additionalProbingBins) const; - - /** - * Returns the score of a perturbation vector generated by perturbation set A. - * The score of a pertubation set (vector) is the sum of scores of the - * participating actions. - * @param A perturbation set to compute the score of. - * @param scores vector containing score of each perturbation. - */ - double PerturbationScore(const std::vector& A, - const arma::vec& scores) const; - - /** - * Inline function used by GetAdditionalProbingBins. The vector shift - * operation replaces the largest element of a vector A with (largest element) - * + 1. Returns true if resulting vector is valid, otherwise false. - * - * @param A perturbation set to shift. - */ - bool PerturbationShift(std::vector& A) const; - - /** - * Inline function used by GetAdditionalProbingBins. The vector expansion - * operation adds the element [1 + (largest_element)] to a vector A, where - * largest_element is the largest element of A. Returns true if resulting - * vector is valid, otherwise false. - * - * @param A perturbation set to expand. - */ - bool PerturbationExpand(std::vector& A) const; - - /** - * Return true if perturbation set A is valid. A perturbation set is invalid - * if it contains two (or more) actions for the same dimension or dimensions - * that are larger than the queryCode's dimensions. - * - * @param A perturbation set to validate. - */ - bool PerturbationValid(const std::vector& A) const; - - //! Reference dataset. - arma::mat referenceSet; - - //! The number of projections. - size_t numProj; - //! The number of hash tables. - size_t numTables; - - //! The arma::cube containing the projection matrix of each table. - arma::cube projections; // should be [numProj x dims] x numTables slices - - //! The list of the offsets 'b' for each of the projection for each table. - arma::mat offsets; // should be numProj x numTables - - //! The hash width. - double hashWidth; - - //! The big prime representing the size of the second hash. - size_t secondHashSize; - - //! The weights of the second hash. - arma::vec secondHashWeights; - - //! The bucket size of the second hash. - size_t bucketSize; - - //! The final hash table; should be (< secondHashSize) vectors each with - //! (<= bucketSize) elements. - std::vector> secondHashTable; - - //! The number of elements present in each hash bucket; should be - //! secondHashSize. - arma::Col bucketContentSize; - - //! For a particular hash value, points to the row in secondHashTable - //! corresponding to this value. Length secondHashSize. - arma::Col bucketRowInHashTable; - - //! The number of distance evaluations. - size_t distanceEvaluations; - - //! Candidate represents a possible candidate neighbor (distance, index). - typedef std::pair Candidate; - - //! Compare two candidates based on the distance. - struct CandidateCmp { - bool operator()(const Candidate& c1, const Candidate& c2) - { - return !SortPolicy::IsBetter(c2.first, c1.first); - }; - }; - - //! Use a priority queue to represent the list of candidate neighbors. - typedef std::priority_queue, CandidateCmp> - CandidateList; -}; // class LSHSearch - -} // namespace neighbor -} // namespace mlpack - -//! Set the serialization version of the LSHSearch class. -BOOST_TEMPLATE_CLASS_VERSION(template, - mlpack::neighbor::LSHSearch, 1); - -// Include implementation. -#include "lsh_search_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/lsh/lsh_search_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/lsh/lsh_search_impl.hpp deleted file mode 100644 index 82a239a83..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/lsh/lsh_search_impl.hpp +++ /dev/null @@ -1,1145 +0,0 @@ -/** - * @file lsh_search_impl.hpp - * @author Parikshit Ram - * - * Implementation of the LSHSearch class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_LSH_SEARCH_IMPL_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_LSH_SEARCH_IMPL_HPP - -#include -#include - -namespace mlpack { -namespace neighbor { - -// Construct the object with random tables -template -LSHSearch:: -LSHSearch(arma::mat referenceSet, - const size_t numProj, - const size_t numTables, - const double hashWidthIn, - const size_t secondHashSize, - const size_t bucketSize) : - numProj(numProj), - numTables(numTables), - hashWidth(hashWidthIn), - secondHashSize(secondHashSize), - bucketSize(bucketSize), - distanceEvaluations(0) -{ - // Pass work to training function. - Train(referenceSet, numProj, numTables, hashWidthIn, secondHashSize, - bucketSize); -} - -// Construct the object with given tables -template -LSHSearch:: -LSHSearch(arma::mat referenceSet, - const arma::cube& projections, - const double hashWidthIn, - const size_t secondHashSize, - const size_t bucketSize) : - numProj(projections.n_cols), - numTables(projections.n_slices), - hashWidth(hashWidthIn), - secondHashSize(secondHashSize), - bucketSize(bucketSize), - distanceEvaluations(0) -{ - // Pass work to training function. - Train(std::move(referenceSet), numProj, numTables, hashWidthIn, - secondHashSize, bucketSize, projections); -} - -// Empty constructor. -template -LSHSearch::LSHSearch() : - numProj(0), - numTables(0), - hashWidth(0), - secondHashSize(99901), - bucketSize(500), - distanceEvaluations(0) -{ -} - -// Copy constructor. -template -LSHSearch::LSHSearch(const LSHSearch& other) : - referenceSet(other.referenceSet), // Copy the other set. - numProj(other.numProj), - numTables(other.numTables), - projections(other.projections), - offsets(other.offsets), - hashWidth(other.hashWidth), - secondHashSize(other.secondHashSize), - secondHashWeights(other.secondHashWeights), - bucketSize(other.bucketSize), - secondHashTable(other.secondHashTable), - bucketContentSize(other.bucketContentSize), - bucketRowInHashTable(other.bucketRowInHashTable), - distanceEvaluations(other.distanceEvaluations) -{ - // Nothing to do. -} - -// Move constructor. -template -LSHSearch::LSHSearch(LSHSearch&& other) : - referenceSet(std::move(other.referenceSet)), - numProj(other.numProj), - numTables(other.numTables), - projections(std::move(other.projections)), - offsets(std::move(other.offsets)), - hashWidth(other.hashWidth), - secondHashSize(other.secondHashSize), - secondHashWeights(std::move(other.secondHashWeights)), - bucketSize(other.bucketSize), - secondHashTable(std::move(other.secondHashTable)), - bucketContentSize(std::move(other.bucketContentSize)), - bucketRowInHashTable(std::move(other.bucketRowInHashTable)), - distanceEvaluations(other.distanceEvaluations) -{ - // Reset other model to defaults. - other.numProj = 0; - other.numTables = 0; - other.hashWidth = 0; - other.secondHashSize = 99901; - other.bucketSize = 500; - other.distanceEvaluations = 0; -} - -// Copy operator. -template -LSHSearch& LSHSearch::operator=(const LSHSearch& other) -{ - referenceSet = other.referenceSet; - numProj = other.numProj; - numTables = other.numTables; - projections = other.projections; - offsets = other.offsets; - hashWidth = other.hashWidth; - secondHashSize = other.secondHashSize; - secondHashWeights = other.secondHashWeights; - bucketSize = other.bucketSize; - secondHashTable = other.secondHashTable; - bucketContentSize = other.bucketContentSize; - bucketRowInHashTable = other.bucketRowInHashTable; - distanceEvaluations = other.distanceEvaluations; - - return *this; -} - -// Move operator. -template -LSHSearch& LSHSearch::operator=(LSHSearch&& other) -{ - referenceSet = std::move(other.referenceSet); - numProj = other.numProj; - numTables = other.numTables; - projections = std::move(other.projections); - offsets = std::move(other.offsets); - hashWidth = other.hashWidth; - secondHashSize = other.secondHashSize; - secondHashWeights = std::move(other.secondHashWeights); - bucketSize = other.bucketSize; - secondHashTable = std::move(other.secondHashTable); - bucketContentSize = std::move(other.bucketContentSize); - bucketRowInHashTable = std::move(other.bucketRowInHashTable); - distanceEvaluations = other.distanceEvaluations; - - // Reset other model to defaults. - other.numProj = 0; - other.numTables = 0; - other.hashWidth = 0; - other.secondHashSize = 99901; - other.bucketSize = 500; - other.distanceEvaluations = 0; - - return *this; -} - -// Train on a new reference set. -template -void LSHSearch::Train(arma::mat referenceSet, - const size_t numProj, - const size_t numTables, - const double hashWidthIn, - const size_t secondHashSize, - const size_t bucketSize, - const arma::cube &projection) -{ - // Set new reference set. - this->referenceSet = std::move(referenceSet); - - // Set new parameters. - this->numProj = numProj; - this->numTables = numTables; - this->hashWidth = hashWidthIn; - this->secondHashSize = secondHashSize; - this->bucketSize = bucketSize; - - if (hashWidth == 0.0) // The user has not provided any value. - { - const size_t numSamples = 25; - // Compute a heuristic hash width from the data. - for (size_t i = 0; i < numSamples; i++) - { - size_t p1 = (size_t) math::RandInt(this->referenceSet.n_cols); - size_t p2 = (size_t) math::RandInt(this->referenceSet.n_cols); - - hashWidth += std::sqrt(metric::EuclideanDistance::Evaluate( - this->referenceSet.unsafe_col(p1), - this->referenceSet.unsafe_col(p2))); - } - - hashWidth /= numSamples; - } - - Log::Info << "Hash width chosen as: " << hashWidth << std::endl; - - // Hash building procedure: - // The first level hash for a single table outputs a 'numProj'-dimensional - // integer key for each point in the set -- (key, pointID). The key creation - // details are presented below. - - // Step I: Prepare the second level hash. - - // Obtain the weights for the second hash. - secondHashWeights = arma::floor(arma::randu(numProj) * - (double) secondHashSize); - - // Instead of putting the points in the row corresponding to the bucket, we - // chose the next empty row and keep track of the row in which the bucket - // lies. This allows us to stack together and slice out the empty buckets at - // the end of the hashing. - bucketRowInHashTable.set_size(secondHashSize); - bucketRowInHashTable.fill(secondHashSize); - - // Step II: The offsets for all projections in all tables. - // Since the 'offsets' are in [0, hashWidth], we obtain the 'offsets' - // as randu(numProj, numTables) * hashWidth. - offsets.randu(numProj, numTables); - offsets *= hashWidth; - - // Step III: Obtain the 'numProj' projections for each table. - projections.clear(); // Reset projections vector. - - if (projection.n_slices == 0) // Randomly generate the tables. - { - // For L2 metric, 2-stable distributions are used, and the normal Z ~ N(0, - // 1) is a 2-stable distribution. - - // Build numTables random tables arranged in a cube. - projections.randn(this->referenceSet.n_rows, numProj, numTables); - } - else if (projection.n_slices == numTables) // Take user-defined tables. - { - projections = projection; - } - else // The user gave something wrong. - { - throw std::invalid_argument("LSHSearch::Train(): number of projection " - "tables provided must be equal to numProj"); - } - - // We will store the second hash vectors in this matrix; the second hash - // vector for table i will be held in row i. We have to use int and not - // size_t, otherwise negative numbers are cast to 0. - arma::Mat secondHashVectors(numTables, this->referenceSet.n_cols); - - for (size_t i = 0; i < numTables; i++) - { - // Step IV: create the 'numProj'-dimensional key for each point in each - // table. - - // The following code performs the task of hashing each point to a - // 'numProj'-dimensional integer key. Hence you get a ('numProj' x - // 'referenceSet.n_cols') key matrix. - // - // For a single table, let the 'numProj' projections be denoted by 'proj_i' - // and the corresponding offset be 'offset_i'. Then the key of a single - // point is obtained as: - // key = { floor(( + offset_i) / 'hashWidth') forall i } - arma::mat offsetMat = arma::repmat(offsets.unsafe_col(i), 1, - this->referenceSet.n_cols); - arma::mat hashMat = projections.slice(i).t() * (this->referenceSet); - hashMat += offsetMat; - hashMat /= hashWidth; - - // Step V: Putting the points in the 'secondHashTable' by hashing the key. - // Now we hash every key, point ID to its corresponding bucket. We must - // also normalize the hashes to the range [0, secondHashSize). - arma::rowvec unmodVector = secondHashWeights.t() * arma::floor(hashMat); - for (size_t j = 0; j < unmodVector.n_elem; ++j) - { - double shs = (double) secondHashSize; // Convenience cast. - if (unmodVector[j] >= 0.0) - { - const size_t key = size_t(fmod(unmodVector[j], shs)); - secondHashVectors(i, j) = key; - } - else - { - const double mod = fmod(-unmodVector[j], shs); - const size_t key = (mod < 1.0) ? 0 : secondHashSize - size_t(mod); - secondHashVectors(i, j) = key; - } - } - } - - // Now, using the hash vectors for each table, count the number of rows we - // have in the second hash table. - arma::Row secondHashBinCounts(secondHashSize, arma::fill::zeros); - for (size_t i = 0; i < secondHashVectors.n_elem; ++i) - secondHashBinCounts[secondHashVectors[i]]++; - - // Enforce the maximum bucket size. - const size_t effectiveBucketSize = (bucketSize == 0) ? SIZE_MAX : bucketSize; - secondHashBinCounts.transform([effectiveBucketSize](size_t val) - { return std::min(val, effectiveBucketSize); }); - - const size_t numRowsInTable = arma::accu(secondHashBinCounts > 0); - bucketContentSize.zeros(numRowsInTable); - secondHashTable.resize(numRowsInTable); - - // Next we must assign each point in each table to the right second hash - // table. - size_t currentRow = 0; - for (size_t i = 0; i < numTables; ++i) - { - // Insert the point in the corresponding row to its bucket in the - // 'secondHashTable'. - for (size_t j = 0; j < secondHashVectors.n_cols; j++) - { - // This is the bucket number. - size_t hashInd = (size_t) secondHashVectors(i, j); - // The point ID is 'j'. - - // If this is currently an empty bucket, start a new row keep track of - // which row corresponds to the bucket. - const size_t maxSize = secondHashBinCounts[hashInd]; - if (bucketRowInHashTable[hashInd] == secondHashSize) - { - bucketRowInHashTable[hashInd] = currentRow; - secondHashTable[currentRow].set_size(maxSize); - currentRow++; - } - - // If this vector in the hash table is not full, add the point. - const size_t index = bucketRowInHashTable[hashInd]; - if (bucketContentSize[index] < maxSize) - secondHashTable[index](bucketContentSize[index]++) = j; - } // Loop over all points in the reference set. - } // Loop over tables. - - Log::Info << "Final hash table size: " << numRowsInTable << " rows, with a " - << "maximum length of " << arma::max(secondHashBinCounts) << ", " - << "totaling " << arma::accu(secondHashBinCounts) << " elements." - << std::endl; -} - -// Base case where the query set is the reference set. (So, we can't return -// ourselves as the nearest neighbor.) -template -inline force_inline -void LSHSearch::BaseCase(const size_t queryIndex, - const arma::uvec& referenceIndices, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) const -{ - // Let's build the list of candidate neighbors for the given query point. - // It will be initialized with k candidates: - // (WorstDistance, referenceSet.n_cols) - const Candidate def = std::make_pair(SortPolicy::WorstDistance(), - referenceSet.n_cols); - std::vector vect(k, def); - CandidateList pqueue(CandidateCmp(), std::move(vect)); - - for (size_t j = 0; j < referenceIndices.n_elem; ++j) - { - const size_t referenceIndex = referenceIndices[j]; - // If the points are the same, skip this point. - if (queryIndex == referenceIndex) - continue; - - const double distance = metric::EuclideanDistance::Evaluate( - referenceSet.unsafe_col(queryIndex), - referenceSet.unsafe_col(referenceIndex)); - - Candidate c = std::make_pair(distance, referenceIndex); - // If this distance is better than the worst candidate, let's insert it. - if (CandidateCmp()(c, pqueue.top())) - { - pqueue.pop(); - pqueue.push(c); - } - } - - for (size_t j = 1; j <= k; j++) - { - neighbors(k - j, queryIndex) = pqueue.top().second; - distances(k - j, queryIndex) = pqueue.top().first; - pqueue.pop(); - } -} - -// Base case for bichromatic search. -template -inline force_inline -void LSHSearch::BaseCase(const size_t queryIndex, - const arma::uvec& referenceIndices, - const size_t k, - const arma::mat& querySet, - arma::Mat& neighbors, - arma::mat& distances) const -{ - // Let's build the list of candidate neighbors for the given query point. - // It will be initialized with k candidates: - // (WorstDistance, referenceSet.n_cols) - const Candidate def = std::make_pair(SortPolicy::WorstDistance(), - referenceSet.n_cols); - std::vector vect(k, def); - CandidateList pqueue(CandidateCmp(), std::move(vect)); - - for (size_t j = 0; j < referenceIndices.n_elem; ++j) - { - const size_t referenceIndex = referenceIndices[j]; - const double distance = metric::EuclideanDistance::Evaluate( - querySet.unsafe_col(queryIndex), - referenceSet.unsafe_col(referenceIndex)); - - Candidate c = std::make_pair(distance, referenceIndex); - // If this distance is better than the worst candidate, let's insert it. - if (CandidateCmp()(c, pqueue.top())) - { - pqueue.pop(); - pqueue.push(c); - } - } - - for (size_t j = 1; j <= k; j++) - { - neighbors(k - j, queryIndex) = pqueue.top().second; - distances(k - j, queryIndex) = pqueue.top().first; - pqueue.pop(); - } -} - -template -inline force_inline -double LSHSearch::PerturbationScore( - const std::vector& A, - const arma::vec& scores) const -{ - double score = 0.0; - for (size_t i = 0; i < A.size(); ++i) - if (A[i]) - score += scores(i); // add scores of non-zero indices - return score; -} - -template -inline force_inline -bool LSHSearch::PerturbationShift(std::vector& A) const -{ - size_t maxPos = 0; - for (size_t i = 0; i < A.size(); ++i) - if (A[i] == 1) // Marked true. - maxPos = i; - - if (maxPos + 1 < A.size()) // Otherwise, this is an invalid vector. - { - A[maxPos] = 0; - A[maxPos + 1] = 1; - return true; // valid - } - return false; // invalid -} - -template -inline force_inline -bool LSHSearch::PerturbationExpand(std::vector& A) const -{ - // Find the last '1' in A. - size_t maxPos = 0; - for (size_t i = 0; i < A.size(); ++i) - if (A[i]) // Marked true. - maxPos = i; - - if (maxPos + 1 < A.size()) // Otherwise, this is an invalid vector. - { - A[maxPos + 1] = 1; - return true; - } - return false; -} - -template -inline force_inline -bool LSHSearch::PerturbationValid( - const std::vector& A) const -{ - // Use check to mark dimensions we have seen before in A. If a dimension is - // seen twice (or more), A is not a valid perturbation. - std::vector check(numProj); - - if (A.size() > 2 * numProj) - return false; // This should never happen. - - // Check that we only see each dimension once. If not, vector is not valid. - for (size_t i = 0; i < A.size(); ++i) - { - // Only check dimensions that were included. - if (!A[i]) - continue; - - // If dimesnion is unseen thus far, mark it as seen. - if (check[i % numProj] == false) - check[i % numProj] = true; - else - return false; // If dimension was seen before, set is not valid. - } - // If we didn't fail, set is valid. - return true; -} - -// Compute additional probing bins for a query -template -void LSHSearch::GetAdditionalProbingBins( - const arma::vec& queryCode, - const arma::vec& queryCodeNotFloored, - const size_t T, - arma::mat& additionalProbingBins) const -{ - // No additional bins requested. Our work is done. - if (T == 0) - return; - - // Each column of additionalProbingBins is the code of a bin. - additionalProbingBins.set_size(numProj, T); - - // Copy the query's code, then in the end we will add/subtract according - // to perturbations we calculated. - for (size_t c = 0; c < T; ++c) - additionalProbingBins.col(c) = queryCode; - - - // Calculate query point's projection position. - arma::mat projection = queryCodeNotFloored; - - // Use projection to calculate query's distance from hash limits. - arma::vec limLow = projection - queryCode * hashWidth; - arma::vec limHigh = hashWidth - limLow; - - // Calculate scores. score = distance^2. - arma::vec scores(2 * numProj); - scores.rows(0, numProj - 1) = arma::pow(limLow, 2); - scores.rows(numProj, (2 * numProj) - 1) = arma::pow(limHigh, 2); - - // Actions vector describes what perturbation (-1/+1) corresponds to a score. - arma::Col actions(2 * numProj); // will be [-1 ... 1 ...] - actions.rows(0, numProj - 1) = // First numProj rows. - -1 * arma::ones< arma::Col > (numProj); // -1s - actions.rows(numProj, (2 * numProj) - 1) = // Last numProj rows. - arma::ones< arma::Col > (numProj); // 1s - - - // Acting dimension vector shows which coordinate to transform according to - // actions (actions are described by actions vector above). - arma::Col positions(2 * numProj); // Will be [0 1 2 ... 0 1 2 ...]. - positions.rows(0, numProj - 1) = - arma::linspace< arma::Col >(0, numProj - 1, numProj); - positions.rows(numProj, 2 * numProj - 1) = - arma::linspace< arma::Col >(0, numProj - 1, numProj); - - // Special case: No need to create heap for 1 or 2 codes. - if (T <= 2) - { - // First, find location of minimum score, generate 1 perturbation vector, - // and add its code to additionalProbingBins column 0. - - // Find location and value of smallest element of scores vector. - double minscore = scores[0]; - size_t minloc = 0; - for (size_t s = 1; s < (2 * numProj); ++s) - { - if (minscore > scores[s]) - { - minscore = scores[s]; - minloc = s; - } - } - - // Add or subtract 1 to dimension corresponding to minimum score. - additionalProbingBins(positions[minloc], 0) += actions[minloc]; - if (T == 1) - return; // Done if asked for only 1 code. - - // Now, find location of second smallest score and generate one more vector. - // The second perturbation vector still can't comprise of more than one - // change in the bin codes, because of the way perturbation vectors - // are generated: First we create the one with the smallest score (Ao) and - // then we either add 1 extra dimension to it (Ae) or shift it by one (As). - // Since As contains the second smallest score, and Ae contains both the - // smallest and the second smallest, it's obvious that score(Ae) > - // score(As). Therefore the second perturbation vector is ALWAYS the vector - // containing only the second-lowest scoring perturbation. - double minscore2 = scores[0]; - size_t minloc2 = 0; - for (size_t s = 0; s < (2 * numProj); ++s) // Here we can't start from 1. - { - if (minscore2 > scores[s] && s != minloc) // Second smallest. - { - minscore2 = scores[s]; - minloc2 = s; - } - } - - // Add or subtract 1 to create second-lowest scoring vector. - additionalProbingBins(positions[minloc2], 1) += actions[minloc2]; - return; - } - - // General case: more than 2 perturbation vectors require use of minheap. - // Sort everything in increasing order. - arma::uvec sortidx = arma::sort_index(scores); - scores = scores(sortidx); - actions = actions(sortidx); - positions = positions(sortidx); - - // Theory: - // A probing sequence is a sequence of T probing bins where a query's - // neighbors are most likely to be. Likelihood is dependent only on a bin's - // score, which is the sum of scores of all dimension-action pairs, so we - // need to calculate the T smallest sums of scores that are not conflicting. - // - // Method: - // Store each perturbation set (pair of (dimension, action)) in a - // std::vector. Create a minheap of scores, with each node pointing to its - // relevant perturbation set. Each perturbation set popped from the minheap - // is the next most likely perturbation set. - // Transform perturbation set to perturbation vector by setting the - // dimensions specified by the set to queryCode+action (action is {-1, 1}). - - // Perturbation sets (A) mark with 1 the (score, action, dimension) positions - // included in a given perturbation vector. Other spaces are 0. - std::vector Ao(2 * numProj); - Ao[0] = 1; // Smallest vector includes only smallest score. - - std::vector< std::vector > perturbationSets; - perturbationSets.push_back(Ao); // Storage of perturbation sets. - - std::priority_queue< - std::pair, // contents: pairs of (score, index) - std::vector< // container: vector of pairs - std::pair - >, - std::greater< std::pair > // comparator of pairs - > minHeap; // our minheap - - // Start by adding the lowest scoring set to the minheap. - minHeap.push(std::make_pair(PerturbationScore(Ao, scores), 0)); - - // Loop invariable: after pvec iterations, additionalProbingBins contains pvec - // valid codes of the lowest-scoring bins (bins most likely to contain - // neighbors of the query). - for (size_t pvec = 0; pvec < T; ++pvec) - { - std::vector Ai; - do - { - // Get the perturbation set corresponding to the minimum score. - Ai = perturbationSets[ minHeap.top().second ]; - minHeap.pop(); // .top() returns, .pop() removes - - // Shift operation on Ai (replace max with max+1). - std::vector As = Ai; - - // Don't add invalid sets. - if (PerturbationShift(As) && PerturbationValid(As)) - { - perturbationSets.push_back(As); // add shifted set to sets - minHeap.push( - std::make_pair(PerturbationScore(As, scores), - perturbationSets.size() - 1)); - } - - // Expand operation on Ai (add max+1 to set). - std::vector Ae = Ai; - - // Don't add invalid sets. - if (PerturbationExpand(Ae) && PerturbationValid(Ae)) - { - perturbationSets.push_back(Ae); // add expanded set to sets - minHeap.push( - std::make_pair(PerturbationScore(Ae, scores), - perturbationSets.size() - 1)); - } - } while (!PerturbationValid(Ai)); // Discard invalid perturbations - - // Found valid perturbation set Ai. Construct perturbation vector from set. - for (size_t pos = 0; pos < Ai.size(); ++pos) - { - // If Ai[pos] is marked, add action to probing vector. - additionalProbingBins(positions(pos), pvec) += Ai[pos] ? actions(pos) : 0; - } - } -} - -template -template -void LSHSearch::ReturnIndicesFromTable( - const VecType& queryPoint, - arma::uvec& referenceIndices, - size_t numTablesToSearch, - const size_t T) const -{ - // Decide on the number of tables to look into. - if (numTablesToSearch == 0) // If no user input is given, search all. - numTablesToSearch = numTables; - - // Sanity check to make sure that the existing number of tables is not - // exceeded. - if (numTablesToSearch > numTables) - numTablesToSearch = numTables; - - // Hash the query in each of the 'numTablesToSearch' hash tables using the - // 'numProj' projections for each table. This gives us 'numTablesToSearch' - // keys for the query where each key is a 'numProj' dimensional integer - // vector. - - // Compute the projection of the query in each table. - arma::mat allProjInTables(numProj, numTablesToSearch); - arma::mat queryCodesNotFloored(numProj, numTablesToSearch); - for (size_t i = 0; i < numTablesToSearch; i++) - queryCodesNotFloored.unsafe_col(i) = projections.slice(i).t() * queryPoint; - - queryCodesNotFloored += offsets.cols(0, numTablesToSearch - 1); - allProjInTables = arma::floor(queryCodesNotFloored / hashWidth); - - // Use hashMat to store the primary probing codes and any additional codes - // from multiprobe LSH. - arma::Mat hashMat; - hashMat.set_size(T + 1, numTablesToSearch); - - // Compute the primary hash value of each key of the query into a bucket of - // the secondHashTable using the secondHashWeights. - hashMat.row(0) = arma::conv_to> // Floor by typecasting - ::from(secondHashWeights.t() * allProjInTables); - // Mod to compute 2nd-level codes. - for (size_t i = 0; i < numTablesToSearch; i++) - hashMat(0, i) = (hashMat(0, i) % secondHashSize); - - // Compute hash codes of additional probing bins. - if (T > 0) - { - for (size_t i = 0; i < numTablesToSearch; ++i) - { - // Construct this table's probing sequence of length T. - arma::mat additionalProbingBins; - GetAdditionalProbingBins(allProjInTables.unsafe_col(i), - queryCodesNotFloored.unsafe_col(i), - T, - additionalProbingBins); - - // Map each probing bin to a bin in secondHashTable (just like we did for - // the primary hash table). - hashMat(arma::span(1, T), i) = // Compute code of rows 1:end of column i - arma::conv_to< arma::Col >:: // floor by typecasting to size_t - from(secondHashWeights.t() * additionalProbingBins); - for (size_t p = 1; p < T + 1; ++p) - hashMat(p, i) = (hashMat(p, i) % secondHashSize); - } - } - - // Count number of points hashed in the same bucket as the query. - size_t maxNumPoints = 0; - for (size_t i = 0; i < numTablesToSearch; ++i) - { - for (size_t p = 0; p < T + 1; ++p) - { - const size_t hashInd = hashMat(p, i); // find query's bucket - const size_t tableRow = bucketRowInHashTable[hashInd]; - if (tableRow < secondHashSize) - maxNumPoints += bucketContentSize[tableRow]; // count bucket contents - } - } - - // There are two ways to proceed here: - // Either allocate a maxNumPoints-size vector, place all candidates, and run - // unique on the vector to discard duplicates. - // Or allocate a referenceSet.n_cols size vector (i.e. number of reference - // points) of zeros, and mark found indices as 1. - // Option 1 runs faster for small maxNumPoints but worse for larger values, so - // we choose based on a heuristic. - const float cutoff = 0.1; - const float selectivity = static_cast(maxNumPoints) / - static_cast(referenceSet.n_cols); - - if (selectivity > cutoff) - { - // Heuristic: larger maxNumPoints means we should use find() because it - // should be faster. - // Reference points hashed in the same bucket as the query are set to >0. - arma::Col refPointsConsidered; - refPointsConsidered.zeros(referenceSet.n_cols); - - for (size_t i = 0; i < numTablesToSearch; ++i) // for all tables - { - for (size_t p = 0; p < T + 1; ++p) // For entire probing sequence. - { - // get the sequence code - size_t hashInd = hashMat(p, i); - size_t tableRow = bucketRowInHashTable[hashInd]; - - if (tableRow < secondHashSize && bucketContentSize[tableRow] > 0) - { - // Pick the indices in the bucket corresponding to hashInd. - for (size_t j = 0; j < bucketContentSize[tableRow]; ++j) - refPointsConsidered[ secondHashTable[tableRow](j) ]++; - } - } - } - - // Only keep reference points found in at least one bucket. - referenceIndices = arma::find(refPointsConsidered > 0); - return; - } - else - { - // Heuristic: smaller maxNumPoints means we should use unique() because it - // should be faster. - // Allocate space for the query's potential neighbors. - arma::uvec refPointsConsideredSmall; - refPointsConsideredSmall.zeros(maxNumPoints); - - // Retrieve candidates. - size_t start = 0; - - for (size_t i = 0; i < numTablesToSearch; ++i) // For all tables - { - for (size_t p = 0; p < T + 1; ++p) - { - const size_t hashInd = hashMat(p, i); // Find the query's bucket. - const size_t tableRow = bucketRowInHashTable[hashInd]; - - if (tableRow < secondHashSize) - { - // Store all secondHashTable points in the candidates set. - for (size_t j = 0; j < bucketContentSize[tableRow]; ++j) - refPointsConsideredSmall(start++) = secondHashTable[tableRow](j); - } - } - } - - // Keep only one copy of each candidate. - referenceIndices = arma::unique(refPointsConsideredSmall); - return; - } -} - -// Search for nearest neighbors in a given query set. -template -void LSHSearch::Search(const arma::mat& querySet, - const size_t k, - arma::Mat& resultingNeighbors, - arma::mat& distances, - const size_t numTablesToSearch, - const size_t T) -{ - // Ensure the dimensionality of the query set is correct. - if (querySet.n_rows != referenceSet.n_rows) - { - std::ostringstream oss; - oss << "LSHSearch::Search(): dimensionality of query set (" - << querySet.n_rows << ") is not equal to the dimensionality the model " - << "was trained on (" << referenceSet.n_rows << ")!" << std::endl; - throw std::invalid_argument(oss.str()); - } - - if (k > referenceSet.n_cols) - { - std::ostringstream oss; - oss << "LSHSearch::Search(): requested " << k << " approximate nearest " - << "neighbors, but reference set has " << referenceSet.n_cols - << " points!" << std::endl; - throw std::invalid_argument(oss.str()); - } - - // Set the size of the neighbor and distance matrices. - resultingNeighbors.set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - // If the user asked for 0 nearest neighbors... uh... we're done. - if (k == 0) - return; - - // If the user requested more than the available number of additional probing - // bins, set Teffective to maximum T. Maximum T is 2^numProj - 1 - size_t Teffective = T; - if (T > ((size_t) ((1 << numProj) - 1))) - { - Teffective = (1 << numProj) - 1; - Log::Warn << "Requested " << T << " additional bins are more than " - << "theoretical maximum. Using " << Teffective << " instead." - << std::endl; - } - - // If the user set multiprobe, log it - if (Teffective > 0) - Log::Info << "Running multiprobe LSH with " << Teffective - <<" additional probing bins per table per query." << std::endl; - - size_t avgIndicesReturned = 0; - - Timer::Start("computing_neighbors"); - - // Parallelization to process more than one query at a time. - #pragma omp parallel for \ - shared(resultingNeighbors, distances) \ - schedule(dynamic)\ - reduction(+:avgIndicesReturned) - for (omp_size_t i = 0; i < (omp_size_t) querySet.n_cols; ++i) - { - // Go through every query point. - // Hash every query into every hash table and eventually into the - // 'secondHashTable' to obtain the neighbor candidates. - arma::uvec refIndices; - ReturnIndicesFromTable(querySet.col(i), refIndices, numTablesToSearch, - Teffective); - - // An informative book-keeping for the number of neighbor candidates - // returned on average. - // Make atomic to avoid race conditions when multiple threads are running - // #pragma omp atomic - avgIndicesReturned = avgIndicesReturned + refIndices.n_elem; - - // Sequentially go through all the candidates and save the best 'k' - // candidates. - BaseCase(i, refIndices, k, querySet, resultingNeighbors, distances); - } - - Timer::Stop("computing_neighbors"); - - distanceEvaluations += avgIndicesReturned; - avgIndicesReturned /= querySet.n_cols; - Log::Info << avgIndicesReturned << " distinct indices returned on average." << - std::endl; -} - -// Search for approximate neighbors of the reference set. -template -void LSHSearch:: -Search(const size_t k, - arma::Mat& resultingNeighbors, - arma::mat& distances, - const size_t numTablesToSearch, - size_t T) -{ - // This is monochromatic search; the query set is the reference set. - resultingNeighbors.set_size(k, referenceSet.n_cols); - distances.set_size(k, referenceSet.n_cols); - - // If the user requested more than the available number of additional probing - // bins, set Teffective to maximum T. Maximum T is 2^numProj - 1 - size_t Teffective = T; - if (T > ((size_t) ((1 << numProj) - 1))) - { - Teffective = (1 << numProj) - 1; - Log::Warn << "Requested " << T << " additional bins are more than " - << "theoretical maximum. Using " << Teffective << " instead." - << std::endl; - } - - // If the user set multiprobe, log it - if (T > 0) - Log::Info << "Running multiprobe LSH with " << Teffective << - " additional probing bins per table per query."<< std::endl; - - size_t avgIndicesReturned = 0; - - Timer::Start("computing_neighbors"); - - // Parallelization to process more than one query at a time. - #pragma omp parallel for \ - shared(resultingNeighbors, distances) \ - schedule(dynamic)\ - reduction(+:avgIndicesReturned) - for (omp_size_t i = 0; i < (omp_size_t) referenceSet.n_cols; ++i) - { - // Go through every query point. - // Hash every query into every hash table and eventually into the - // 'secondHashTable' to obtain the neighbor candidates. - arma::uvec refIndices; - ReturnIndicesFromTable(referenceSet.col(i), refIndices, numTablesToSearch, - Teffective); - - // An informative book-keeping for the number of neighbor candidates - // returned on average. - // Make atomic to avoid race conditions when multiple threads are running. - // #pragma omp atomic - avgIndicesReturned += refIndices.n_elem; - - // Sequentially go through all the candidates and save the best 'k' - // candidates. - BaseCase(i, refIndices, k, resultingNeighbors, distances); - } - - Timer::Stop("computing_neighbors"); - - distanceEvaluations += avgIndicesReturned; - avgIndicesReturned /= referenceSet.n_cols; - Log::Info << avgIndicesReturned << " distinct indices returned on average." << - std::endl; -} - -template -double LSHSearch::ComputeRecall( - const arma::Mat& foundNeighbors, - const arma::Mat& realNeighbors) -{ - if (foundNeighbors.n_rows != realNeighbors.n_rows || - foundNeighbors.n_cols != realNeighbors.n_cols) - throw std::invalid_argument("LSHSearch::ComputeRecall(): matrices provided" - " must have equal size"); - - const size_t queries = foundNeighbors.n_cols; - const size_t neighbors = foundNeighbors.n_rows; // Should be equal to k. - - // The recall is the set intersection of found and real neighbors. - size_t found = 0; - for (size_t col = 0; col < queries; ++col) - for (size_t row = 0; row < neighbors; ++row) - for (size_t nei = 0; nei < realNeighbors.n_rows; ++nei) - if (realNeighbors(row, col) == foundNeighbors(nei, col)) - { - found++; - break; - } - - return ((double) found) / realNeighbors.n_elem; -} - -template -template -void LSHSearch::serialize(Archive& ar, - const unsigned int version) -{ - ar & BOOST_SERIALIZATION_NVP(referenceSet); - ar & BOOST_SERIALIZATION_NVP(numProj); - ar & BOOST_SERIALIZATION_NVP(numTables); - - // Delete existing projections, if necessary. - if (Archive::is_loading::value) - projections.reset(); - - // Backward compatibility: older versions of LSHSearch stored the projection - // tables in a std::vector. - if (version == 0) - { - std::vector tmpProj; - ar & BOOST_SERIALIZATION_NVP(tmpProj); - - projections.set_size(tmpProj[0].n_rows, tmpProj[0].n_cols, tmpProj.size()); - for (size_t i = 0; i < tmpProj.size(); ++i) - projections.slice(i) = tmpProj[i]; - } - else - { - ar & BOOST_SERIALIZATION_NVP(projections); - } - - ar & BOOST_SERIALIZATION_NVP(offsets); - ar & BOOST_SERIALIZATION_NVP(hashWidth); - ar & BOOST_SERIALIZATION_NVP(secondHashSize); - ar & BOOST_SERIALIZATION_NVP(secondHashWeights); - ar & BOOST_SERIALIZATION_NVP(bucketSize); - // needs specific handling for new version - - // Backward compatibility: in older versions of LSHSearch, the secondHashTable - // was stored as an arma::Mat. So we need to properly load that, then - // prune it down to size. - if (version == 0) - { - arma::Mat tmpSecondHashTable; - ar & BOOST_SERIALIZATION_NVP(tmpSecondHashTable); - - // The old secondHashTable was stored in row-major format, so we transpose - // it. - tmpSecondHashTable = tmpSecondHashTable.t(); - - secondHashTable.resize(tmpSecondHashTable.n_cols); - for (size_t i = 0; i < tmpSecondHashTable.n_cols; ++i) - { - // Find length of each column. We know we are at the end of the list when - // the value referenceSet.n_cols is seen. - - size_t len = 0; - for (; len < tmpSecondHashTable.n_rows; ++len) - if (tmpSecondHashTable(len, i) == referenceSet.n_cols) - break; - - // Set the size of the new column correctly. - secondHashTable[i].set_size(len); - for (size_t j = 0; j < len; ++j) - secondHashTable[i](j) = tmpSecondHashTable(j, i); - } - } - else - { - size_t tables; - if (Archive::is_saving::value) - tables = secondHashTable.size(); - ar & BOOST_SERIALIZATION_NVP(tables); - - // Set size of second hash table if needed. - if (Archive::is_loading::value) - { - secondHashTable.clear(); - secondHashTable.resize(tables); - } - - ar & BOOST_SERIALIZATION_NVP(secondHashTable); - } - - // Backward compatibility: old versions of LSHSearch held bucketContentSize - // for all possible buckets (of size secondHashSize), but now we hold a - // compressed representation. - if (version == 0) - { - // The vector was stored in the old uncompressed form. So we need to shrink - // it. But we can't do that until we have bucketRowInHashTable, so we also - // have to load that. - arma::Col tmpBucketContentSize; - ar & BOOST_SERIALIZATION_NVP(tmpBucketContentSize); - ar & BOOST_SERIALIZATION_NVP(bucketRowInHashTable); - - // Compress into a smaller vector by just dropping all of the zeros. - bucketContentSize.set_size(secondHashTable.size()); - for (size_t i = 0; i < tmpBucketContentSize.n_elem; ++i) - if (tmpBucketContentSize[i] > 0) - bucketContentSize[bucketRowInHashTable[i]] = tmpBucketContentSize[i]; - } - else - { - ar & BOOST_SERIALIZATION_NVP(bucketContentSize); - ar & BOOST_SERIALIZATION_NVP(bucketRowInHashTable); - } - - ar & BOOST_SERIALIZATION_NVP(distanceEvaluations); -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/matrix_completion/matrix_completion.hpp b/src/sdk/mlpack/include/mlpack/methods/matrix_completion/matrix_completion.hpp deleted file mode 100644 index 6b0646080..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/matrix_completion/matrix_completion.hpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @file matrix_completion.hpp - * @author Stephen Tu - * - * A thin wrapper around nuclear norm minimization to solve - * low rank matrix completion problems. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_MATRIX_COMPLETION_MATRIX_COMPLETION_HPP -#define MLPACK_METHODS_MATRIX_COMPLETION_MATRIX_COMPLETION_HPP - -#include -#include - -namespace mlpack { -namespace matrix_completion { - -/** - * This class implements the popular nuclear norm minimization heuristic for - * matrix completion problems. That is, given known values M_ij's, the - * following optimization problem (semi-definite program) is solved to fill in - * the remaining unknown values of X - * - * min ||X||_* subj to X_ij = M_ij - * - * where ||X||_* denotes the nuclear norm (sum of singular values of X). - * - * For a theoretical treatment of the conditions necessary for exact recovery, - * see the following paper: - * - * A Simpler Appoarch to Matrix Completion. - * Benjamin Recht. JMLR 11. - * http://arxiv.org/pdf/0910.0651v2.pdf - * - * An example of how to use this class is shown below: - * - * @code - * size_t m, n; // size of unknown matrix - * arma::umat indices; // contains the known indices [2 x n_entries] - * arma::vec values; // contains the known values [n_entries] - * arma::mat recovered; // will contain the completed matrix - * - * MatrixCompletion mc(m, n, indices, values); - * mc.Recover(recovered); - * @endcode - * - * @see LRSDP - */ -class MatrixCompletion -{ - public: - /** - * Construct a matrix completion problem, specifying the maximum rank of the - * solution. - * - * @param m Number of rows of original matrix. - * @param n Number of columns of original matrix. - * @param indices Matrix containing the indices of the known entries (must be - * [2 x p]). - * @param values Vector containing the values of the known entries (must be - * length p). - * @param r Maximum rank of solution. - */ - MatrixCompletion(const size_t m, - const size_t n, - const arma::umat& indices, - const arma::vec& values, - const size_t r); - - /** - * Construct a matrix completion problem, specifying the initial point of the - * optimization. - * - * @param m Number of rows of original matrix. - * @param n Number of columns of original matrix. - * @param indices Matrix containing the indices of the known entries (must be - * [2 x p]). - * @param values Vector containing the values of the known entries (must be - * length p). - * @param initialPoint Starting point for the SDP optimization. - */ - MatrixCompletion(const size_t m, - const size_t n, - const arma::umat& indices, - const arma::vec& values, - const arma::mat& initialPoint); - - /** - * Construct a matrix completion problem. - * - * @param m Number of rows of original matrix. - * @param n Number of columns of original matrix. - * @param indices Matrix containing the indices of the known entries (must be - * [2 x p]). - * @param values Vector containing the values of the known entries (must be - * length p). - */ - MatrixCompletion(const size_t m, - const size_t n, - const arma::umat& indices, - const arma::vec& values); - - /** - * Solve the underlying SDP to fill in the remaining values. - * - * @param recovered Will contain the completed matrix. - */ - void Recover(arma::mat& recovered); - - //! Return the underlying SDP. - const optimization::LRSDP>& Sdp() const - { - return sdp; - } - //! Modify the underlying SDP. - optimization::LRSDP>& Sdp() { return sdp; } - - private: - //! Number of rows in original matrix. - size_t m; - //! Number of columns in original matrix. - size_t n; - //! Matrix containing the indices of the known entries (has two rows). - arma::umat indices; - //! Vector containing the values of the known entries. - arma::mat values; - - //! The underlying SDP to be solved. - optimization::LRSDP> sdp; - - //! Validate the input matrices. - void CheckValues(); - //! Initialize the SDP. - void InitSDP(); - - //! Select a rank of the matrix given that is of size m x n and has p known - //! elements. - static size_t DefaultRank(const size_t m, const size_t n, const size_t p); -}; - -} // namespace matrix_completion -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/mean_shift/mean_shift.hpp b/src/sdk/mlpack/include/mlpack/methods/mean_shift/mean_shift.hpp deleted file mode 100644 index b393fac2a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/mean_shift/mean_shift.hpp +++ /dev/null @@ -1,178 +0,0 @@ -/** - * @file mean_shift.hpp - * @author Shangtong Zhang - * - * Mean Shift clustering - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_HPP -#define MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_HPP - -#include -#include -#include -#include -#include - -namespace mlpack { -namespace meanshift /** Mean shift clustering. */ { - -/** - * This class implements mean shift clustering. For each point in dataset, - * apply mean shift algorithm until maximum iterations or convergence. Then - * remove duplicate centroids. - * - * A simple example of how to run mean shift clustering is shown below. - * - * @code - * extern arma::mat data; // Dataset we want to run mean shift on. - * arma::Row assignments; // Cluster assignments. - * arma::mat centroids; // Cluster centroids. - * bool forceConvergence = true; // Flag whether to force each centroid seed - * to converge regardless of maxIterations. - * - * MeanShift<> meanShift(); - * meanShift.Cluster(dataset, assignments, centroids, forceConvergence); - * @endcode - * - * @tparam UseKernel Use kernel or mean to calculate new centroid. - * If false, KernelType will be ignored. - * @tparam KernelType The kernel to use. - * @tparam MatType The type of matrix the data is stored in. - */ -template -class MeanShift -{ - public: - /** - * Create a mean shift object and set the parameters which mean shift will be - * run with. - * - * @param radius If distance of two centroids is less than it, one will be - * removed. If this value isn't positive, an estimation will be given - * when clustering. - * @param maxIterations Maximum number of iterations allowed before giving up - * iterations will terminate. - * @param kernel Optional KernelType object. - */ - MeanShift(const double radius = 0, - const size_t maxIterations = 1000, - const KernelType kernel = KernelType()); - - /** - * Give an estimation of radius based on given dataset. - * - * @param data Dataset for estimation. - * @param ratio Percentage of dataset to use for nearest neighbor search. - */ - double EstimateRadius(const MatType& data, const double ratio = 0.2); - - /** - * Perform mean shift clustering on the data, returning a list of cluster - * assignments and centroids. - * - * @tparam MatType Type of matrix. - * @param data Dataset to cluster. - * @param assignments Vector to store cluster assignments in. - * @param centroids Matrix in which centroids are stored. - * @param forceConvergence Flag whether to force each centroid seed to - * converge regardless of maxIterations. - */ - void Cluster(const MatType& data, - arma::Row& assignments, - arma::mat& centroids, - bool forceConvergence = true, - bool useSeeds = true); - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Set the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - //! Get the radius. - double Radius() const { return radius; } - //! Set the radius. - void Radius(double radius); - - //! Get the kernel. - const KernelType& Kernel() const { return kernel; } - //! Modify the kernel. - KernelType& Kernel() { return kernel; } - - private: - /** - * To speed up, we can generate some seeds from data set and use - * them as initial centroids rather than all the points in the data set. The - * basic idea here is that we will place our points into hypercube bins of - * side length binSize, and any bins that contain fewer than minFreq points - * will be removed as possible seeds. Usually, 1 is a sufficient parameter - * for minFreq, and the bin size can be set equal to the estimated radius. - * - * @param data The reference data set. - * @param binSize Width of hypercube bins. - * @param minFreq Minimum number of points in bin. - * @param seed Matrix to store generated seeds in. - */ - void GenSeeds(const MatType& data, - const double binSize, - const int minFreq, - MatType& seeds); - - /** - * Use kernel to calculate new centroid given dataset and valid neighbors. - * - * @param data The whole dataset - * @param neighbors Valid neighbors - * @param distances Distances to neighbors - # @param centroid Store calculated centroid - */ - template - typename std::enable_if::type - CalculateCentroid(const MatType& data, - const std::vector& neighbors, - const std::vector& distances, - arma::colvec& centroid); - - /** - * Use mean to calculate new centroid given dataset and valid neighbors. - * - * @param data The whole dataset - * @param neighbors Valid neighbors - * @param distances Distances to neighbors - # @param centroid Store calculated centroid - */ - template - typename std::enable_if::type - CalculateCentroid(const MatType& data, - const std::vector& neighbors, - const std::vector&, /*unused*/ - arma::colvec& centroid); - - /** - * If distance of two centroids is less than radius, one will be removed. - * Points with distance to current centroid less than radius will be used - * to calculate new centroid. - */ - double radius; - - //! Maximum number of iterations before giving up. - size_t maxIterations; - - //! Instantiated kernel. - KernelType kernel; -}; - -} // namespace meanshift -} // namespace mlpack - -// Include implementation. -#include "mean_shift_impl.hpp" - -#endif // MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/mean_shift/mean_shift_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/mean_shift/mean_shift_impl.hpp deleted file mode 100644 index f7e6a1beb..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/mean_shift/mean_shift_impl.hpp +++ /dev/null @@ -1,300 +0,0 @@ -/** - * @file mean_shift_impl.hpp - * @author Shangtong Zhang - * - * Mean shift clustering implementation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_IMPL_HPP -#define MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_IMPL_HPP - -#include -#include -#include -#include -#include - -#include "map" - -// In case it hasn't been included yet. -#include "mean_shift.hpp" - -namespace mlpack { -namespace meanshift { - -/** - * Construct the Mean Shift object. - */ -template -MeanShift:: -MeanShift(const double radius, - const size_t maxIterations, - const KernelType kernel) : - radius(radius), - maxIterations(maxIterations), - kernel(kernel) -{ - // Nothing to do. -} - -template -void MeanShift::Radius(double radius) -{ - this->radius = radius; -} - -// Estimate radius based on given dataset. -template -double MeanShift:: -EstimateRadius(const MatType& data, double ratio) -{ - neighbor::KNN neighborSearch(data); - - /** - * For each point in dataset, select nNeighbors nearest points and get - * nNeighbors distances. Use the maximum distance to estimate the duplicate - * threshhold. - */ - const size_t nNeighbors = size_t(data.n_cols * ratio); - arma::Mat neighbors; - arma::mat distances; - neighborSearch.Search(nNeighbors, neighbors, distances); - - // Get max distance for each point. - arma::rowvec maxDistances = max(distances); - - // Calculate and return the radius. - return arma::sum(maxDistances) / (double) data.n_cols; -} - -// Class to compare two vectors. -template -class less -{ - public: - bool operator()(const VecType& first, const VecType& second) const - { - for (size_t i = 0; i < first.n_rows; ++i) - { - if (first[i] == second[i]) - continue; - return first(i) < second(i); - } - return false; - } -}; - -// Generate seeds from given data set. -template -void MeanShift::GenSeeds( - const MatType& data, - const double binSize, - const int minFreq, - MatType& seeds) -{ - typedef arma::colvec VecType; - std::map > allSeeds; - for (size_t i = 0; i < data.n_cols; ++i) - { - VecType binnedPoint = arma::floor(data.unsafe_col(i) / binSize); - if (allSeeds.find(binnedPoint) == allSeeds.end()) - allSeeds[binnedPoint] = 1; - else - allSeeds[binnedPoint]++; - } - - // Remove seeds with too few points. First we count the number of seeds we - // end up with, then we add them. - std::map >::iterator it; - size_t count = 0; - for (it = allSeeds.begin(); it != allSeeds.end(); ++it) - if (it->second >= minFreq) - ++count; - - seeds.set_size(data.n_rows, count); - count = 0; - for (it = allSeeds.begin(); it != allSeeds.end(); ++it) - { - if (it->second >= minFreq) - { - seeds.col(count) = it->first; - ++count; - } - } - - seeds *= binSize; -} - -// Calculate new centroid with given kernel. -template -template -typename std::enable_if::type -MeanShift:: -CalculateCentroid(const MatType& data, - const std::vector& neighbors, - const std::vector& distances, - arma::colvec& centroid) -{ - double sumWeight = 0; - for (size_t i = 0; i < neighbors.size(); ++i) - { - if (distances[i] > 0) - { - double dist = distances[i] / radius; - double weight = kernel.Gradient(dist) / dist; - sumWeight += weight; - centroid += weight * data.unsafe_col(neighbors[i]); - } - } - - if (sumWeight != 0) - { - centroid /= sumWeight; - return true; - } - return false; -} - -// Calculate new centroid by mean. -template -template -typename std::enable_if::type -MeanShift:: -CalculateCentroid(const MatType& data, - const std::vector& neighbors, - const std::vector&, /*unused*/ - arma::colvec& centroid) -{ - for (size_t i = 0; i < neighbors.size(); ++i) - centroid += data.unsafe_col(neighbors[i]); - - centroid /= neighbors.size(); - return true; -} - -/** - * Perform Mean Shift clustering on the data set, returning a list of cluster - * assignments and centroids. - */ -template -inline void MeanShift::Cluster( - const MatType& data, - arma::Row& assignments, - arma::mat& centroids, - bool forceConvergence, - bool useSeeds) -{ - if (radius <= 0) - { - // An invalid radius is given; an estimation is needed. - Radius(EstimateRadius(data)); - } - - MatType seeds; - const MatType* pSeeds = &data; - if (useSeeds) - { - GenSeeds(data, radius, 1, seeds); - pSeeds = &seeds; - } - - // Holds all centroids before removing duplicate ones. - arma::mat allCentroids(pSeeds->n_rows, pSeeds->n_cols); - - assignments.set_size(data.n_cols); - - range::RangeSearch<> rangeSearcher(data); - math::Range validRadius(0, radius); - std::vector > neighbors; - std::vector > distances; - - // For each seed, perform mean shift algorithm. - for (size_t i = 0; i < pSeeds->n_cols; ++i) - { - // Initial centroid is the seed itself. - allCentroids.col(i) = pSeeds->unsafe_col(i); - for (size_t completedIterations = 0; completedIterations < maxIterations - || forceConvergence; completedIterations++) - { - // Store new centroid in this. - arma::colvec newCentroid = arma::zeros(pSeeds->n_rows); - - rangeSearcher.Search(allCentroids.unsafe_col(i), validRadius, - neighbors, distances); - if (neighbors[0].size() == 0) // There are no points in the cluster. - break; - - // Calculate new centroid. - if (!CalculateCentroid(data, neighbors[0], distances[0], newCentroid)) - newCentroid = allCentroids.unsafe_col(i); - - // If the mean shift vector is small enough, it has converged. - if (metric::EuclideanDistance::Evaluate(newCentroid, - allCentroids.unsafe_col(i)) < 1e-3 * radius) - { - // Determine if the new centroid is duplicate with old ones. - bool isDuplicated = false; - for (size_t k = 0; k < centroids.n_cols; ++k) - { - const double distance = metric::EuclideanDistance::Evaluate( - allCentroids.unsafe_col(i), centroids.unsafe_col(k)); - if (distance < radius) - { - isDuplicated = true; - break; - } - } - - if (!isDuplicated) - centroids.insert_cols(centroids.n_cols, allCentroids.unsafe_col(i)); - - // Get out of the loop. - break; - } - - // Update the centroid. - allCentroids.col(i) = newCentroid; - } - } - - // If no centroid has converged due to too little iterations and without - // forcing convergence, take 1 random centroid calculated. - if (centroids.empty()) - { - Log::Warn << "No clusters converged; setting 1 random centroid calculated. " - << "Try increasing the maximum number of iterations or setting the " - << "option to force convergence." << std::endl; - - if (maxIterations == 0) - { - centroids.insert_cols(centroids.n_cols, data.col(0)); - } - else - { - centroids.insert_cols(centroids.n_cols, allCentroids.col(0)); - } - assignments.zeros(); - } - else if (centroids.n_cols == 1) - { - assignments.zeros(); - } - else - { - // Assign centroids to each point. - neighbor::KNN neighborSearcher(centroids); - arma::mat neighborDistances; - arma::Mat resultingNeighbors; - neighborSearcher.Search(data, 1, resultingNeighbors, neighborDistances); - assignments = resultingNeighbors; - } -} - -} // namespace meanshift -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/mvu/mvu.hpp b/src/sdk/mlpack/include/mlpack/methods/mvu/mvu.hpp deleted file mode 100644 index c1cea307f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/mvu/mvu.hpp +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @file mvu.hpp - * @author Ryan Curtin - * - * An implementation of Maximum Variance Unfolding. This file defines an MVU - * class as well as a class representing the objective function (a semidefinite - * program) which MVU seeks to minimize. Minimization is performed by the - * Augmented Lagrangian optimizer (which in turn uses the L-BFGS optimizer). - * - * Note: this implementation of MVU does not work. See #189. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_MVU_MVU_HPP -#define MLPACK_METHODS_MVU_MVU_HPP - -#include - -namespace mlpack { -namespace mvu { - -/** - * The MVU class is meant to provide a good abstraction for users. The dataset - * needs to be provided, as well as several parameters. - * - * - dataset - * - new dimensionality - */ -class MVU -{ - public: - MVU(const arma::mat& dataIn); - - void Unfold(const size_t newDim, - const size_t numNeighbors, - arma::mat& outputCoordinates); - - private: - const arma::mat& data; -}; - -} // namespace mvu -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/naive_bayes/naive_bayes_classifier.hpp b/src/sdk/mlpack/include/mlpack/methods/naive_bayes/naive_bayes_classifier.hpp deleted file mode 100644 index a4bc64185..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/naive_bayes/naive_bayes_classifier.hpp +++ /dev/null @@ -1,247 +0,0 @@ -/** - * @file naive_bayes_classifier.hpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * @author Shihao Jing (shihao.jing810@gmail.com) - * - * A Naive Bayes Classifier which parametrically estimates the distribution of - * the features. It is assumed that the features have been sampled from a - * Gaussian PDF. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NAIVE_BAYES_NAIVE_BAYES_CLASSIFIER_HPP -#define MLPACK_METHODS_NAIVE_BAYES_NAIVE_BAYES_CLASSIFIER_HPP - -#include - -namespace mlpack { -namespace naive_bayes /** The Naive Bayes Classifier. */ { - -/** - * The simple Naive Bayes classifier. This class trains on the data by - * calculating the sample mean and variance of the features with respect to each - * of the labels, and also the class probabilities. The class labels are - * assumed to be positive integers (starting with 0), and are expected to be the - * last row of the data input to the constructor. - * - * Mathematically, it computes P(X_i = x_i | Y = y_j) for each feature X_i for - * each of the labels y_j. Along with this, it also computes the class - * probabilities P(Y = y_j). - * - * For classifying a data point (x_1, x_2, ..., x_n), it computes the following: - * arg max_y(P(Y = y)*P(X_1 = x_1 | Y = y) * ... * P(X_n = x_n | Y = y)) - * - * Example use: - * - * @code - * extern arma::mat training_data, testing_data; - * NaiveBayesClassifier<> nbc(training_data, 5); - * arma::vec results; - * - * nbc.Classify(testing_data, results); - * @endcode - * - * The ModelMatType template parameter specifies the internal matrix type that - * NaiveBayesClassifier will use to hold the means, variances, and weights that - * make up the Naive Bayes model. This can be arma::mat, arma::fmat, or any - * other Armadillo (or Armadillo-compatible) object. Because ModelMatType may - * be different than the type of the data the model is trained on, now training - * is possible with subviews, sparse matrices, or anything else, while still - * storing the model as a ModelMatType internally. - * - * @tparam ModelMatType Internal matrix type to use to store the model. - */ -template -class NaiveBayesClassifier -{ - public: - // Convenience typedef. - typedef typename ModelMatType::elem_type ElemType; - - /** - * Initializes the classifier as per the input and then trains it by - * calculating the sample mean and variances. - * - * Example use: - * @code - * extern arma::mat training_data, testing_data; - * extern arma::Row labels; - * NaiveBayesClassifier nbc(training_data, labels, 5); - * @endcode - * - * @param data Training data points. - * @param labels Labels corresponding to training data points. - * @param numClasses Number of classes in this classifier. - * @param incrementalVariance If true, an incremental algorithm is used to - * calculate the variance; this can prevent loss of precision in some - * cases, but will be somewhat slower to calculate. - */ - template - NaiveBayesClassifier(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const bool incrementalVariance = false); - - /** - * Initialize the Naive Bayes classifier without performing training. All of - * the parameters of the model will be initialized to zero. Be sure to use - * Train() before calling Classify(), otherwise the results may be - * meaningless. - */ - NaiveBayesClassifier(const size_t dimensionality = 0, - const size_t numClasses = 0); - - /** - * Train the Naive Bayes classifier on the given dataset. If the incremental - * algorithm is used, the current model is used as a starting point (this is - * the default). If the incremental algorithm is not used, then the current - * model is ignored and the new model will be trained only on the given data. - * Note that even if the incremental algorithm is not used, the data must have - * the same dimensionality and number of classes that the model was - * initialized with. If you want to change the dimensionality or number of - * classes, either re-initialize or call Means(), Variances(), and - * Probabilities() individually to set them to the right size. - * - * @param data The dataset to train on. - * @param labels The labels for the dataset. - * @param numClasses The numbe of classes in the dataset. - * @param incremental Whether or not to use the incremental algorithm for - * training. - */ - template - void Train(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const bool incremental = true); - - /** - * Train the Naive Bayes classifier on the given point. This will use the - * incremental algorithm for updating the model parameters. The data must be - * the same dimensionality as the existing model parameters. - * - * @param point Data point to train on. - * @param label Label of data point. - */ - template - void Train(const VecType& point, const size_t label); - - /** - * Classify the given point, using the trained NaiveBayesClassifier model. The - * predicted label is returned. - * - * @param point Point to classify. - */ - template - size_t Classify(const VecType& point) const; - - /** - * Classify the given point using the trained NaiveBayesClassifier model and - * also return estimates of the probability for each class in the given - * vector. - * - * @param point Point to classify. - * @param prediction This will be set to the predicted class of the point. - * @param probabilities This will be filled with class probabilities for the - * point. - */ - template - void Classify(const VecType& point, - size_t& prediction, - ProbabilitiesVecType& probabilities) const; - - /** - * Classify the given points using the trained NaiveBayesClassifier model. - * The predicted labels for each point are stored in the given vector. - * - * @code - * arma::mat test_data; // each column is a test point - * arma::Row results; - * ... - * nbc.Classify(test_data, results); - * @endcode - * - * @param data List of data points. - * @param predictions Vector that class predictions will be placed into. - */ - template - void Classify(const MatType& data, - arma::Row& predictions) const; - - /** - * Classify the given points using the trained NaiveBayesClassifier model and - * also return estimates of the probabilities for each class in the given - * matrix. The predicted labels for each point are stored in the given - * vector. - * - * @code - * arma::mat test_data; // each column is a test point - * arma::Row results; - * arma::mat resultsProbs; - * ... - * nbc.Classify(test_data, results, resultsProbs); - * @endcode - * - * @param data Set of points to classify. - * @param predictions This will be filled with predictions for each point. - * @param probabilities This will be filled with class probabilities for each - * point. Each row represents a point. - * @tparam MatType Type of data to be classified. - * @tparam ProbabilitiesMatType Type to store output probabilities in. - */ - template - void Classify(const MatType& data, - arma::Row& predictions, - ProbabilitiesMatType& probabilities) const; - - //! Get the sample means for each class. - const ModelMatType& Means() const { return means; } - //! Modify the sample means for each class. - ModelMatType& Means() { return means; } - - //! Get the sample variances for each class. - const ModelMatType& Variances() const { return variances; } - //! Modify the sample variances for each class. - ModelMatType& Variances() { return variances; } - - //! Get the prior probabilities for each class. - const ModelMatType& Probabilities() const { return probabilities; } - //! Modify the prior probabilities for each class. - ModelMatType& Probabilities() { return probabilities; } - - //! Serialize the classifier. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Sample mean for each class. - ModelMatType means; - //! Sample variances for each class. - ModelMatType variances; - //! Class probabilities; this has the shape of a column vector. - ModelMatType probabilities; - //! Number of training points seen so far. - size_t trainingPoints; - - /** - * Compute the unnormalized posterior log probability of given points (log - * likelihood). Results are returned as arma::mat, and each column represents - * a point, each row represents log likelihood of a class. - * - * @param data Set of points to compute posterior log probability for. - * @param logLikelihoods Matrix to store log likelihoods in. - */ - template - void LogLikelihood(const MatType& data, - ModelMatType& logLikelihoods) const; -}; - -} // namespace naive_bayes -} // namespace mlpack - -// Include implementation. -#include "naive_bayes_classifier_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/naive_bayes/naive_bayes_classifier_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/naive_bayes/naive_bayes_classifier_impl.hpp deleted file mode 100644 index 20fa070dd..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/naive_bayes/naive_bayes_classifier_impl.hpp +++ /dev/null @@ -1,354 +0,0 @@ -/** - * @file naive_bayes_classifier_impl.hpp - * @author Parikshit Ram (pram@cc.gatech.edu) - * @author Vahab Akbarzadeh (v.akbarzadeh@gmail.com) - * @author Shihao Jing (shihao.jing810@gmail.com) - * - * A Naive Bayes Classifier which parametrically estimates the distribution of - * the features. This classifier makes its predictions based on the assumption - * that the features have been sampled from a set of Gaussians with diagonal - * covariance. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NAIVE_BAYES_NAIVE_BAYES_CLASSIFIER_IMPL_HPP -#define MLPACK_METHODS_NAIVE_BAYES_NAIVE_BAYES_CLASSIFIER_IMPL_HPP - -#include - -// In case it hasn't been included already. -#include "naive_bayes_classifier.hpp" - -namespace mlpack { -namespace naive_bayes { - -template -template -NaiveBayesClassifier::NaiveBayesClassifier( - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const bool incremental) : - trainingPoints(0) // Set when we call Train(). -{ - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - - // Perform training, after initializing the model to 0 (that is, if Train() - // won't do that for us, which it won't if we're using the incremental - // algorithm). - if (incremental) - { - probabilities.zeros(numClasses); - means.zeros(data.n_rows, numClasses); - variances.zeros(data.n_rows, numClasses); - } - else - { - probabilities.set_size(numClasses); - means.set_size(data.n_rows, numClasses); - variances.set_size(data.n_rows, numClasses); - } - - Train(data, labels, numClasses, incremental); -} - -template -NaiveBayesClassifier::NaiveBayesClassifier( - const size_t dimensionality, - const size_t numClasses) : - trainingPoints(0) -{ - // Initialize model to 0. - probabilities.zeros(numClasses); - means.zeros(dimensionality, numClasses); - variances.zeros(dimensionality, numClasses); -} - -template -template -void NaiveBayesClassifier::Train( - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const bool incremental) -{ - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - - // Do we need to resize the model? - if (probabilities.n_elem != numClasses) - { - // Perform training, after initializing the model to 0 (that is, if Train() - // won't do that for us, which it won't if we're using the incremental - // algorithm). - if (incremental) - { - probabilities.zeros(numClasses); - means.zeros(data.n_rows, numClasses); - variances.zeros(data.n_rows, numClasses); - } - else - { - probabilities.set_size(numClasses); - means.set_size(data.n_rows, numClasses); - variances.set_size(data.n_rows, numClasses); - } - } - - // Calculate the class probabilities as well as the sample mean and variance - // for each of the features with respect to each of the labels. - if (incremental) - { - // Use incremental algorithm. - // Fist, de-normalize probabilities. - probabilities *= trainingPoints; - - for (size_t j = 0; j < data.n_cols; ++j) - { - const size_t label = labels[j]; - ++probabilities[label]; - - arma::vec delta = data.col(j) - means.col(label); - means.col(label) += delta / probabilities[label]; - variances.col(label) += delta % (data.col(j) - means.col(label)); - } - - for (size_t i = 0; i < probabilities.n_elem; ++i) - { - if (probabilities[i] > 2) - variances.col(i) /= (probabilities[i] - 1); - } - } - else - { - // Set all parameters to zero. - probabilities.zeros(); - means.zeros(); - variances.zeros(); - - // Don't use incremental algorithm. This is a two-pass algorithm. It is - // possible to calculate the means and variances using a faster one-pass - // algorithm but there are some precision and stability issues. If this is - // too slow, it's an option to use the faster algorithm by default and then - // have this (and the incremental algorithm) be other options. - - // Calculate the means. - for (size_t j = 0; j < data.n_cols; ++j) - { - const size_t label = labels[j]; - ++probabilities[label]; - means.col(label) += data.col(j); - } - - // Normalize means. - for (size_t i = 0; i < probabilities.n_elem; ++i) - if (probabilities[i] != 0.0) - means.col(i) /= probabilities[i]; - - // Calculate variances. - for (size_t j = 0; j < data.n_cols; ++j) - { - const size_t label = labels[j]; - variances.col(label) += square(data.col(j) - means.col(label)); - } - - // Normalize variances. - for (size_t i = 0; i < probabilities.n_elem; ++i) - if (probabilities[i] > 1) - variances.col(i) /= (probabilities[i] - 1); - } - - // Ensure that the variances are invertible. - for (size_t i = 0; i < variances.n_elem; ++i) - if (variances[i] == 0.0) - variances[i] = 1e-50; - - probabilities /= data.n_cols; - trainingPoints += data.n_cols; -} - -template -template -void NaiveBayesClassifier::Train(const VecType& point, - const size_t label) -{ - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - - // We must use the incremental algorithm here. - probabilities *= trainingPoints; - probabilities[label]++; - - arma::vec delta = point - means.col(label); - means.col(label) += delta / probabilities[label]; - if (probabilities[label] > 2) - variances.col(label) *= (probabilities[label] - 2); - variances.col(label) += (delta % (point - means.col(label))); - if (probabilities[label] > 1) - variances.col(label) /= probabilities[label] - 1; - - trainingPoints++; - probabilities /= trainingPoints; -} - -template -template -void NaiveBayesClassifier::LogLikelihood( - const MatType& data, - ModelMatType& logLikelihoods) const -{ - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - - logLikelihoods = arma::log(arma::repmat(probabilities, 1, data.n_cols)); - ModelMatType invVar = 1.0 / variances; - - // Calculate the joint log likelihood of point for each of the - // means.n_cols. - - // Loop over every class. - for (size_t i = 0; i < means.n_cols; i++) - { - // This is an adaptation of gmm::phi() for the case where the covariance is - // a diagonal matrix. - ModelMatType diffs = data - arma::repmat(means.col(i), 1, data.n_cols); - ModelMatType rhs = -0.5 * arma::diagmat(invVar.col(i)) * diffs; - arma::Mat exponents = arma::sum(diffs % rhs, 0); - - logLikelihoods.row(i) += (data.n_rows / -2.0 * log(2 * M_PI) - 0.5 * - std::log(arma::det(arma::diagmat(variances.col(i)))) + exponents); - } -} - -template -template -size_t NaiveBayesClassifier::Classify(const VecType& point) const -{ - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - - // Find the label(class) with max log likelihood. - ModelMatType logLikelihoods; - LogLikelihood(point, logLikelihoods); - - arma::uword maxIndex = 0; - logLikelihoods.max(maxIndex); - return maxIndex; -} - -template -template -void NaiveBayesClassifier::Classify( - const VecType& point, - size_t& prediction, - ProbabilitiesVecType& probabilities) const -{ - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - - // log(Prob(Y|X)) = Log(Prob(X|Y)) + Log(Prob(Y)) - Log(Prob(X)); - // But LogLikelihood() gives us the unnormalized log likelihood which is - // Log(Prob(X|Y)) + Log(Prob(Y)) so we need to subtract the normalization - // term. - ModelMatType logLikelihoods; - LogLikelihood(point, logLikelihoods); - const double logProbX = log(arma::accu(exp(logLikelihoods))); // Log(Prob(X)). - logLikelihoods -= logProbX; - - arma::uword maxIndex = 0; - logLikelihoods.max(maxIndex); - prediction = (size_t) maxIndex; - probabilities = exp(logLikelihoods); // log(exp(value)) == value. -} - -template -template -void NaiveBayesClassifier::Classify( - const MatType& data, - arma::Row& predictions) const -{ - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - - predictions.set_size(data.n_cols); - - ModelMatType logLikelihoods; - LogLikelihood(data, logLikelihoods); - - for (size_t i = 0; i < data.n_cols; ++i) - { - arma::uword maxIndex = 0; - logLikelihoods.unsafe_col(i).max(maxIndex); - predictions[i] = maxIndex; - } -} - -template -template -void NaiveBayesClassifier::Classify( - const MatType& data, - arma::Row& predictions, - ProbabilitiesMatType& predictionProbs) const -{ - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - static_assert(std::is_same::value, - "NaiveBayesClassifier: element type of given data must match the element " - "type of the model!"); - - predictions.set_size(data.n_cols); - - ModelMatType logLikelihoods; - LogLikelihood(data, logLikelihoods); - - // This will hold log(Prob(X)) for each point. - arma::Col logProbX(data.n_cols); - for (size_t j = 0; j < data.n_cols; ++j) - { - logProbX(j) = log(arma::accu(exp(logLikelihoods.col(j)))); - logLikelihoods.col(j) -= logProbX(j); - } - - predictionProbs = arma::exp(logLikelihoods); - - // Now calculate maximum probabilities for each point. - for (size_t i = 0; i < data.n_cols; ++i) - { - arma::uword maxIndex = 0; - logLikelihoods.unsafe_col(i).max(maxIndex); - predictions[i] = maxIndex; - } -} - -template -template -void NaiveBayesClassifier::serialize( - Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(means); - ar & BOOST_SERIALIZATION_NVP(variances); - ar & BOOST_SERIALIZATION_NVP(probabilities); -} - -} // namespace naive_bayes -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nca/nca.hpp b/src/sdk/mlpack/include/mlpack/methods/nca/nca.hpp deleted file mode 100644 index 22b8bce24..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nca/nca.hpp +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @file nca.hpp - * @author Ryan Curtin - * - * Declaration of NCA class (Neighborhood Components Analysis). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NCA_NCA_HPP -#define MLPACK_METHODS_NCA_NCA_HPP - -#include -#include -#include - -#include "nca_softmax_error_function.hpp" - -namespace mlpack { -namespace nca /** Neighborhood Components Analysis. */ { - -/** - * An implementation of Neighborhood Components Analysis, both a linear - * dimensionality reduction technique and a distance learning technique. The - * method seeks to improve k-nearest-neighbor classification on a dataset by - * scaling the dimensions. The method is nonparametric, and does not require a - * value of k. It works by using stochastic ("soft") neighbor assignments and - * using optimization techniques over the gradient of the accuracy of the - * neighbor assignments. - * - * For more details, see the following published paper: - * - * @code - * @inproceedings{Goldberger2004, - * author = {Goldberger, Jacob and Roweis, Sam and Hinton, Geoff and - * Salakhutdinov, Ruslan}, - * booktitle = {Advances in Neural Information Processing Systems 17}, - * pages = {513--520}, - * publisher = {MIT Press}, - * title = {{Neighbourhood Components Analysis}}, - * year = {2004} - * } - * @endcode - */ -template -class NCA -{ - public: - /** - * Construct the Neighborhood Components Analysis object. This simply stores - * the reference to the dataset and labels as well as the parameters for - * optimization before the actual optimization is performed. - * - * @param dataset Input dataset. - * @param labels Input dataset labels. - * @param stepSize Step size for stochastic gradient descent. - * @param maxIterations Maximum iterations for stochastic gradient descent. - * @param tolerance Tolerance for termination of stochastic gradient descent. - * @param shuffle Whether or not to shuffle the dataset during SGD. - * @param metric Instantiated metric to use. - */ - NCA(const arma::mat& dataset, - const arma::Row& labels, - MetricType metric = MetricType()); - - /** - * Perform Neighborhood Components Analysis. The output distance learning - * matrix is written into the passed reference. If LearnDistance() is called - * with an outputMatrix which has the correct size (dataset.n_rows x - * dataset.n_rows), that matrix will be used as the starting point for - * optimization. - * - * @param output_matrix Covariance matrix of Mahalanobis distance. - */ - void LearnDistance(arma::mat& outputMatrix); - - //! Get the dataset reference. - const arma::mat& Dataset() const { return dataset; } - //! Get the labels reference. - const arma::Row& Labels() const { return labels; } - - //! Get the optimizer. - const OptimizerType& Optimizer() const { return optimizer; } - OptimizerType& Optimizer() { return optimizer; } - - private: - //! Dataset reference. - const arma::mat& dataset; - //! Labels reference. - const arma::Row& labels; - - //! Metric to be used. - MetricType metric; - - //! The function to optimize. - SoftmaxErrorFunction errorFunction; - - //! The optimizer to use. - OptimizerType optimizer; -}; - -} // namespace nca -} // namespace mlpack - -// Include the implementation. -#include "nca_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nca/nca_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/nca/nca_impl.hpp deleted file mode 100644 index 314c97a5c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nca/nca_impl.hpp +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file nca_impl.hpp - * @author Ryan Curtin - * - * Implementation of templated NCA class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NCA_NCA_IMPL_HPP -#define MLPACK_METHODS_NCA_NCA_IMPL_HPP - -// In case it was not already included. -#include "nca.hpp" - -namespace mlpack { -namespace nca { - -// Just set the internal matrix reference. -template -NCA::NCA(const arma::mat& dataset, - const arma::Row& labels, - MetricType metric) : - dataset(dataset), - labels(labels), - metric(metric), - errorFunction(dataset, labels, metric) -{ /* Nothing to do. */ } - -template -void NCA::LearnDistance(arma::mat& outputMatrix) -{ - // See if we were passed an initialized matrix. - if ((outputMatrix.n_rows != dataset.n_rows) || - (outputMatrix.n_cols != dataset.n_rows)) - outputMatrix.eye(dataset.n_rows, dataset.n_rows); - - Timer::Start("nca_sgd_optimization"); - - optimizer.Optimize(errorFunction, outputMatrix); - - Timer::Stop("nca_sgd_optimization"); -} - -} // namespace nca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nca/nca_softmax_error_function.hpp b/src/sdk/mlpack/include/mlpack/methods/nca/nca_softmax_error_function.hpp deleted file mode 100644 index e2372971e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nca/nca_softmax_error_function.hpp +++ /dev/null @@ -1,177 +0,0 @@ -/** - * @file nca_softmax_error_function.hpp - * @author Ryan Curtin - * - * Implementation of the stochastic neighbor assignment probability error - * function (the "softmax error"). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NCA_NCA_SOFTMAX_ERROR_FUNCTION_HPP -#define MLPACK_METHODS_NCA_NCA_SOFTMAX_ERROR_FUNCTION_HPP - -#include -#include - -namespace mlpack { -namespace nca { - -/** - * The "softmax" stochastic neighbor assignment probability function. - * - * The actual function is - * - * p_ij = (exp(-|| A x_i - A x_j || ^ 2)) / - * (sum_{k != i} (exp(-|| A x_i - A x_k || ^ 2))) - * - * where x_n represents a point and A is the current scaling matrix. - * - * This class is more flexible than the original paper, allowing an arbitrary - * metric function to be used in place of || A x_i - A x_j ||^2, meaning that - * the squared Euclidean distance is not the only allowed metric for NCA. - * However, that is probably the best way to use this class. - * - * In addition to the standard Evaluate() and Gradient() functions which mlpack - * optimizers use, overloads of Evaluate() and Gradient() are given which only - * operate on one point in the dataset. This is useful for optimizers like - * stochastic gradient descent (see mlpack::optimization::SGD). - */ -template -class SoftmaxErrorFunction -{ - public: - /** - * Initialize with the given kernel; useful when the kernel has some state to - * store, which is set elsewhere. If no kernel is given, an empty kernel is - * used; this way, you can call the constructor with no arguments. A - * reference to the dataset we will be optimizing over is also required. - * - * @param dataset Matrix containing the dataset. - * @param labels Vector of class labels for each point in the dataset. - * @param kernel Instantiated kernel (optional). - */ - SoftmaxErrorFunction(const arma::mat& dataset, - const arma::Row& labels, - MetricType metric = MetricType()); - - /** - * Shuffle the dataset. - */ - void Shuffle(); - - /** - * Evaluate the softmax function for the given covariance matrix. This is the - * non-separable implementation, where the objective function is not - * decomposed into the sum of several objective functions. - * - * @param covariance Covariance matrix of Mahalanobis distance. - */ - double Evaluate(const arma::mat& covariance); - - /** - * Evaluate the softmax objective function for the given covariance matrix on - * the given batch size from a given inital point of the dataset. - * This is the separable implementation, where the objective - * function is decomposed into the sum of many objective - * functions, and here, only one of those constituent objective functions is - * returned. - * - * @param covariance Covariance matrix of Mahalanobis distance. - * @param begin Index of the initial point to use for objective function. - * @param batchSize Number of points to use for objective function. - */ - double Evaluate(const arma::mat& covariance, - const size_t begin, - const size_t batchSize = 1); - - /** - * Evaluate the gradient of the softmax function for the given covariance - * matrix. This is the non-separable implementation, where the objective - * function is not decomposed into the sum of several objective functions. - * - * @param covariance Covariance matrix of Mahalanobis distance. - * @param gradient Matrix to store the calculated gradient in. - */ - void Gradient(const arma::mat& covariance, arma::mat& gradient); - - /** - * Evaluate the gradient of the softmax function for the given covariance - * matrix on the given batch size, from a given initial point of the dataset. - * This is the separable implementation, where the objective function is - * decomposed into the sum of many objective functions, and here, - * only one of those constituent objective functions is returned. - * The type of the gradient parameter is a template - * argument to allow the computation of a sparse gradient. - * - * @tparam GradType The type of the gradient out-param. - * @param covariance Covariance matrix of Mahalanobis distance. - * @param begin Index of the initial point to use for objective function. - * @param batchSize Number of points to use for objective function. - * @param gradient Matrix to store the calculated gradient in. - */ - template - void Gradient(const arma::mat& covariance, - const size_t begin, - GradType& gradient, - const size_t batchSize = 1); - - /** - * Get the initial point. - */ - const arma::mat GetInitialPoint() const; - - /** - * Get the number of functions the objective function can be decomposed into. - * This is just the number of points in the dataset. - */ - size_t NumFunctions() const { return dataset.n_cols; } - - private: - //! The dataset. This is an alias until Shuffle() is called. - arma::mat dataset; - //! Labels for each point in the dataset. This is an alias until Shuffle() is - //! called. - arma::Row labels; - - //! The instantiated metric. - MetricType metric; - - //! Last coordinates. Used for the non-separable Evaluate() and Gradient(). - arma::mat lastCoordinates; - //! Stretched dataset. Kept internal to avoid memory reallocations. - arma::mat stretchedDataset; - //! Holds calculated p_i, for the non-separable Evaluate() and Gradient(). - arma::vec p; - //! Holds denominators for calculation of p_ij, for the non-separable - //! Evaluate() and Gradient(). - arma::vec denominators; - - //! False if nothing has ever been precalculated (only at construction time). - bool precalculated; - - /** - * Precalculate the denominators and numerators that will make up the p_ij, - * but only if the coordinates matrix is different than the last coordinates - * the Precalculate() method was run with. This method is only called by the - * non-separable Evaluate() and Gradient(). - * - * This will update last_coordinates_ and stretched_dataset_, and also - * calculate the p_i and denominators_ which are used in the calculation of - * p_i or p_ij. The calculation will be O((n * (n + 1)) / 2), which is not - * great. - * - * @param coordinates Coordinates matrix to use for precalculation. - */ - void Precalculate(const arma::mat& coordinates); -}; - -} // namespace nca -} // namespace mlpack - -// Include implementation. -#include "nca_softmax_error_function_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nca/nca_softmax_error_function_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/nca/nca_softmax_error_function_impl.hpp deleted file mode 100644 index 506970a50..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nca/nca_softmax_error_function_impl.hpp +++ /dev/null @@ -1,310 +0,0 @@ -/** - * @file nca_softmax_impl.h - * @author Ryan Curtin - * - * Implementation of the Softmax error function. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NCA_NCA_SOFTMAX_ERROR_FUNCTCLIN_IMPL_H -#define MLPACK_METHODS_NCA_NCA_SOFTMAX_ERROR_FUNCTCLIN_IMPL_H - -// In case it hasn't been included already. -#include "nca_softmax_error_function.hpp" - -namespace mlpack { -namespace nca { - -// Initialize with the given kernel. -template -SoftmaxErrorFunction::SoftmaxErrorFunction( - const arma::mat& dataset, - const arma::Row& labels, - MetricType metric) : - dataset(math::MakeAlias(const_cast(dataset), false)), - labels(math::MakeAlias(const_cast&>(labels), false)), - metric(metric), - precalculated(false) -{ /* nothing to do */ } - -//! Shuffle the dataset. -template -void SoftmaxErrorFunction::Shuffle() -{ - arma::mat newDataset; - arma::Row newLabels; - - math::ShuffleData(dataset, labels, newDataset, newLabels); - - math::ClearAlias(dataset); - math::ClearAlias(labels); - - dataset = std::move(newDataset); - labels = std::move(newLabels); -} - -//! The non-separable implementation, which uses Precalculate() to save time. -template -double SoftmaxErrorFunction::Evaluate(const arma::mat& coordinates) -{ - // Calculate the denominators and numerators, if necessary. - Precalculate(coordinates); - - return -accu(p); // Sum of p_i for all i. We negate because our solver - // minimizes, not maximizes. -}; - -//! The separated objective function, which does not use Precalculate(), -//! for a given batch size and from an initial index. -template -double SoftmaxErrorFunction::Evaluate(const arma::mat& coordinates, - const size_t begin, - const size_t batchSize) -{ - // Unfortunately each evaluation will take O(N) time because it requires a - // scan over all points in the dataset. Our objective is to compute p_i. - double denominator = 0; - double numerator = 0; - double result = 0; - - // It's quicker to do this now than one point at a time later. - stretchedDataset = coordinates * dataset; - for (size_t i = begin; i < begin + batchSize; i++) - { - for (size_t k = 0; k < dataset.n_cols; ++k) - { - // Don't consider the case where the points are the same. - if (k == i) - continue; - - // We want to evaluate exp(-D(A x_i, A x_k)). - double eval = std::exp(-metric.Evaluate(stretchedDataset.unsafe_col(i), - stretchedDataset.unsafe_col(k))); - - // If they are in the same class, update the numerator. - if (labels[i] == labels[k]) - numerator += eval; - - denominator += eval; - } - - // Now the result is just a simple division, but we have to be sure that the - // denominator is not 0. - if (denominator == 0.0) - { - Log::Warn << "Denominator of p_" << i << " is 0!" << std::endl; - continue; - } - - result += -(numerator / denominator); // Negate because the optimizer is a - // minimizer. - } - return result; -} - -//! The non-separable implementation, where Precalculate() is used. -template -void SoftmaxErrorFunction::Gradient(const arma::mat& coordinates, - arma::mat& gradient) -{ - // Calculate the denominators and numerators, if necessary. - Precalculate(coordinates); - - // Now, we handle the summation over i: - // sum_i (p_i sum_k (p_ik x_ik x_ik^T) - - // sum_{j in class of i} (p_ij x_ij x_ij^T) - // We can algebraically manipulate the whole thing to produce a more - // memory-friendly way to calculate this. Looping over each i and k (again - // O((n * (n + 1)) / 2) as with the last step, we can add the following to the - // sum: - // - // if class of i is the same as the class of k, add - // (((p_i - (1 / p_i)) p_ik) + ((p_k - (1 / p_k)) p_ki)) x_ik x_ik^T - // otherwise, add - // (p_i p_ik + p_k p_ki) x_ik x_ik^T - arma::mat sum; - sum.zeros(stretchedDataset.n_rows, stretchedDataset.n_rows); - for (size_t i = 0; i < stretchedDataset.n_cols; i++) - { - for (size_t k = (i + 1); k < stretchedDataset.n_cols; k++) - { - // Calculate p_ik and p_ki first. - double eval = exp(-metric.Evaluate(stretchedDataset.unsafe_col(i), - stretchedDataset.unsafe_col(k))); - double p_ik = 0, p_ki = 0; - p_ik = eval / denominators(i); - p_ki = eval / denominators(k); - - // Subtract x_i from x_k. We are not using stretched points here. - arma::vec x_ik = dataset.col(i) - dataset.col(k); - arma::mat secondTerm = (x_ik * trans(x_ik)); - - if (labels[i] == labels[k]) - sum += ((p[i] - 1) * p_ik + (p[k] - 1) * p_ki) * secondTerm; - else - sum += (p[i] * p_ik + p[k] * p_ki) * secondTerm; - } - } - - // Assemble the final gradient. - gradient = -2 * coordinates * sum; -} - -//! The separable implementation for a given batch size and an initial index. -template -template -void SoftmaxErrorFunction::Gradient(const arma::mat& coordinates, - const size_t begin, - GradType& gradient, - const size_t batchSize) -{ - // The gradient involves two matrix terms which are eventually combined into - // one. - GradType firstTerm, secondTerm; - // We will need to calculate p_i before this evaluation is done, so - // these two variables will hold the information necessary for that. - double numerator, denominator; - - gradient.zeros(coordinates.n_rows, coordinates.n_rows); - - // Compute the stretched dataset. - stretchedDataset = coordinates * dataset; - for (size_t i = begin; i < begin + batchSize; i++) - { - numerator = 0; - denominator = 0; - - firstTerm.zeros(coordinates.n_rows, coordinates.n_cols); - secondTerm.zeros(coordinates.n_rows, coordinates.n_cols); - - for (size_t k = 0; k < dataset.n_cols; ++k) - { - // Don't consider the case where the points are the same. - if (i == k) - continue; - - // Calculate the numerator of p_ik. - double eval = exp(-metric.Evaluate(stretchedDataset.unsafe_col(i), - stretchedDataset.unsafe_col(k))); - - // If the points are in the same class, we must add to the second term of - // the gradient as well as the numerator of p_i. We will divide by the - // denominator of p_ik later. For x_ik we are not using stretched points. - GradType x_ik = dataset.col(i) - dataset.col(k); - if (labels[i] == labels[k]) - { - numerator += eval; - secondTerm += eval * x_ik * trans(x_ik); - } - - // We always have to add to the denominator of p_i - // and the first term of the gradient computation. - // We will divide by the denominator of p_ik later. - denominator += eval; - firstTerm += eval * x_ik * trans(x_ik); - } - - // Calculate p_i. - double p = 0; - if (denominator == 0) - { - Log::Warn << "Denominator of p_" << i << " is 0!" << std::endl; - // If the denominator is zero, then all p_ik should be zero and there is - // no gradient contribution from this point. - continue; - } - else - { - p = numerator / denominator; - firstTerm /= denominator; - secondTerm /= denominator; - } - - // Now multiply the first term by p_i, and add the two together and multiply - // all by 2 * A. We negate it though, because our optimizer is a minimizer. - gradient += -2 * coordinates * (p * firstTerm - secondTerm); - } -} - -template -const arma::mat SoftmaxErrorFunction::GetInitialPoint() const -{ - return arma::eye(dataset.n_rows, dataset.n_rows); -} - -template -void SoftmaxErrorFunction::Precalculate( - const arma::mat& coordinates) -{ - // Ensure it is the right size. - if (lastCoordinates.n_rows != coordinates.n_rows || - lastCoordinates.n_cols != coordinates.n_cols) - { - lastCoordinates.set_size(coordinates.n_rows, coordinates.n_cols); - } - else if ((accu(coordinates == lastCoordinates) == coordinates.n_elem) && - precalculated) - { - return; // No need to calculate; we already have this stuff saved. - } - - // Coordinates are different; save the new ones, and stretch the dataset. - lastCoordinates = coordinates; - stretchedDataset = coordinates * dataset; - - // For each point i, we must evaluate the softmax function: - // p_ij = exp( -K(x_i, x_j) ) / ( sum_{k != i} ( exp( -K(x_i, x_k) ))) - // p_i = sum_{j in class of i} p_ij - // We will do this by keeping track of the denominators for each i as well as - // the numerators (the sum for all j in class of i). This will be on the - // order of O((n * (n + 1)) / 2), which really isn't all that great. - p.zeros(stretchedDataset.n_cols); - denominators.zeros(stretchedDataset.n_cols); - for (size_t i = 0; i < stretchedDataset.n_cols; i++) - { - for (size_t j = (i + 1); j < stretchedDataset.n_cols; j++) - { - // Evaluate exp(-d(x_i, x_j)). - double eval = exp(-metric.Evaluate(stretchedDataset.unsafe_col(i), - stretchedDataset.unsafe_col(j))); - - // Add this to the denominators of both p_i and p_j: K(i, j) = K(j, i). - denominators[i] += eval; - denominators[j] += eval; - - // If i and j are the same class, add to numerator of both. - if (labels[i] == labels[j]) - { - p[i] += eval; - p[j] += eval; - } - } - } - - // Divide p_i by their denominators. - p /= denominators; - - // Clean up any bad values. - for (size_t i = 0; i < stretchedDataset.n_cols; i++) - { - if (denominators[i] == 0.0) - { - Log::Debug << "Denominator of p_{" << i << ", j} is 0." << std::endl; - - // Set to usable values. - denominators[i] = std::numeric_limits::infinity(); - p[i] = 0; - } - } - - // We've done a precalculation. Mark it as done. - precalculated = true; -} - -} // namespace nca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search.hpp deleted file mode 100644 index 0086c16ff..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search.hpp +++ /dev/null @@ -1,376 +0,0 @@ -/** - * @file neighbor_search.hpp - * @author Ryan Curtin - * - * Defines the NeighborSearch class, which performs an abstract - * nearest-neighbor-like query on two datasets. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_HPP - -#include -#include -#include - -#include -#include -#include - -#include "neighbor_search_stat.hpp" -#include "sort_policies/nearest_neighbor_sort.hpp" -#include "neighbor_search_rules.hpp" - -namespace mlpack { -// Neighbor-search routines. These include all-nearest-neighbors and -// all-furthest-neighbors searches. -namespace neighbor { - -// Forward declaration. -template -class TrainVisitor; - -//! NeighborSearchMode represents the different neighbor search modes available. -enum NeighborSearchMode -{ - NAIVE_MODE, - SINGLE_TREE_MODE, - DUAL_TREE_MODE, - GREEDY_SINGLE_TREE_MODE -}; - -/** - * The NeighborSearch class is a template class for performing distance-based - * neighbor searches. It takes a query dataset and a reference dataset (or just - * a reference dataset) and, for each point in the query dataset, finds the k - * neighbors in the reference dataset which have the 'best' distance according - * to a given sorting policy. A constructor is given which takes only a - * reference dataset, and if that constructor is used, the given reference - * dataset is also used as the query dataset. - * - * The template parameters SortPolicy and Metric define the sort function used - * and the metric (distance function) used. More information on those classes - * can be found in the NearestNeighborSort class and the kernel::ExampleKernel - * class. - * - * @tparam SortPolicy The sort policy for distances; see NearestNeighborSort. - * @tparam MetricType The metric to use for computation. - * @tparam MatType The type of data matrix. - * @tparam TreeType The tree type to use; must adhere to the TreeType API. - * @tparam DualTreeTraversalType The type of dual tree traversal to use - * (defaults to the tree's default traverser). - * @tparam SingleTreeTraversalType The type of single tree traversal to use - * (defaults to the tree's default traverser). - */ -template class TreeType = tree::KDTree, - template class DualTreeTraversalType = - TreeType, - MatType>::template DualTreeTraverser, - template class SingleTreeTraversalType = - TreeType, - MatType>::template SingleTreeTraverser> -class NeighborSearch -{ - public: - //! Convenience typedef. - typedef TreeType, MatType> Tree; - - /** - * Initialize the NeighborSearch object, passing a reference dataset (this is - * the dataset which is searched). Optionally, perform the computation in - * a different mode. An initialized distance metric can be given, for cases - * where the metric has internal data (i.e. the distance::MahalanobisDistance - * class). - * - * This method will move the matrices to internal copies, which are rearranged - * during tree-building. You can avoid creating an extra copy by pre-constructing - * the trees, passing std::move(yourReferenceSet). - * - * @param referenceSet Set of reference points. - * @param mode Neighbor search mode. - * @param epsilon Relative approximate error (non-negative). - * @param metric An optional instance of the MetricType class. - */ - NeighborSearch(MatType referenceSet, - const NeighborSearchMode mode = DUAL_TREE_MODE, - const double epsilon = 0, - const MetricType metric = MetricType()); - - /** - * Initialize the NeighborSearch object with a copy of the given - * pre-constructed reference tree (this is the tree built on the points that - * will be searched). Optionally, choose to use single-tree mode. Naive mode - * is not available as an option for this constructor. Additionally, an - * instantiated distance metric can be given, for cases where the distance - * metric holds data. - * - * This method will copy the given tree. When copies must absolutely be avoided, - * you can avoid this copy, while taking ownership of the given tree, by passing - * std::move(yourReferenceTree) - * - * @note - * Mapping the points of the matrix back to their original indices is not done - * when this constructor is used, so if the tree type you are using maps - * points (like BinarySpaceTree), then you will have to perform the re-mapping - * manually. - * @endnote - * - * @param referenceTree Pre-built tree for reference points. - * @param mode Neighbor search mode. - * @param epsilon Relative approximate error (non-negative). - * @param metric Instantiated distance metric. - */ - NeighborSearch(Tree referenceTree, - const NeighborSearchMode mode = DUAL_TREE_MODE, - const double epsilon = 0, - const MetricType metric = MetricType()); - - /** - * Create a NeighborSearch object without any reference data. If Search() is - * called before a reference set is set with Train(), an exception will be - * thrown. - * - * @param mode Neighbor search mode. - * @param epsilon Relative approximate error (non-negative). - * @param metric Instantiated metric. - */ - NeighborSearch(const NeighborSearchMode mode = DUAL_TREE_MODE, - const double epsilon = 0, - const MetricType metric = MetricType()); - - /** - * Construct the NeighborSearch object by copying the given NeighborSearch - * object. - * - * @param other NeighborSearch object to copy. - */ - NeighborSearch(const NeighborSearch& other); - - /** - * Construct the NeighborSearch object by taking ownership of the given - * NeighborSearch object. - * - * @param other NeighborSearch object to take ownership of. - */ - NeighborSearch(NeighborSearch&& other); - - /** - * Copy the given NeighborSearch object. - * - * @param other NeighborSearch object to copy. - */ - NeighborSearch& operator=(const NeighborSearch& other); - - /** - * Take ownership of the given NeighborSearch object. - * - * @param other NeighborSearch object to take ownership of. - */ - NeighborSearch& operator=(NeighborSearch&& other); - - /** - * Delete the NeighborSearch object. The tree is the only member we are - * responsible for deleting. The others will take care of themselves. - */ - ~NeighborSearch(); - - /** - * Set the reference set to a new reference set, and build a tree if - * necessary. The dataset is copied by default, but the copy can be avoided by - * transferring the ownership of the dataset using std::move(). This method - * is called 'Train()' in order to match the rest of the mlpack abstractions, - * even though calling this "training" is maybe a bit of a stretch. - * - * @param referenceSet New set of reference data. - */ - void Train(MatType referenceSet); - - /** - * Set the reference tree to a new reference tree. The tree is copied by - * default, but the copy can be avoided by using std::move() to transfer the - * ownership of the tree. This method is called 'Train()' in order to match - * the rest of the mlpack abstractions, even though calling this "training" is - * maybe a bit of a stretch. - * - * @param referenceTree Pre-built tree for reference points. - */ - void Train(Tree referenceTree); - - /** - * For each point in the query set, compute the nearest neighbors and store - * the output in the given matrices. The matrices will be set to the size of - * n columns by k rows, where n is the number of points in the query dataset - * and k is the number of neighbors being searched for. - * - * If querySet contains only a few query points, the extra cost of building a - * tree on the points for dual-tree search may not be warranted, and it may be - * worthwhile to set singleMode = false (either in the constructor or with - * SingleMode()). - * - * @param querySet Set of query points (can be just one point). - * @param k Number of neighbors to search for. - * @param neighbors Matrix storing lists of neighbors for each query point. - * @param distances Matrix storing distances of neighbors for each query - * point. - */ - void Search(const MatType& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - /** - * Given a pre-built query tree, search for the nearest neighbors of each - * point in the query tree, storing the output in the given matrices. The - * matrices will be set to the size of n columns by k rows, where n is the - * number of points in the query dataset and k is the number of neighbors - * being searched for. - * - * Note that if you are calling Search() multiple times with a single query - * tree, you need to reset the bounds in the statistic of each query node, - * otherwise the result may be wrong! You can do this by calling - * TreeType::Stat()::Reset() on each node in the query tree. - * - * @param queryTree Tree built on query points. - * @param k Number of neighbors to search for. - * @param neighbors Matrix storing lists of neighbors for each query point. - * @param distances Matrix storing distances of neighbors for each query - * point. - * @param sameSet Denotes whether or not the reference and query sets are the - * same. - */ - void Search(Tree& queryTree, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances, - bool sameSet = false); - - /** - * Search for the nearest neighbors of every point in the reference set. This - * is basically equivalent to calling any other overload of Search() with the - * reference set as the query set; so, this lets you do - * all-k-nearest-neighbors search. The results are stored in the given - * matrices. The matrices will be set to the size of n columns by k rows, - * where n is the number of points in the query dataset and k is the number of - * neighbors being searched for. - * - * @param k Number of neighbors to search for. - * @param neighbors Matrix storing lists of neighbors for each query point. - * @param distances Matrix storing distances of neighbors for each query - * point. - */ - void Search(const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - /** - * Calculate the average relative error (effective error) between the - * distances calculated and the true distances provided. The input matrices - * must have the same size. - * - * Cases where the true distance is zero (the same point) or the calculated - * distance is SortPolicy::WorstDistance() (didn't find enough points) will be - * ignored. - * - * @param foundDistances Matrix storing lists of calculated distances for each - * query point. - * @param realDistances Matrix storing lists of true best distances for each - * query point. - * @return Average relative error. - */ - static double EffectiveError(arma::mat& foundDistances, - arma::mat& realDistances); - - /** - * Calculate the recall (% of neighbors found) given the list of found - * neighbors and the true set of neighbors. The recall returned will be in - * the range [0, 1]. - * - * @param foundNeighbors Matrix storing lists of calculated neighbors for each - * query point. - * @param realNeighbors Matrix storing lists of true best neighbors for each - * query point. - * @return Recall. - */ - static double Recall(arma::Mat& foundNeighbors, - arma::Mat& realNeighbors); - - //! Return the total number of base case evaluations performed during the last - //! search. - size_t BaseCases() const { return baseCases; } - - //! Return the number of node combination scores during the last search. - size_t Scores() const { return scores; } - - //! Access the search mode. - NeighborSearchMode SearchMode() const { return searchMode; } - //! Modify the search mode. - NeighborSearchMode& SearchMode() { return searchMode; } - - //! Access the relative error to be considered in approximate search. - double Epsilon() const { return epsilon; } - //! Modify the relative error to be considered in approximate search. - double& Epsilon() { return epsilon; } - - //! Access the reference dataset. - const MatType& ReferenceSet() const { return *referenceSet; } - - //! Access the reference tree. - const Tree& ReferenceTree() const { return *referenceTree; } - //! Modify the reference tree. - Tree& ReferenceTree() { return *referenceTree; } - - //! Serialize the NeighborSearch model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Permutations of reference points during tree building. - std::vector oldFromNewReferences; - //! Pointer to the root of the reference tree. - Tree* referenceTree; - //! Reference dataset. In some situations we may be the owner of this. - const MatType* referenceSet; - - //! Indicates the neighbor search mode. - NeighborSearchMode searchMode; - //! Indicates the relative error to be considered in approximate search. - double epsilon; - - //! Instantiation of metric. - MetricType metric; - - //! The total number of base cases. - size_t baseCases; - //! The total number of scores (applicable for non-naive search). - size_t scores; - - //! If this is true, the reference tree bounds need to be reset on a call to - //! Search() without a query set. - bool treeNeedsReset; - - //! The NSModel class should have access to internal members. - template - friend class TrainVisitor; -}; // class NeighborSearch - -} // namespace neighbor -} // namespace mlpack - -// Include implementation. -#include "neighbor_search_impl.hpp" - -// Include convenience typedefs. -#include "typedef.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_impl.hpp deleted file mode 100644 index b5f60c346..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_impl.hpp +++ /dev/null @@ -1,1030 +0,0 @@ -/** - * @file neighbor_search_impl.hpp - * @author Ryan Curtin - * - * Implementation of Neighbor-Search class to perform all-nearest-neighbors on - * two specified data sets. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_IMPL_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_IMPL_HPP - -#include -#include -#include "neighbor_search_rules.hpp" -#include - -namespace mlpack { -namespace neighbor { - -//! Call the tree constructor that does mapping. -template -TreeType* BuildTree( - MatType&& dataset, - std::vector& oldFromNew, - typename std::enable_if_t< - tree::TreeTraits::RearrangesDataset, TreeType - >* = 0) -{ - return new TreeType(std::forward(dataset), oldFromNew); -} - -//! Call the tree constructor that does not do mapping. -template -TreeType* BuildTree( - MatType&& dataset, - const std::vector& /* oldFromNew */, - const typename std::enable_if_t< - !tree::TreeTraits::RearrangesDataset, TreeType - >* = 0) -{ - return new TreeType(std::forward(dataset)); -} - -// Construct the object. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -NeighborSearch::NeighborSearch(MatType referenceSetIn, - const NeighborSearchMode mode, - const double epsilon, - const MetricType metric) : - referenceTree(mode == NAIVE_MODE ? NULL : - BuildTree(std::move(referenceSetIn), oldFromNewReferences)), - referenceSet(mode == NAIVE_MODE ? new MatType(std::move(referenceSetIn)) : - &referenceTree->Dataset()), - searchMode(mode), - epsilon(epsilon), - metric(metric), - baseCases(0), - scores(0), - treeNeedsReset(false) -{ - if (epsilon < 0) - throw std::invalid_argument("epsilon must be non-negative"); -} - -// Construct the object. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -NeighborSearch::NeighborSearch(Tree referenceTree, - const NeighborSearchMode mode, - const double epsilon, - const MetricType metric) : - referenceTree(new Tree(std::move(referenceTree))), - referenceSet(&this->referenceTree->Dataset()), - searchMode(mode), - epsilon(epsilon), - metric(metric), - baseCases(0), - scores(0), - treeNeedsReset(false) -{ - if (epsilon < 0) - throw std::invalid_argument("epsilon must be non-negative"); -} - -// Construct the object without a reference dataset. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -NeighborSearch::NeighborSearch(const NeighborSearchMode mode, - const double epsilon, - const MetricType metric) : - referenceTree(NULL), - referenceSet(new MatType()), // Empty matrix. - searchMode(mode), - epsilon(epsilon), - metric(metric), - baseCases(0), - scores(0), - treeNeedsReset(false) -{ - if (epsilon < 0) - throw std::invalid_argument("epsilon must be non-negative"); - - // Build the tree on the empty dataset, if necessary. - if (mode != NAIVE_MODE) - { - referenceTree = BuildTree(*referenceSet, oldFromNewReferences); - referenceSet = &referenceTree->Dataset(); - } -} - -// Copy constructor. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -NeighborSearch::NeighborSearch(const NeighborSearch& other) : - oldFromNewReferences(other.oldFromNewReferences), - referenceTree(other.referenceTree ? new Tree(*other.referenceTree) : NULL), - referenceSet(other.referenceTree ? &referenceTree->Dataset() : - new MatType(*other.referenceSet)), - searchMode(other.searchMode), - epsilon(other.epsilon), - metric(other.metric), - baseCases(other.baseCases), - scores(other.scores), - treeNeedsReset(false) -{ - // Nothing else to do. -} - -// Move constructor. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -NeighborSearch::NeighborSearch(NeighborSearch&& other) : - oldFromNewReferences(std::move(other.oldFromNewReferences)), - referenceTree(other.referenceTree), - referenceSet(other.referenceSet), - searchMode(other.searchMode), - epsilon(other.epsilon), - metric(std::move(other.metric)), - baseCases(other.baseCases), - scores(other.scores), - treeNeedsReset(other.treeNeedsReset) -{ - // Clear the other model. - other.referenceSet = new MatType(); - other.referenceTree = BuildTree(*other.referenceSet, - other.oldFromNewReferences); - other.referenceSet = &other.referenceTree->Dataset(); - other.searchMode = DUAL_TREE_MODE, - other.epsilon = 0.0; - other.baseCases = 0; - other.scores = 0; - other.treeNeedsReset = false; -} - -// Copy operator. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -NeighborSearch& -NeighborSearch::operator=(const NeighborSearch& other) -{ - if (&other == this) - return *this; // Nothing to do. - - // Clean memory first. - if (referenceTree) - { - delete referenceTree; - referenceTree = NULL; - } - else - { - delete referenceSet; - referenceSet = NULL; - } - - oldFromNewReferences = other.oldFromNewReferences; - referenceTree = other.referenceTree ? new Tree(*other.referenceTree) : NULL; - referenceSet = other.referenceTree ? &referenceTree->Dataset() : - new MatType(*other.referenceSet); - searchMode = other.searchMode; - epsilon = other.epsilon; - metric = other.metric; - baseCases = other.baseCases; - scores = other.scores; - treeNeedsReset = false; -} - -// Move operator. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -NeighborSearch& -NeighborSearch::operator=(NeighborSearch&& other) -{ - if (&other == this) - return *this; // Nothing to do. - - // Clean memory first. - if (referenceTree) - { - delete referenceTree; - referenceTree = NULL; - } - else - { - delete referenceSet; - referenceSet = NULL; - } - - oldFromNewReferences = std::move(other.oldFromNewReferences); - referenceTree = other.referenceTree; - referenceSet = other.referenceSet; - searchMode = other.searchMode; - epsilon = other.epsilon; - metric = other.metric; - baseCases = other.baseCases; - scores = other.scores; - treeNeedsReset = other.treeNeedsReset; - - // Reset the other object. - other.referenceTree = BuildTree(*other.referenceSet, - other.oldFromNewReferences); - other.referenceSet = &other.referenceTree->Dataset(); - other.searchMode = DUAL_TREE_MODE, - other.epsilon = 0.0; - other.baseCases = 0; - other.scores = 0; - other.treeNeedsReset = false; -} - -// Clean memory. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -NeighborSearch::~NeighborSearch() -{ - if (referenceTree) - { - delete referenceTree; - referenceTree = NULL; - } - else - { - delete referenceSet; - referenceSet = NULL; - } -} - -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -void NeighborSearch::Train(MatType referenceSetIn) -{ - // Clean up the old tree, if we built one. - if (referenceTree) - { - oldFromNewReferences.clear(); - delete referenceTree; - referenceTree = NULL; - } - else - { - delete referenceSet; - referenceSet = NULL; - } - - // We may need to rebuild the tree. - if (searchMode != NAIVE_MODE) - { - referenceTree = BuildTree(std::move(referenceSetIn), - oldFromNewReferences); - referenceSet = &referenceTree->Dataset(); - } - else - { - referenceSet = new MatType(std::move(referenceSetIn)); - } -} - -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -void NeighborSearch::Train(Tree referenceTree) -{ - if (searchMode == NAIVE_MODE) - throw std::invalid_argument("cannot train on given reference tree when " - "naive search (without trees) is desired"); - - if (this->referenceTree) - { - oldFromNewReferences.clear(); - delete this->referenceTree; - this->referenceTree = NULL; - } - else - { - delete this->referenceSet; - this->referenceSet = NULL; - } - - this->referenceTree = new Tree(std::move(referenceTree)); - this->referenceSet = &this->referenceTree->Dataset(); -} - -/** - * Computes the best neighbors and stores them in resultingNeighbors and - * distances. - */ -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -void NeighborSearch::Search( - const MatType& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - if (k > referenceSet->n_cols) - { - std::stringstream ss; - ss << "Requested value of k (" << k << ") is greater than the number of " - << "points in the reference set (" << referenceSet->n_cols << ")"; - throw std::invalid_argument(ss.str()); - } - - Timer::Start("computing_neighbors"); - - baseCases = 0; - scores = 0; - - // This will hold mappings for query points, if necessary. - std::vector oldFromNewQueries; - - // If we have built the trees ourselves, then we will have to map all the - // indices back to their original indices when this computation is finished. - // To avoid an extra copy, we will store the neighbors and distances in a - // separate matrix. - arma::Mat* neighborPtr = &neighbors; - arma::mat* distancePtr = &distances; - - // Mapping is only necessary if the tree rearranges points. - if (tree::TreeTraits::RearrangesDataset) - { - if (searchMode == DUAL_TREE_MODE) - { - distancePtr = new arma::mat; // Query indices need to be mapped. - neighborPtr = new arma::Mat; - } - else if (!oldFromNewReferences.empty()) - neighborPtr = new arma::Mat; // Reference indices need mapping. - } - - // Set the size of the neighbor and distance matrices. - neighborPtr->set_size(k, querySet.n_cols); - distancePtr->set_size(k, querySet.n_cols); - - typedef NeighborSearchRules RuleType; - - switch (searchMode) - { - case NAIVE_MODE: - { - // Create the helper object for the tree traversal. - RuleType rules(*referenceSet, querySet, k, metric, epsilon); - - // The naive brute-force traversal. - for (size_t i = 0; i < querySet.n_cols; ++i) - for (size_t j = 0; j < referenceSet->n_cols; ++j) - rules.BaseCase(i, j); - - baseCases += querySet.n_cols * referenceSet->n_cols; - - rules.GetResults(*neighborPtr, *distancePtr); - break; - } - case SINGLE_TREE_MODE: - { - // Create the helper object for the tree traversal. - RuleType rules(*referenceSet, querySet, k, metric, epsilon); - - // Create the traverser. - SingleTreeTraversalType traverser(rules); - - // Now have it traverse for each point. - for (size_t i = 0; i < querySet.n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - scores += rules.Scores(); - baseCases += rules.BaseCases(); - - Log::Info << rules.Scores() << " node combinations were scored." - << std::endl; - Log::Info << rules.BaseCases() << " base cases were calculated." - << std::endl; - - rules.GetResults(*neighborPtr, *distancePtr); - break; - } - case DUAL_TREE_MODE: - { - // Build the query tree. - Timer::Stop("computing_neighbors"); - Timer::Start("tree_building"); - Tree* queryTree = BuildTree(querySet, oldFromNewQueries); - Timer::Stop("tree_building"); - Timer::Start("computing_neighbors"); - - // Create the helper object for the tree traversal. - RuleType rules(*referenceSet, queryTree->Dataset(), k, metric, epsilon); - - // Create the traverser. - DualTreeTraversalType traverser(rules); - - traverser.Traverse(*queryTree, *referenceTree); - - scores += rules.Scores(); - baseCases += rules.BaseCases(); - - Log::Info << rules.Scores() << " node combinations were scored." - << std::endl; - Log::Info << rules.BaseCases() << " base cases were calculated." - << std::endl; - - rules.GetResults(*neighborPtr, *distancePtr); - - delete queryTree; - break; - } - case GREEDY_SINGLE_TREE_MODE: - { - // Create the helper object for the tree traversal. - RuleType rules(*referenceSet, querySet, k, metric); - - // Create the traverser. - tree::GreedySingleTreeTraverser traverser(rules); - - // Set the value of minBaseCases. - traverser.MinBaseCases() = k; - - // Now have it traverse for each point. - for (size_t i = 0; i < querySet.n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - scores += rules.Scores(); - baseCases += rules.BaseCases(); - - Log::Info << rules.Scores() << " node combinations were scored." - << std::endl; - Log::Info << rules.BaseCases() << " base cases were calculated." - << std::endl; - - rules.GetResults(*neighborPtr, *distancePtr); - break; - } - } - - Timer::Stop("computing_neighbors"); - - // Map points back to original indices, if necessary. - if (tree::TreeTraits::RearrangesDataset) - { - if (searchMode == DUAL_TREE_MODE && !oldFromNewReferences.empty()) - { - // We must map both query and reference indices. - neighbors.set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - for (size_t i = 0; i < distances.n_cols; i++) - { - // Map distances (copy a column). - distances.col(oldFromNewQueries[i]) = distancePtr->col(i); - - // Map indices of neighbors. - for (size_t j = 0; j < distances.n_rows; j++) - { - neighbors(j, oldFromNewQueries[i]) = - oldFromNewReferences[(*neighborPtr)(j, i)]; - } - } - - // Finished with temporary matrices. - delete neighborPtr; - delete distancePtr; - } - else if (searchMode == DUAL_TREE_MODE) - { - // We must map query indices only. - neighbors.set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - for (size_t i = 0; i < distances.n_cols; ++i) - { - // Map distances (copy a column). - const size_t queryMapping = oldFromNewQueries[i]; - distances.col(queryMapping) = distancePtr->col(i); - neighbors.col(queryMapping) = neighborPtr->col(i); - } - - // Finished with temporary matrices. - delete neighborPtr; - delete distancePtr; - } - else if (!oldFromNewReferences.empty()) - { - // We must map reference indices only. - neighbors.set_size(k, querySet.n_cols); - - // Map indices of neighbors. - for (size_t i = 0; i < neighbors.n_cols; i++) - for (size_t j = 0; j < neighbors.n_rows; j++) - neighbors(j, i) = oldFromNewReferences[(*neighborPtr)(j, i)]; - - // Finished with temporary matrix. - delete neighborPtr; - } - } -} // Search() - -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -void NeighborSearch::Search( - Tree& queryTree, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances, - bool sameSet) -{ - if (k > referenceSet->n_cols) - { - std::stringstream ss; - ss << "Requested value of k (" << k << ") is greater than the number of " - << "points in the reference set (" << referenceSet->n_cols << ")"; - throw std::invalid_argument(ss.str()); - } - - // Make sure we are in dual-tree mode. - if (searchMode != DUAL_TREE_MODE) - throw std::invalid_argument("cannot call NeighborSearch::Search() with a " - "query tree when naive or singleMode are set to true"); - - Timer::Start("computing_neighbors"); - - baseCases = 0; - scores = 0; - - // Get a reference to the query set. - const MatType& querySet = queryTree.Dataset(); - - // We won't need to map query indices, but will we need to map distances? - arma::Mat* neighborPtr = &neighbors; - - if (!oldFromNewReferences.empty() && - tree::TreeTraits::RearrangesDataset) - neighborPtr = new arma::Mat; - - neighborPtr->set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - // Create the helper object for the traversal. - typedef NeighborSearchRules RuleType; - RuleType rules(*referenceSet, querySet, k, metric, epsilon, sameSet); - - // Create the traverser. - DualTreeTraversalType traverser(rules); - traverser.Traverse(queryTree, *referenceTree); - - scores += rules.Scores(); - baseCases += rules.BaseCases(); - - Log::Info << rules.Scores() << " node combinations were scored." << std::endl; - Log::Info << rules.BaseCases() << " base cases were calculated." << std::endl; - - rules.GetResults(*neighborPtr, distances); - - Log::Info << rules.Scores() << " node combinations were scored.\n"; - Log::Info << rules.BaseCases() << " base cases were calculated.\n"; - - Timer::Stop("computing_neighbors"); - - // Do we need to map indices? - if (!oldFromNewReferences.empty() && - tree::TreeTraits::RearrangesDataset) - { - // We must map reference indices only. - neighbors.set_size(k, querySet.n_cols); - - // Map indices of neighbors. - for (size_t i = 0; i < neighbors.n_cols; i++) - for (size_t j = 0; j < neighbors.n_rows; j++) - neighbors(j, i) = oldFromNewReferences[(*neighborPtr)(j, i)]; - - // Finished with temporary matrix. - delete neighborPtr; - } -} - -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -void NeighborSearch::Search( - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - if (k > referenceSet->n_cols) - { - std::stringstream ss; - ss << "Requested value of k (" << k << ") is greater than the number of " - << "points in the reference set (" << referenceSet->n_cols << ")"; - throw std::invalid_argument(ss.str()); - } - if (k == referenceSet->n_cols) - { - std::stringstream ss; - ss << "Requested value of k (" << k << ") is equal to the number of " - << "points in the reference set (" << referenceSet->n_cols << ") and " - << "no query set has been provided."; - throw std::invalid_argument(ss.str()); - } - - Timer::Start("computing_neighbors"); - - baseCases = 0; - scores = 0; - - arma::Mat* neighborPtr = &neighbors; - arma::mat* distancePtr = &distances; - - if (!oldFromNewReferences.empty() && - tree::TreeTraits::RearrangesDataset) - { - // We will always need to rearrange in this case. - distancePtr = new arma::mat; - neighborPtr = new arma::Mat; - } - - // Initialize results. - neighborPtr->set_size(k, referenceSet->n_cols); - distancePtr->set_size(k, referenceSet->n_cols); - - // Create the helper object for the traversal. - typedef NeighborSearchRules RuleType; - RuleType rules(*referenceSet, *referenceSet, k, metric, epsilon, - true /* don't return the same point as nearest neighbor */); - - switch (searchMode) - { - case NAIVE_MODE: - { - // The naive brute-force solution. - for (size_t i = 0; i < referenceSet->n_cols; ++i) - for (size_t j = 0; j < referenceSet->n_cols; ++j) - rules.BaseCase(i, j); - - baseCases += referenceSet->n_cols * referenceSet->n_cols; - break; - } - case SINGLE_TREE_MODE: - { - // Create the traverser. - SingleTreeTraversalType traverser(rules); - - // Now have it traverse for each point. - for (size_t i = 0; i < referenceSet->n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - scores += rules.Scores(); - baseCases += rules.BaseCases(); - - Log::Info << rules.Scores() << " node combinations were scored." - << std::endl; - Log::Info << rules.BaseCases() << " base cases were calculated." - << std::endl; - break; - } - case DUAL_TREE_MODE: - { - // The dual-tree monochromatic search case may require resetting the - // bounds in the tree. - if (treeNeedsReset) - { - std::stack nodes; - nodes.push(referenceTree); - while (!nodes.empty()) - { - Tree* node = nodes.top(); - nodes.pop(); - - // Reset bounds of this node. - node->Stat().Reset(); - - // Then add the children. - for (size_t i = 0; i < node->NumChildren(); ++i) - nodes.push(&node->Child(i)); - } - } - - // Create the traverser. - DualTreeTraversalType traverser(rules); - - if (tree::IsSpillTree::value) - { - // For Dual Tree Search on SpillTree, the queryTree must be built with - // non overlapping (tau = 0). - Tree queryTree(*referenceSet); - traverser.Traverse(queryTree, *referenceTree); - } - else - { - traverser.Traverse(*referenceTree, *referenceTree); - // Next time we perform this search, we'll need to reset the tree. - treeNeedsReset = true; - } - - scores += rules.Scores(); - baseCases += rules.BaseCases(); - - Log::Info << rules.Scores() << " node combinations were scored." - << std::endl; - Log::Info << rules.BaseCases() << " base cases were calculated." - << std::endl; - - // Next time we perform this search, we'll need to reset the tree. - treeNeedsReset = true; - break; - } - case GREEDY_SINGLE_TREE_MODE: - { - // Create the traverser. - tree::GreedySingleTreeTraverser traverser(rules); - - // Set the value of minBaseCases. - traverser.MinBaseCases() = k; - - // Now have it traverse for each point. - for (size_t i = 0; i < referenceSet->n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - scores += rules.Scores(); - baseCases += rules.BaseCases(); - - Log::Info << rules.Scores() << " node combinations were scored." - << std::endl; - Log::Info << rules.BaseCases() << " base cases were calculated." - << std::endl; - break; - } - } - - rules.GetResults(*neighborPtr, *distancePtr); - - Timer::Stop("computing_neighbors"); - - // Do we need to map the reference indices? - if (!oldFromNewReferences.empty() && - tree::TreeTraits::RearrangesDataset) - { - neighbors.set_size(k, referenceSet->n_cols); - distances.set_size(k, referenceSet->n_cols); - - for (size_t i = 0; i < distances.n_cols; ++i) - { - // Map distances (copy a column). - const size_t refMapping = oldFromNewReferences[i]; - distances.col(refMapping) = distancePtr->col(i); - - // Map each neighbor's index. - for (size_t j = 0; j < distances.n_rows; ++j) - neighbors(j, refMapping) = oldFromNewReferences[(*neighborPtr)(j, i)]; - } - - // Finished with temporary matrices. - delete neighborPtr; - delete distancePtr; - } -} - -//! Calculate the average relative error. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -double NeighborSearch::EffectiveError( - arma::mat& foundDistances, - arma::mat& realDistances) -{ - if (foundDistances.n_rows != realDistances.n_rows || - foundDistances.n_cols != realDistances.n_cols) - throw std::invalid_argument("matrices provided must have equal size"); - - double effectiveError = 0; - size_t numCases = 0; - - for (size_t i = 0; i < foundDistances.n_elem; i++) - { - if (realDistances(i) != 0 && - foundDistances(i) != SortPolicy::WorstDistance()) - { - effectiveError += fabs(foundDistances(i) - realDistances(i)) / - realDistances(i); - numCases++; - } - } - - if (numCases) - effectiveError /= numCases; - - return effectiveError; -} - -//! Calculate the recall. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -double NeighborSearch::Recall( - arma::Mat& foundNeighbors, - arma::Mat& realNeighbors) -{ - if (foundNeighbors.n_rows != realNeighbors.n_rows || - foundNeighbors.n_cols != realNeighbors.n_cols) - throw std::invalid_argument("matrices provided must have equal size"); - - size_t found = 0; - for (size_t col = 0; col < foundNeighbors.n_cols; ++col) - for (size_t row = 0; row < foundNeighbors.n_rows; ++row) - for (size_t nei = 0; nei < realNeighbors.n_rows; ++nei) - if (foundNeighbors(row, col) == realNeighbors(nei, col)) - { - found++; - break; - } - - return ((double) found) / realNeighbors.n_elem; -} - -//! Serialize the NeighborSearch model. -template class TreeType, - template class DualTreeTraversalType, - template class SingleTreeTraversalType> -template -void NeighborSearch::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // Serialize preferences for search. - ar & BOOST_SERIALIZATION_NVP(searchMode); - ar & BOOST_SERIALIZATION_NVP(treeNeedsReset); - - // If we are doing naive search, we serialize the dataset. Otherwise we - // serialize the tree. - if (searchMode == NAIVE_MODE) - { - // Delete the current reference set, if necessary and if we are loading. - if (Archive::is_loading::value && referenceSet) - { - delete referenceSet; - referenceSet = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(referenceSet); - ar & BOOST_SERIALIZATION_NVP(metric); - - // If we are loading, set the tree to NULL and clean up memory if necessary. - if (Archive::is_loading::value) - { - if (referenceTree) - delete referenceTree; - - referenceTree = NULL; - oldFromNewReferences.clear(); - } - } - else - { - // Delete the current reference tree, if necessary and if we are loading. - if (Archive::is_loading::value && referenceTree) - { - delete referenceTree; - referenceTree = NULL; - } - - ar & BOOST_SERIALIZATION_NVP(referenceTree); - ar & BOOST_SERIALIZATION_NVP(oldFromNewReferences); - - // If we are loading, set the dataset accordingly and clean up memory if - // necessary. - if (Archive::is_loading::value) - { - referenceSet = &referenceTree->Dataset(); - metric = referenceTree->Metric(); // Get the metric from the tree. - } - } - - // Reset base cases and scores. - if (Archive::is_loading::value) - { - baseCases = 0; - scores = 0; - } -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_rules.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_rules.hpp deleted file mode 100644 index 1109b2507..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_rules.hpp +++ /dev/null @@ -1,236 +0,0 @@ -/** - * @file neighbor_search_rules.hpp - * @author Ryan Curtin - * - * Defines the pruning rules and base case rules necessary to perform a - * tree-based search (with an arbitrary tree) for the NeighborSearch class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_RULES_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_RULES_HPP - -#include - -#include - -namespace mlpack { -namespace neighbor { - -/** - * The NeighborSearchRules class is a template helper class used by - * NeighborSearch class when performing distance-based neighbor searches. For - * each point in the query dataset, it keeps track of the k neighbors in the - * reference dataset which have the 'best' distance according to a given sorting - * policy. - * - * @tparam SortPolicy The sort policy for distances. - * @tparam MetricType The metric to use for computation. - * @tparam TreeType The tree type to use; must adhere to the TreeType API. - */ -template -class NeighborSearchRules -{ - public: - /** - * Construct the NeighborSearchRules object. This is usually done from within - * the NeighborSearch class at search time. - * - * @param referenceSet Set of reference data. - * @param querySet Set of query data. - * @param k Number of neighbors to search for. - * @param metric Instantiated metric. - * @param epsilon Relative approximate error. - * @param sameSet If true, the query and reference set are taken to be the - * same, and a query point will not return itself in the results. - */ - NeighborSearchRules(const typename TreeType::Mat& referenceSet, - const typename TreeType::Mat& querySet, - const size_t k, - MetricType& metric, - const double epsilon = 0, - const bool sameSet = false); - - /** - * Store the list of candidates for each query point in the given matrices. - * - * @param neighbors Matrix storing lists of neighbors for each query point. - * @param distances Matrix storing distances of neighbors for each query - * point. - */ - void GetResults(arma::Mat& neighbors, arma::mat& distances); - - /** - * Get the distance from the query point to the reference point. - * This will update the list of candidates with the new point if appropriate - * and will track the number of base cases (number of points evaluated). - * - * @param queryIndex Index of query point. - * @param referenceIndex Index of reference point. - */ - double BaseCase(const size_t queryIndex, const size_t referenceIndex); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - */ - double Score(const size_t queryIndex, TreeType& referenceNode); - - /** - * Get the child node with the best score. - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - */ - size_t GetBestChild(const size_t queryIndex, TreeType& referenceNode); - - /** - * Get the child node with the best score. - * - * @param queryNode Node to be considered. - * @param referenceNode Candidate node to be recursed into. - */ - size_t GetBestChild(const TreeType& queryNode, TreeType& referenceNode); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). This is used when the score has already - * been calculated, but another recursion may have modified the bounds for - * pruning. So the old score is checked against the new pruning bound. - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - * @param oldScore Old score produced by Score() (or Rescore()). - */ - double Rescore(const size_t queryIndex, - TreeType& referenceNode, - const double oldScore) const; - - /** - * Get the score for recursion order. A low score indicates priority for - * recursionm while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - */ - double Score(TreeType& queryNode, TreeType& referenceNode); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). This is used when the score has already - * been calculated, but another recursion may have modified the bounds for - * pruning. So the old score is checked against the new pruning bound. - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - * @param oldScore Old score produced by Socre() (or Rescore()). - */ - double Rescore(TreeType& queryNode, - TreeType& referenceNode, - const double oldScore) const; - - //! Get the number of base cases that have been performed. - size_t BaseCases() const { return baseCases; } - //! Modify the number of base cases that have been performed. - size_t& BaseCases() { return baseCases; } - - //! Get the number of scores that have been performed. - size_t Scores() const { return scores; } - //! Modify the number of scores that have been performed. - size_t& Scores() { return scores; } - - //! Convenience typedef. - typedef typename tree::TraversalInfo TraversalInfoType; - - //! Get the traversal info. - const TraversalInfoType& TraversalInfo() const { return traversalInfo; } - //! Modify the traversal info. - TraversalInfoType& TraversalInfo() { return traversalInfo; } - - protected: - //! The reference set. - const typename TreeType::Mat& referenceSet; - - //! The query set. - const typename TreeType::Mat& querySet; - - //! Candidate represents a possible candidate neighbor (distance, index). - typedef std::pair Candidate; - - //! Compare two candidates based on the distance. - struct CandidateCmp { - bool operator()(const Candidate& c1, const Candidate& c2) - { - return !SortPolicy::IsBetter(c2.first, c1.first); - }; - }; - - //! Use a priority queue to represent the list of candidate neighbors. - typedef std::priority_queue, CandidateCmp> - CandidateList; - - //! Set of candidate neighbors for each point. - std::vector candidates; - - //! Number of neighbors to search for. - const size_t k; - - //! The instantiated metric. - MetricType& metric; - - //! Denotes whether or not the reference and query sets are the same. - bool sameSet; - - //! Relative error to be considered in approximate search. - const double epsilon; - - //! The last query point BaseCase() was called with. - size_t lastQueryIndex; - //! The last reference point BaseCase() was called with. - size_t lastReferenceIndex; - //! The last base case result. - double lastBaseCase; - - //! The number of base cases that have been performed. - size_t baseCases; - //! The number of scores that have been performed. - size_t scores; - - //! Traversal info for the parent combination; this is updated by the - //! traversal before each call to Score(). - TraversalInfoType traversalInfo; - - /** - * Recalculate the bound for a given query node. - */ - double CalculateBound(TreeType& queryNode) const; - - /** - * Helper function to insert a point into the list of candidate points. - * - * @param queryIndex Index of point whose neighbors we are inserting into. - * @param neighbor Index of reference point which is being inserted. - * @param distance Distance from query point to reference point. - */ - void InsertNeighbor(const size_t queryIndex, - const size_t neighbor, - const double distance); -}; - -} // namespace neighbor -} // namespace mlpack - -// Include implementation. -#include "neighbor_search_rules_impl.hpp" - -#endif // MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_RULES_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_rules_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_rules_impl.hpp deleted file mode 100644 index 835bd5073..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_rules_impl.hpp +++ /dev/null @@ -1,515 +0,0 @@ -/** - * @file neighbor_search_rules_impl.hpp - * @author Ryan Curtin - * - * Implementation of NeighborSearchRules. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP - -// In case it hasn't been included yet. -#include "neighbor_search_rules.hpp" -#include - -namespace mlpack { -namespace neighbor { - -template -NeighborSearchRules::NeighborSearchRules( - const typename TreeType::Mat& referenceSet, - const typename TreeType::Mat& querySet, - const size_t k, - MetricType& metric, - const double epsilon, - const bool sameSet) : - referenceSet(referenceSet), - querySet(querySet), - k(k), - metric(metric), - sameSet(sameSet), - epsilon(epsilon), - lastQueryIndex(querySet.n_cols), - lastReferenceIndex(referenceSet.n_cols), - baseCases(0), - scores(0) -{ - // We must set the traversal info last query and reference node pointers to - // something that is both invalid (i.e. not a tree node) and not NULL. We'll - // use the this pointer. - traversalInfo.LastQueryNode() = (TreeType*) this; - traversalInfo.LastReferenceNode() = (TreeType*) this; - - // Let's build the list of candidate neighbors for each query point. - // It will be initialized with k candidates: (WorstDistance, size_t() - 1) - // The list of candidates will be updated when visiting new points with the - // BaseCase() method. - const Candidate def = std::make_pair(SortPolicy::WorstDistance(), - size_t() - 1); - - std::vector vect(k, def); - CandidateList pqueue(CandidateCmp(), std::move(vect)); - - candidates.reserve(querySet.n_cols); - for (size_t i = 0; i < querySet.n_cols; i++) - candidates.push_back(pqueue); -} - -template -void NeighborSearchRules::GetResults( - arma::Mat& neighbors, - arma::mat& distances) -{ - neighbors.set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - for (size_t i = 0; i < querySet.n_cols; i++) - { - CandidateList& pqueue = candidates[i]; - for (size_t j = 1; j <= k; j++) - { - neighbors(k - j, i) = pqueue.top().second; - distances(k - j, i) = pqueue.top().first; - pqueue.pop(); - } - } -}; - -template -inline force_inline // Absolutely MUST be inline so optimizations can happen. -double NeighborSearchRules:: -BaseCase(const size_t queryIndex, const size_t referenceIndex) -{ - // If the datasets are the same, then this search is only using one dataset - // and we should not return identical points. - if (sameSet && (queryIndex == referenceIndex)) - return 0.0; - - // If we have already performed this base case, then do not perform it again. - if ((lastQueryIndex == queryIndex) && (lastReferenceIndex == referenceIndex)) - return lastBaseCase; - - double distance = metric.Evaluate(querySet.col(queryIndex), - referenceSet.col(referenceIndex)); - ++baseCases; - - InsertNeighbor(queryIndex, referenceIndex, distance); - - // Cache this information for the next time BaseCase() is called. - lastQueryIndex = queryIndex; - lastReferenceIndex = referenceIndex; - lastBaseCase = distance; - - return distance; -} - -template -inline double NeighborSearchRules::Score( - const size_t queryIndex, - TreeType& referenceNode) -{ - ++scores; // Count number of Score() calls. - double distance; - if (tree::TreeTraits::FirstPointIsCentroid) - { - // The first point in the tree is the centroid. So we can then calculate - // the base case between that and the query point. - double baseCase = -1.0; - if (tree::TreeTraits::HasSelfChildren) - { - // If the parent node is the same, then we have already calculated the - // base case. - if ((referenceNode.Parent() != NULL) && - (referenceNode.Point(0) == referenceNode.Parent()->Point(0))) - baseCase = referenceNode.Parent()->Stat().LastDistance(); - else - baseCase = BaseCase(queryIndex, referenceNode.Point(0)); - - // Save this evaluation. - referenceNode.Stat().LastDistance() = baseCase; - } - - distance = SortPolicy::CombineBest(baseCase, - referenceNode.FurthestDescendantDistance()); - } - else - { - distance = SortPolicy::BestPointToNodeDistance(querySet.col(queryIndex), - &referenceNode); - } - - // Compare against the best k'th distance for this query point so far. - double bestDistance = candidates[queryIndex].top().first; - bestDistance = SortPolicy::Relax(bestDistance, epsilon); - - return (SortPolicy::IsBetter(distance, bestDistance)) ? - SortPolicy::ConvertToScore(distance) : DBL_MAX; -} - -template -inline size_t NeighborSearchRules:: -GetBestChild(const size_t queryIndex, TreeType& referenceNode) -{ - ++scores; - return SortPolicy::GetBestChild(querySet.col(queryIndex), referenceNode); -} - -template -inline size_t NeighborSearchRules:: -GetBestChild(const TreeType& queryNode, TreeType& referenceNode) -{ - ++scores; - return SortPolicy::GetBestChild(queryNode, referenceNode); -} - -template -inline double NeighborSearchRules::Rescore( - const size_t queryIndex, - TreeType& /* referenceNode */, - const double oldScore) const -{ - // If we are already pruning, still prune. - if (oldScore == DBL_MAX) - return oldScore; - - const double distance = SortPolicy::ConvertToDistance(oldScore); - - // Just check the score again against the distances. - double bestDistance = candidates[queryIndex].top().first; - bestDistance = SortPolicy::Relax(bestDistance, epsilon); - - return (SortPolicy::IsBetter(distance, bestDistance)) ? oldScore : DBL_MAX; -} - -template -inline double NeighborSearchRules::Score( - TreeType& queryNode, - TreeType& referenceNode) -{ - ++scores; // Count number of Score() calls. - - // Update our bound. - const double bestDistance = CalculateBound(queryNode); - - // Use the traversal info to see if a parent-child or parent-parent prune is - // possible. This is a looser bound than we could make, but it might be - // sufficient. - const double queryParentDist = queryNode.ParentDistance(); - const double queryDescDist = queryNode.FurthestDescendantDistance(); - const double refParentDist = referenceNode.ParentDistance(); - const double refDescDist = referenceNode.FurthestDescendantDistance(); - const double score = traversalInfo.LastScore(); - double adjustedScore; - - // We want to set adjustedScore to be the distance between the centroid of the - // last query node and last reference node. We will do this by adjusting the - // last score. In some cases, we can just use the last base case. - if (tree::TreeTraits::FirstPointIsCentroid) - { - adjustedScore = traversalInfo.LastBaseCase(); - } - else if (score == 0.0) // Nothing we can do here. - { - adjustedScore = 0.0; - } - else - { - // The last score is equal to the distance between the centroids minus the - // radii of the query and reference bounds along the axis of the line - // between the two centroids. In the best case, these radii are the - // furthest descendant distances, but that is not always true. It would - // take too long to calculate the exact radii, so we are forced to use - // MinimumBoundDistance() as a lower-bound approximation. - const double lastQueryDescDist = - traversalInfo.LastQueryNode()->MinimumBoundDistance(); - const double lastRefDescDist = - traversalInfo.LastReferenceNode()->MinimumBoundDistance(); - adjustedScore = SortPolicy::CombineWorst(score, lastQueryDescDist); - adjustedScore = SortPolicy::CombineWorst(adjustedScore, lastRefDescDist); - } - - // Assemble an adjusted score. For nearest neighbor search, this adjusted - // score is a lower bound on MinDistance(queryNode, referenceNode) that is - // assembled without actually calculating MinDistance(). For furthest - // neighbor search, it is an upper bound on - // MaxDistance(queryNode, referenceNode). If the traversalInfo isn't usable - // then the node should not be pruned by this. - if (traversalInfo.LastQueryNode() == queryNode.Parent()) - { - const double queryAdjust = queryParentDist + queryDescDist; - adjustedScore = SortPolicy::CombineBest(adjustedScore, queryAdjust); - } - else if (traversalInfo.LastQueryNode() == &queryNode) - { - adjustedScore = SortPolicy::CombineBest(adjustedScore, queryDescDist); - } - else - { - // The last query node wasn't this query node or its parent. So we force - // the adjustedScore to be such that this combination can't be pruned here, - // because we don't really know anything about it. - - // It would be possible to modify this section to try and make a prune based - // on the query descendant distance and the distance between the query node - // and last traversal query node, but this case doesn't actually happen for - // kd-trees or cover trees. - adjustedScore = SortPolicy::BestDistance(); - } - - if (traversalInfo.LastReferenceNode() == referenceNode.Parent()) - { - const double refAdjust = refParentDist + refDescDist; - adjustedScore = SortPolicy::CombineBest(adjustedScore, refAdjust); - } - else if (traversalInfo.LastReferenceNode() == &referenceNode) - { - adjustedScore = SortPolicy::CombineBest(adjustedScore, refDescDist); - } - else - { - // The last reference node wasn't this reference node or its parent. So we - // force the adjustedScore to be such that this combination can't be pruned - // here, because we don't really know anything about it. - - // It would be possible to modify this section to try and make a prune based - // on the reference descendant distance and the distance between the - // reference node and last traversal reference node, but this case doesn't - // actually happen for kd-trees or cover trees. - adjustedScore = SortPolicy::BestDistance(); - } - - // Can we prune? - if (!SortPolicy::IsBetter(adjustedScore, bestDistance)) - { - if (!(tree::TreeTraits::FirstPointIsCentroid && score == 0.0)) - { - // There isn't any need to set the traversal information because no - // descendant combinations will be visited, and those are the only - // combinations that would depend on the traversal information. - return DBL_MAX; - } - } - - double distance; - if (tree::TreeTraits::FirstPointIsCentroid) - { - // The first point in the node is the centroid, so we can calculate the - // distance between the two points using BaseCase() and then find the - // bounds. This is potentially loose for non-ball bounds. - double baseCase = -1.0; - if (tree::TreeTraits::HasSelfChildren && - (traversalInfo.LastQueryNode()->Point(0) == queryNode.Point(0)) && - (traversalInfo.LastReferenceNode()->Point(0) == referenceNode.Point(0))) - { - // We already calculated it. - baseCase = traversalInfo.LastBaseCase(); - } - else - { - baseCase = BaseCase(queryNode.Point(0), referenceNode.Point(0)); - } - - distance = SortPolicy::CombineBest(baseCase, - queryNode.FurthestDescendantDistance() + - referenceNode.FurthestDescendantDistance()); - - lastQueryIndex = queryNode.Point(0); - lastReferenceIndex = referenceNode.Point(0); - lastBaseCase = baseCase; - - traversalInfo.LastBaseCase() = baseCase; - } - else - { - distance = SortPolicy::BestNodeToNodeDistance(&queryNode, &referenceNode); - } - - if (SortPolicy::IsBetter(distance, bestDistance)) - { - // Set traversal information. - traversalInfo.LastQueryNode() = &queryNode; - traversalInfo.LastReferenceNode() = &referenceNode; - traversalInfo.LastScore() = distance; - - return SortPolicy::ConvertToScore(distance); - } - else - { - // There isn't any need to set the traversal information because no - // descendant combinations will be visited, and those are the only - // combinations that would depend on the traversal information. - return DBL_MAX; - } -} - -template -inline double NeighborSearchRules::Rescore( - TreeType& queryNode, - TreeType& /* referenceNode */, - const double oldScore) const -{ - if (oldScore == DBL_MAX || oldScore == 0.0) - return oldScore; - - const double distance = SortPolicy::ConvertToDistance(oldScore); - - // Update our bound. - const double bestDistance = CalculateBound(queryNode); - - return (SortPolicy::IsBetter(distance, bestDistance)) ? oldScore : DBL_MAX; -} - -// Calculate the bound for a given query node in its current state and update -// it. -template -inline double NeighborSearchRules:: - CalculateBound(TreeType& queryNode) const -{ - // This is an adapted form of the B(N_q) function in the paper - // ``Tree-Independent Dual-Tree Algorithms'' by Curtin et. al.; the goal is to - // place a bound on the worst possible distance a point combination could have - // to improve any of the current neighbor estimates. If the best possible - // distance between two nodes is greater than this bound, then the node - // combination can be pruned (see Score()). - - // There are a couple ways we can assemble a bound. For simplicity, this is - // described for nearest neighbor search (SortPolicy = NearestNeighborSort), - // but the code that is written is adapted for whichever SortPolicy. - - // First, we can consider the current worst neighbor candidate distance of any - // descendant point. This is assembled with 'worstDistance' by looping - // through the points held by the query node, and then by taking the cached - // worst distance from any child nodes (Stat().FirstBound()). This - // corresponds roughly to B_1(N_q) in the paper. - - // The other way of bounding is to use the triangle inequality. To do this, - // we find the current best kth-neighbor candidate distance of any descendant - // query point, and use the triangle inequality to place a bound on the - // distance that candidate would have to any other descendant query point. - // This corresponds roughly to B_2(N_q) in the paper, and is the bounding - // style for cover trees. - - // Then, to assemble the final bound, since both bounds are valid, we simply - // take the better of the two. - - double worstDistance = SortPolicy::BestDistance(); - double bestDistance = SortPolicy::WorstDistance(); - double bestPointDistance = SortPolicy::WorstDistance(); - double auxDistance = SortPolicy::WorstDistance(); - - // Loop over points held in the node. - for (size_t i = 0; i < queryNode.NumPoints(); ++i) - { - const double distance = candidates[queryNode.Point(i)].top().first; - if (SortPolicy::IsBetter(worstDistance, distance)) - worstDistance = distance; - if (SortPolicy::IsBetter(distance, bestPointDistance)) - bestPointDistance = distance; - } - - auxDistance = bestPointDistance; - - // Loop over children of the node, and use their cached information to - // assemble bounds. - for (size_t i = 0; i < queryNode.NumChildren(); ++i) - { - const double firstBound = queryNode.Child(i).Stat().FirstBound(); - const double auxBound = queryNode.Child(i).Stat().AuxBound(); - - if (SortPolicy::IsBetter(worstDistance, firstBound)) - worstDistance = firstBound; - if (SortPolicy::IsBetter(auxBound, auxDistance)) - auxDistance = auxBound; - } - - // Add triangle inequality adjustment to best distance. It is possible this - // could be tighter for some certain types of trees. - bestDistance = SortPolicy::CombineWorst(auxDistance, - 2 * queryNode.FurthestDescendantDistance()); - - // Add triangle inequality adjustment to best distance of points in node. - bestPointDistance = SortPolicy::CombineWorst(bestPointDistance, - queryNode.FurthestPointDistance() + - queryNode.FurthestDescendantDistance()); - - if (SortPolicy::IsBetter(bestPointDistance, bestDistance)) - bestDistance = bestPointDistance; - - // At this point: - // worstDistance holds the value of B_1(N_q). - // bestDistance holds the value of B_2(N_q). - // auxDistance holds the value of B_aux(N_q). - - // Now consider the parent bounds. - if (queryNode.Parent() != NULL) - { - // The parent's worst distance bound implies that the bound for this node - // must be at least as good. Thus, if the parent worst distance bound is - // better, then take it. - if (SortPolicy::IsBetter(queryNode.Parent()->Stat().FirstBound(), - worstDistance)) - worstDistance = queryNode.Parent()->Stat().FirstBound(); - - // The parent's best distance bound implies that the bound for this node - // must be at least as good. Thus, if the parent best distance bound is - // better, then take it. - if (SortPolicy::IsBetter(queryNode.Parent()->Stat().SecondBound(), - bestDistance)) - bestDistance = queryNode.Parent()->Stat().SecondBound(); - } - - // Could the existing bounds be better? - if (SortPolicy::IsBetter(queryNode.Stat().FirstBound(), worstDistance)) - worstDistance = queryNode.Stat().FirstBound(); - if (SortPolicy::IsBetter(queryNode.Stat().SecondBound(), bestDistance)) - bestDistance = queryNode.Stat().SecondBound(); - - // Cache bounds for later. - queryNode.Stat().FirstBound() = worstDistance; - queryNode.Stat().SecondBound() = bestDistance; - queryNode.Stat().AuxBound() = auxDistance; - - worstDistance = SortPolicy::Relax(worstDistance, epsilon); - - // We can't consider B_2 for Spill Trees. - if (tree::IsSpillTree::value) - return worstDistance; - - if (SortPolicy::IsBetter(worstDistance, bestDistance)) - return worstDistance; - else - return bestDistance; -} - -/** - * Helper function to insert a point into the list of candidate points. - * - * @param queryIndex Index of point whose neighbors we are inserting into. - * @param neighbor Index of reference point which is being inserted. - * @param distance Distance from query point to reference point. - */ -template -inline void NeighborSearchRules:: -InsertNeighbor( - const size_t queryIndex, - const size_t neighbor, - const double distance) -{ - CandidateList& pqueue = candidates[queryIndex]; - Candidate c = std::make_pair(distance, neighbor); - - if (CandidateCmp()(c, pqueue.top())) - { - pqueue.pop(); - pqueue.push(c); - } -} - -} // namespace neighbor -} // namespace mlpack - -#endif // MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_RULES_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_stat.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_stat.hpp deleted file mode 100644 index dd48eef6e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/neighbor_search_stat.hpp +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file neighbor_search.hpp - * @author Ryan Curtin - * - * Defines the NeighborSearch class, which performs an abstract - * nearest-neighbor-like query on two datasets. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_STAT_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_NEIGHBOR_SEARCH_STAT_HPP - -#include - -namespace mlpack { -namespace neighbor { - -/** - * Extra data for each node in the tree. For neighbor searches, each node only - * needs to store a bound on neighbor distances. - */ -template -class NeighborSearchStat -{ - private: - //! The first bound on the node's neighbor distances (B_1). This represents - //! the worst candidate distance of any descendants of this node. - double firstBound; - //! The second bound on the node's neighbor distances (B_2). This represents - //! a bound on the worst distance of any descendants of this node assembled - //! using the best descendant candidate distance modified by the furthest - //! descendant distance. - double secondBound; - //! The aux bound on the node's neighbor distances (B_aux). This represents - //! the best descendant candidate distance (used to calculate secondBound). - double auxBound; - //! The last distance evaluation. - double lastDistance; - - public: - /** - * Initialize the statistic with the worst possible distance according to - * our sorting policy. - */ - NeighborSearchStat() : - firstBound(SortPolicy::WorstDistance()), - secondBound(SortPolicy::WorstDistance()), - auxBound(SortPolicy::WorstDistance()), - lastDistance(0.0) { } - - /** - * Initialization for a fully initialized node. In this case, we don't need - * to worry about the node. - */ - template - NeighborSearchStat(TreeType& /* node */) : - firstBound(SortPolicy::WorstDistance()), - secondBound(SortPolicy::WorstDistance()), - auxBound(SortPolicy::WorstDistance()), - lastDistance(0.0) { } - - /** - * Reset statistic parameters to initial values. - */ - void Reset() - { - firstBound = SortPolicy::WorstDistance(); - secondBound = SortPolicy::WorstDistance(); - auxBound = SortPolicy::WorstDistance(); - lastDistance = 0.0; - } - - //! Get the first bound. - double FirstBound() const { return firstBound; } - //! Modify the first bound. - double& FirstBound() { return firstBound; } - //! Get the second bound. - double SecondBound() const { return secondBound; } - //! Modify the second bound. - double& SecondBound() { return secondBound; } - //! Get the aux bound. - double AuxBound() const { return auxBound; } - //! Modify the aux bound. - double& AuxBound() { return auxBound; } - //! Get the last distance calculation. - double LastDistance() const { return lastDistance; } - //! Modify the last distance calculation. - double& LastDistance() { return lastDistance; } - - //! Serialize the statistic to/from an archive. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(firstBound); - ar & BOOST_SERIALIZATION_NVP(secondBound); - ar & BOOST_SERIALIZATION_NVP(auxBound); - ar & BOOST_SERIALIZATION_NVP(lastDistance); - } -}; - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/ns_model.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/ns_model.hpp deleted file mode 100644 index b2067a0f1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/ns_model.hpp +++ /dev/null @@ -1,417 +0,0 @@ -/** - * @file ns_model.hpp - * @author Ryan Curtin - * - * This is a model for nearest or furthest neighbor search. It is useful in - * that it provides an easy way to serialize a model, abstracts away the - * different types of trees, and also reflects the NeighborSearch API and - * automatically directs to the right tree type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NS_MODEL_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_NS_MODEL_HPP - -#include -#include -#include -#include -#include -#include -#include "neighbor_search.hpp" - -namespace mlpack { -namespace neighbor { - -/** - * Alias template for euclidean neighbor search. - */ -template class TreeType> -using NSType = NeighborSearch, - arma::mat>::template DualTreeTraverser>; - -/** - * MonoSearchVisitor executes a monochromatic neighbor search on the given - * NSType. We don't make any difference for different instantiations of NSType. - */ -class MonoSearchVisitor : public boost::static_visitor -{ - private: - //! Number of neighbors to search for. - const size_t k; - //! Result matrix for neighbors. - arma::Mat& neighbors; - //! Result matrix for distances. - arma::mat& distances; - - public: - //! Perform monochromatic nearest neighbor search. - template - void operator()(NSType* ns) const; - - //! Construct the MonoSearchVisitor object with the given parameters. - MonoSearchVisitor(const size_t k, - arma::Mat& neighbors, - arma::mat& distances) : - k(k), - neighbors(neighbors), - distances(distances) - {}; -}; - -/** - * BiSearchVisitor executes a bichromatic neighbor search on the given NSType. - * We use template specialization to differentiate those tree types that - * accept leafSize as a parameter. In these cases, before doing neighbor search, - * a query tree with proper leafSize is built from the querySet. - */ -template -class BiSearchVisitor : public boost::static_visitor -{ - private: - //! The query set for the bichromatic search. - const arma::mat& querySet; - //! The number of neighbors to search for. - const size_t k; - //! The result matrix for neighbors. - arma::Mat& neighbors; - //! The result matrix for distances. - arma::mat& distances; - //! The number of points in a leaf (for BinarySpaceTrees). - const size_t leafSize; - //! Overlapping size (for spill trees). - const double tau; - //! Balance threshold (for spill trees). - const double rho; - - //! Bichromatic neighbor search on the given NSType considering the leafSize. - template - void SearchLeaf(NSType* ns) const; - - public: - //! Alias template necessary for visual c++ compiler. - template class TreeType> - using NSTypeT = NSType; - - //! Default Bichromatic neighbor search on the given NSType instance. - template class TreeType> - void operator()(NSTypeT* ns) const; - - //! Bichromatic neighbor search on the given NSType specialized for KDTrees. - void operator()(NSTypeT* ns) const; - - //! Bichromatic neighbor search on the given NSType specialized for BallTrees. - void operator()(NSTypeT* ns) const; - - //! Bichromatic neighbor search specialized for SPTrees. - void operator()(SpillKNN* ns) const; - - //! Bichromatic neighbor search specialized for octrees. - void operator()(NSTypeT* ns) const; - - //! Construct the BiSearchVisitor. - BiSearchVisitor(const arma::mat& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances, - const size_t leafSize, - const double tau, - const double rho); -}; - -/** - * TrainVisitor sets the reference set to a new reference set on the given - * NSType. We use template specialization to differentiate those tree types that - * accept leafSize as a parameter. In these cases, a reference tree with proper - * leafSize is built from the referenceSet. - */ -template -class TrainVisitor : public boost::static_visitor -{ - private: - //! The reference set to use for training. - arma::mat&& referenceSet; - //! The leaf size, used only by BinarySpaceTree. - size_t leafSize; - //! Overlapping size (for spill trees). - const double tau; - //! Balance threshold (for spill trees). - const double rho; - - //! Train on the given NSType considering the leafSize. - template - void TrainLeaf(NSType* ns) const; - - public: - //! Alias template necessary for visual c++ compiler. - template class TreeType> - using NSTypeT = NSType; - - //! Default Train on the given NSType instance. - template class TreeType> - void operator()(NSTypeT* ns) const; - - //! Train on the given NSType specialized for KDTrees. - void operator()(NSTypeT* ns) const; - - //! Train on the given NSType specialized for BallTrees. - void operator()(NSTypeT* ns) const; - - //! Train specialized for SPTrees. - void operator()(SpillKNN* ns) const; - - //! Train specialized for octrees. - void operator()(NSTypeT* ns) const; - - //! Construct the TrainVisitor object with the given reference set, leafSize - //! for BinarySpaceTrees, and tau and rho for spill trees. - TrainVisitor(arma::mat&& referenceSet, - const size_t leafSize, - const double tau, - const double rho); -}; - -/** - * SearchModeVisitor exposes the SearchMode() method of the given NSType. - */ -class SearchModeVisitor : public boost::static_visitor -{ - public: - //! Return the search mode. - template - NeighborSearchMode& operator()(NSType* ns) const; -}; - -/** - * EpsilonVisitor exposes the Epsilon method of the given NSType. - */ -class EpsilonVisitor : public boost::static_visitor -{ - public: - //! Return epsilon, the approximation parameter. - template - double& operator()(NSType *ns) const; -}; - -/** - * ReferenceSetVisitor exposes the referenceSet of the given NSType. - */ -class ReferenceSetVisitor : public boost::static_visitor -{ - public: - //! Return the reference set. - template - const arma::mat& operator()(NSType *ns) const; -}; - -/** - * DeleteVisitor deletes the given NSType instance. - */ -class DeleteVisitor : public boost::static_visitor -{ - public: - //! Delete the NSType object. - template - void operator()(NSType *ns) const; -}; - -/** - * The NSModel class provides an easy way to serialize a model, abstracts away - * the different types of trees, and also reflects the NeighborSearch API. This - * class is meant to be used by the command-line mlpack_knn and mlpack_kfn - * programs, and thus does not have the same complete functionality and - * flexibility as the NeighborSearch class. So if you are using it outside of - * mlpack_knn and mlpack_kfn, be aware that it is limited! - * - * @tparam SortPolicy The sort policy for distances; see NearestNeighborSort. - */ -template -class NSModel -{ - public: - //! Enum type to identify each accepted tree type. - enum TreeTypes - { - KD_TREE, - COVER_TREE, - R_TREE, - R_STAR_TREE, - BALL_TREE, - X_TREE, - HILBERT_R_TREE, - R_PLUS_TREE, - R_PLUS_PLUS_TREE, - VP_TREE, - RP_TREE, - MAX_RP_TREE, - SPILL_TREE, - UB_TREE, - OCTREE - }; - - private: - //! Tree type considered for neighbor search. - TreeTypes treeType; - - //! For tree types that accept the maxLeafSize parameter. - size_t leafSize; - - //! Overlapping size (for spill trees). - double tau; - //! Balance threshold (for spill trees). - double rho; - - //! If true, random projections are used. - bool randomBasis; - //! This is the random projection matrix; only used if randomBasis is true. - arma::mat q; - - /** - * nSearch holds an instance of the NeigborSearch class for the current - * treeType. It is initialized every time BuildModel is executed. - * We access to the contained value through the visitor classes defined above. - */ - boost::variant*, - NSType*, - NSType*, - NSType*, - NSType*, - NSType*, - NSType*, - NSType*, - NSType*, - NSType*, - NSType*, - NSType*, - SpillKNN*, - NSType*, - NSType*> nSearch; - - public: - /** - * Initialize the NSModel with the given type and whether or not a random - * basis should be used. - * - * @param treeType Type of tree to use. - * @param randomBasis Whether or not to project the points onto a random basis - * before searching. - */ - NSModel(TreeTypes treeType = TreeTypes::KD_TREE, bool randomBasis = false); - - /** - * Copy the given NSModel. - * - * @param other Model to copy. - */ - NSModel(const NSModel& other); - - /** - * Take ownership of the given NSModel. - * - * @param other Model to take ownership of. - */ - NSModel(NSModel&& other); - - /** - * Copy the given NSModel. - * - * @param other Model to copy. - */ - NSModel& operator=(const NSModel& other); - - /** - * Take ownership of the given NSModel. - * - * @param other Model to take ownership of. - */ - NSModel& operator=(NSModel&& other); - - //! Clean memory, if necessary. - ~NSModel(); - - //! Serialize the neighbor search model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - //! Expose the dataset. - const arma::mat& Dataset() const; - - //! Expose SearchMode. - NeighborSearchMode SearchMode() const; - NeighborSearchMode& SearchMode(); - - //! Expose Epsilon. - double Epsilon() const; - double& Epsilon(); - - //! Expose leafSize. - size_t LeafSize() const { return leafSize; } - size_t& LeafSize() { return leafSize; } - - //! Expose tau. - double Tau() const { return tau; } - double& Tau() { return tau; } - - //! Expose rho. - double Rho() const { return rho; } - double& Rho() { return rho; } - - //! Expose treeType. - TreeTypes TreeType() const { return treeType; } - TreeTypes& TreeType() { return treeType; } - - //! Expose randomBasis. - bool RandomBasis() const { return randomBasis; } - bool& RandomBasis() { return randomBasis; } - - //! Build the reference tree. - void BuildModel(arma::mat&& referenceSet, - const size_t leafSize, - const NeighborSearchMode searchMode, - const double epsilon = 0); - - //! Perform neighbor search. The query set will be reordered. - void Search(arma::mat&& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - //! Perform monochromatic neighbor search. - void Search(const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - //! Return a string representation of the current tree type. - std::string TreeName() const; -}; - -} // namespace neighbor -} // namespace mlpack - -//! Set the serialization version of the NSModel class. -BOOST_TEMPLATE_CLASS_VERSION(template, - mlpack::neighbor::NSModel, 1); - -// Include implementation. -#include "ns_model_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/ns_model_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/ns_model_impl.hpp deleted file mode 100644 index 17c986e32..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/ns_model_impl.hpp +++ /dev/null @@ -1,641 +0,0 @@ -/** - * @file ns_model_impl.hpp - * @author Ryan Curtin - * - * This is a model for nearest or furthest neighbor search. It is useful in - * that it provides an easy way to serialize a model, abstracts away the - * different types of trees, and also reflects the NeighborSearch API and - * automatically directs to the right tree type. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NS_MODEL_IMPL_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_NS_MODEL_IMPL_HPP - -// In case it hasn't been included yet. -#include "ns_model.hpp" - -#include - -namespace mlpack { -namespace neighbor { - -//! Monochromatic neighbor search on the given NSType instance. -template -void MonoSearchVisitor::operator()(NSType *ns) const -{ - if (ns) - return ns->Search(k, neighbors, distances); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Save parameters for bichromatic neighbor search. -template -BiSearchVisitor::BiSearchVisitor(const arma::mat& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances, - const size_t leafSize, - const double tau, - const double rho) : - querySet(querySet), - k(k), - neighbors(neighbors), - distances(distances), - leafSize(leafSize), - tau(tau), - rho(rho) -{} - -//! Default Bichromatic neighbor search on the given NSType instance. -template -template class TreeType> -void BiSearchVisitor::operator()(NSTypeT* ns) const -{ - if (ns) - return ns->Search(querySet, k, neighbors, distances); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Bichromatic neighbor search on the given NSType specialized for KDTrees. -template -void BiSearchVisitor::operator()(NSTypeT* ns) const -{ - if (ns) - return SearchLeaf(ns); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Bichromatic neighbor search on the given NSType specialized for BallTrees. -template -void BiSearchVisitor::operator()(NSTypeT* ns) const -{ - if (ns) - return SearchLeaf(ns); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Bichromatic neighbor search specialized for SPTrees. -template -void BiSearchVisitor::operator()(SpillKNN* ns) const -{ - if (ns) - { - if (ns->SearchMode() == DUAL_TREE_MODE) - { - // For Dual Tree Search on SpillTrees, the queryTree must be built with - // non overlapping (tau = 0). - typename SpillKNN::Tree queryTree(std::move(querySet), 0 /* tau*/, - leafSize, rho); - ns->Search(queryTree, k, neighbors, distances); - } - else - ns->Search(querySet, k, neighbors, distances); - } - else - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Bichromatic neighbor search specialized for octrees. -template -void BiSearchVisitor::operator()(NSTypeT* ns) const -{ - if (ns) - return SearchLeaf(ns); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Bichromatic neighbor search on the given NSType considering the leafSize. -template -template -void BiSearchVisitor::SearchLeaf(NSType* ns) const -{ - if (ns->SearchMode() == DUAL_TREE_MODE) - { - std::vector oldFromNewQueries; - typename NSType::Tree queryTree(std::move(querySet), oldFromNewQueries, - leafSize); - - arma::Mat neighborsOut; - arma::mat distancesOut; - ns->Search(queryTree, k, neighborsOut, distancesOut); - - // Unmap the query points. - distances.set_size(distancesOut.n_rows, distancesOut.n_cols); - neighbors.set_size(neighborsOut.n_rows, neighborsOut.n_cols); - for (size_t i = 0; i < neighborsOut.n_cols; ++i) - { - neighbors.col(oldFromNewQueries[i]) = neighborsOut.col(i); - distances.col(oldFromNewQueries[i]) = distancesOut.col(i); - } - } - else - ns->Search(querySet, k, neighbors, distances); -} - -//! Save parameters for Train. -template -TrainVisitor::TrainVisitor(arma::mat&& referenceSet, - const size_t leafSize, - const double tau, - const double rho) : - referenceSet(std::move(referenceSet)), - leafSize(leafSize), - tau(tau), - rho(rho) -{} - -//! Default Train on the given NSType instance. -template -template class TreeType> -void TrainVisitor::operator()(NSTypeT* ns) const -{ - if (ns) - return ns->Train(std::move(referenceSet)); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Train on the given NSType specialized for KDTrees. -template -void TrainVisitor::operator()(NSTypeT* ns) const -{ - if (ns) - return TrainLeaf(ns); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Train on the given NSType specialized for BallTrees. -template -void TrainVisitor::operator()(NSTypeT* ns) const -{ - if (ns) - return TrainLeaf(ns); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Train specialized for SPTrees. -template -void TrainVisitor::operator()(SpillKNN* ns) const -{ - if (ns) - { - if (ns->SearchMode() == NAIVE_MODE) - ns->Train(std::move(referenceSet)); - else - { - typename SpillKNN::Tree tree(std::move(referenceSet), tau, leafSize, rho); - ns->Train(std::move(tree)); - } - } - else - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Train specialized for Octrees. -template -void TrainVisitor::operator()(NSTypeT* ns) const -{ - if (ns) - return TrainLeaf(ns); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Train on the given NSType considering the leafSize. -template -template -void TrainVisitor::TrainLeaf(NSType* ns) const -{ - if (ns->SearchMode() == NAIVE_MODE) - ns->Train(std::move(referenceSet)); - else - { - std::vector oldFromNewReferences; - typename NSType::Tree referenceTree(std::move(referenceSet), - oldFromNewReferences, leafSize); - ns->Train(std::move(referenceTree)); - // Set the mappings. - ns->oldFromNewReferences = std::move(oldFromNewReferences); - } -} - -//! Return the search mode. -template -NeighborSearchMode& SearchModeVisitor::operator()(NSType* ns) const -{ - if (ns) - return ns->SearchMode(); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Expose the Epsilon method of the given NSType. -template -double& EpsilonVisitor::operator()(NSType* ns) const -{ - if (ns) - return ns->Epsilon(); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Expose the referenceSet of the given NSType. -template -const arma::mat& ReferenceSetVisitor::operator()(NSType* ns) const -{ - if (ns) - return ns->ReferenceSet(); - throw std::runtime_error("no neighbor search model initialized"); -} - -//! Clean memory, if necessary. -template -void DeleteVisitor::operator()(NSType* ns) const -{ - if (ns) - delete ns; -} - -/** - * Initialize the NSModel with the given type and whether or not a random - * basis should be used. - */ -template -NSModel::NSModel(TreeTypes treeType, bool randomBasis) : - treeType(treeType), - leafSize(20), - tau(0), - rho(0.7), - randomBasis(randomBasis) -{ - // Nothing to do. -} - -template -NSModel::NSModel(const NSModel& other) : - treeType(other.treeType), - leafSize(other.leafSize), - tau(other.tau), - rho(other.rho), - randomBasis(other.randomBasis), - q(other.q), - nSearch(other.nSearch) -{ - // Nothing to do. -} - -template -NSModel::NSModel(NSModel&& other) : - treeType(other.treeType), - leafSize(other.leafSize), - tau(other.tau), - rho(other.rho), - randomBasis(other.randomBasis), - q(std::move(other.q)), - nSearch(other.nSearch) -{ - // Reset parameters of the other model. - other.treeType = TreeTypes::KD_TREE; - other.leafSize = 20; - other.tau = 0; - other.rho = 0.7; - other.randomBasis = false; - other.nSearch = decltype(other.nSearch)(); -} - -template -NSModel& NSModel::operator=(const NSModel& other) -{ - boost::apply_visitor(DeleteVisitor(), nSearch); - - treeType = other.treeType; - leafSize = other.leafSize; - tau = other.tau; - rho = other.rho; - randomBasis = other.randomBasis; - q = other.q; - nSearch = other.nSearch; - - return *this; -} - -template -NSModel& NSModel::operator=(NSModel&& other) -{ - boost::apply_visitor(DeleteVisitor(), nSearch); - - treeType = other.treeType; - leafSize = other.leafSize; - tau = other.tau; - rho = other.rho; - randomBasis = other.randomBasis; - q = std::move(other.q); - // Copy the pointer and type. - nSearch = other.nSearch; - - // Reset parameters of the other model. - other.treeType = TreeTypes::KD_TREE; - other.leafSize = 20; - other.tau = 0; - other.rho = 0.7; - other.randomBasis = false; - other.nSearch = decltype(other.nSearch)(); - - return *this; -} - -//! Clean memory, if necessary. -template -NSModel::~NSModel() -{ - boost::apply_visitor(DeleteVisitor(), nSearch); -} - -//! Serialize the kNN model. -template -template -void NSModel::serialize(Archive& ar, const unsigned int version) -{ - ar & BOOST_SERIALIZATION_NVP(treeType); - // Backward compatibility: older versions of NSModel didn't include these - // parameters. - if (version > 0) - { - ar & BOOST_SERIALIZATION_NVP(leafSize); - ar & BOOST_SERIALIZATION_NVP(tau); - ar & BOOST_SERIALIZATION_NVP(rho); - } - ar & BOOST_SERIALIZATION_NVP(randomBasis); - ar & BOOST_SERIALIZATION_NVP(q); - - // This should never happen, but just in case, be clean with memory. - if (Archive::is_loading::value) - boost::apply_visitor(DeleteVisitor(), nSearch); - - ar & BOOST_SERIALIZATION_NVP(nSearch); -} - -//! Expose the dataset. -template -const arma::mat& NSModel::Dataset() const -{ - return boost::apply_visitor(ReferenceSetVisitor(), nSearch); -} - -//! Access the search mode. -template -NeighborSearchMode NSModel::SearchMode() const -{ - return boost::apply_visitor(SearchModeVisitor(), nSearch); -} - -//! Modify the search mode. -template -NeighborSearchMode& NSModel::SearchMode() -{ - return boost::apply_visitor(SearchModeVisitor(), nSearch); -} - -template -double NSModel::Epsilon() const -{ - return boost::apply_visitor(EpsilonVisitor(), nSearch); -} - -template -double& NSModel::Epsilon() -{ - return boost::apply_visitor(EpsilonVisitor(), nSearch); -} - -//! Build the reference tree. -template -void NSModel::BuildModel(arma::mat&& referenceSet, - const size_t leafSize, - const NeighborSearchMode searchMode, - const double epsilon) -{ - this->leafSize = leafSize; - // Initialize random basis if necessary. - if (randomBasis) - { - Log::Info << "Creating random basis..." << std::endl; - while (true) - { - // [Q, R] = qr(randn(d, d)); - // Q = Q * diag(sign(diag(R))); - arma::mat r; - if (arma::qr(q, r, arma::randn(referenceSet.n_rows, - referenceSet.n_rows))) - { - arma::vec rDiag(r.n_rows); - for (size_t i = 0; i < rDiag.n_elem; ++i) - { - if (r(i, i) < 0) - rDiag(i) = -1; - else if (r(i, i) > 0) - rDiag(i) = 1; - else - rDiag(i) = 0; - } - - q *= arma::diagmat(rDiag); - - // Check if the determinant is positive. - if (arma::det(q) >= 0) - break; - } - } - } - - // Clean memory, if necessary. - boost::apply_visitor(DeleteVisitor(), nSearch); - - // Do we need to modify the reference set? - if (randomBasis) - referenceSet = q * referenceSet; - - if (searchMode != NAIVE_MODE) - { - Timer::Start("tree_building"); - Log::Info << "Building reference tree..." << std::endl; - } - - switch (treeType) - { - case KD_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case COVER_TREE: - nSearch = new NSType(searchMode, - epsilon); - break; - case R_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case R_STAR_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case BALL_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case X_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case HILBERT_R_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case R_PLUS_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case R_PLUS_PLUS_TREE: - nSearch = new NSType(searchMode, - epsilon); - break; - case VP_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case RP_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case MAX_RP_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case SPILL_TREE: - nSearch = new SpillKNN(searchMode, epsilon); - break; - case UB_TREE: - nSearch = new NSType(searchMode, epsilon); - break; - case OCTREE: - nSearch = new NSType(searchMode, epsilon); - break; - } - - TrainVisitor tn(std::move(referenceSet), leafSize, tau, rho); - boost::apply_visitor(tn, nSearch); - - if (searchMode != NAIVE_MODE) - { - Timer::Stop("tree_building"); - Log::Info << "Tree built." << std::endl; - } -} - -//! Perform neighbor search. The query set will be reordered. -template -void NSModel::Search(arma::mat&& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - // We may need to map the query set randomly. - if (randomBasis) - querySet = q * querySet; - - Log::Info << "Searching for " << k << " neighbors with "; - - switch (SearchMode()) - { - case NAIVE_MODE: - Log::Info << "brute-force (naive) search..." << std::endl; - break; - case SINGLE_TREE_MODE: - Log::Info << "single-tree " << TreeName() << " search..." << std::endl; - break; - case DUAL_TREE_MODE: - Log::Info << "dual-tree " << TreeName() << " search..." << std::endl; - break; - case GREEDY_SINGLE_TREE_MODE: - Log::Info << "greedy single-tree " << TreeName() << " search..." - << std::endl; - break; - } - - BiSearchVisitor search(querySet, k, neighbors, distances, - leafSize, tau, rho); - boost::apply_visitor(search, nSearch); -} - -//! Perform neighbor search. -template -void NSModel::Search(const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - Log::Info << "Searching for " << k << " neighbors with "; - - switch (SearchMode()) - { - case NAIVE_MODE: - Log::Info << "brute-force (naive) search..." << std::endl; - break; - case SINGLE_TREE_MODE: - Log::Info << "single-tree " << TreeName() << " search..." << std::endl; - break; - case DUAL_TREE_MODE: - Log::Info << "dual-tree " << TreeName() << " search..." << std::endl; - break; - case GREEDY_SINGLE_TREE_MODE: - Log::Info << "greedy single-tree " << TreeName() << " search..." - << std::endl; - break; - } - - if (Epsilon() != 0 && SearchMode() != NAIVE_MODE) - Log::Info << "Maximum of " << Epsilon() * 100 << "% relative error." - << std::endl; - - MonoSearchVisitor search(k, neighbors, distances); - boost::apply_visitor(search, nSearch); -} - -//! Get the name of the tree type. -template -std::string NSModel::TreeName() const -{ - switch (treeType) - { - case KD_TREE: - return "kd-tree"; - case COVER_TREE: - return "cover tree"; - case R_TREE: - return "R tree"; - case R_STAR_TREE: - return "R* tree"; - case BALL_TREE: - return "ball tree"; - case X_TREE: - return "X tree"; - case HILBERT_R_TREE: - return "Hilbert R tree"; - case R_PLUS_TREE: - return "R+ tree"; - case R_PLUS_PLUS_TREE: - return "R++ tree"; - case SPILL_TREE: - return "Spill tree"; - case VP_TREE: - return "vantage point tree"; - case RP_TREE: - return "random projection tree (mean split)"; - case MAX_RP_TREE: - return "random projection tree (max split)"; - case UB_TREE: - return "UB tree"; - case OCTREE: - return "octree"; - default: - return "unknown tree"; - } -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/furthest_neighbor_sort.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/furthest_neighbor_sort.hpp deleted file mode 100644 index d7c01258a..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/furthest_neighbor_sort.hpp +++ /dev/null @@ -1,205 +0,0 @@ -/** - * @file furthest_neighbor_sort.hpp - * @author Ryan Curtin - * - * Implementation of the SortPolicy class for NeighborSearch; in this case, the - * furthest neighbors are those that are most important. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_FURTHEST_NEIGHBOR_SORT_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_FURTHEST_NEIGHBOR_SORT_HPP - -#include - -namespace mlpack { -namespace neighbor { - -/** - * This class implements the necessary methods for the SortPolicy template - * parameter of the NeighborSearch class. The sorting policy here is that the - * minimum distance is the best (so, when used with NeighborSearch, the output - * is furthest neighbors). - */ -class FurthestNeighborSort -{ - public: - /** - * Return whether or not value is "better" than ref. In this case, that means - * that the value is greater than or equal to the reference. - * - * @param value Value to compare - * @param ref Value to compare with - * - * @return bool indicating whether or not (value >= ref). - */ - static inline bool IsBetter(const double value, const double ref) - { - return (value >= ref); - } - - /** - * Return the best possible distance between two nodes. In our case, this is - * the maximum distance between the two tree nodes using the given distance - * function. - */ - template - static double BestNodeToNodeDistance(const TreeType* queryNode, - const TreeType* referenceNode); - - /** - * Return the best possible distance between two nodes, given that the - * distance between the centers of the two nodes has already been calculated. - * This is used in conjunction with trees that have self-children (like cover - * trees). - */ - template - static double BestNodeToNodeDistance(const TreeType* queryNode, - const TreeType* referenceNode, - const double centerToCenterDistance); - - /** - * Return the best possible distance between the query node and the reference - * child node given the base case distance between the query node and the - * reference node. TreeType::ParentDistance() must be implemented to use - * this. - * - * @param queryNode Query node. - * @param referenceNode Reference node. - * @param referenceChildNode Child of reference node which is being inspected. - * @param centerToCenterDistance Distance between centers of query node and - * reference node. - */ - template - static double BestNodeToNodeDistance(const TreeType* queryNode, - const TreeType* referenceNode, - const TreeType* referenceChildNode, - const double centerToCenterDistance); - - /** - * Return the best possible distance between a node and a point. In our case, - * this is the maximum distance between the tree node and the point using the - * given distance function. - */ - template - static double BestPointToNodeDistance(const VecType& queryPoint, - const TreeType* referenceNode); - - /** - * Return the best possible distance between a point and a node, given that - * the distance between the point and the center of the node has already been - * calculated. This is used in conjunction with trees that have - * self-children (like cover trees). - */ - template - static double BestPointToNodeDistance(const VecType& queryPoint, - const TreeType* referenceNode, - const double pointToCenterDistance); - - /** - * Return the best child according to this sort policy. In this case it will - * return the one with the maximum distance. - */ - template - static size_t GetBestChild(const VecType& queryPoint, TreeType& referenceNode) - { - return referenceNode.GetFurthestChild(queryPoint); - }; - - /** - * Return the best child according to this sort policy. In this case it will - * return the one with the maximum distance. - */ - template - static size_t GetBestChild(const TreeType& queryNode, TreeType& referenceNode) - { - return referenceNode.GetFurthestChild(queryNode); - }; - - /** - * Return what should represent the worst possible distance with this - * particular sort policy. In our case, this should be the minimum possible - * distance, 0. - * - * @return 0 - */ - static inline double WorstDistance() { return 0; } - - /** - * Return what should represent the best possible distance with this - * particular sort policy. In our case, this should be the maximum possible - * distance, DBL_MAX. - * - * @return DBL_MAX - */ - static inline double BestDistance() { return DBL_MAX; } - - /** - * Return the best combination of the two distances. - */ - static inline double CombineBest(const double a, const double b) - { - if (a == DBL_MAX || b == DBL_MAX) - return DBL_MAX; - return a + b; - } - - /** - * Return the worst combination of the two distances. - */ - static inline double CombineWorst(const double a, const double b) - { return std::max(a - b, 0.0); } - - /** - * Return the given value relaxed. - * - * @param value Value to relax. - * @param epsilon Relative error (non-negative). - * - * @return double Value relaxed. - */ - static inline double Relax(const double value, const double epsilon) - { - if (value == 0) - return 0; - if (value == DBL_MAX || epsilon >= 1) - return DBL_MAX; - return (1 / (1 - epsilon)) * value; - } - - /** - * Convert the given distance to a score. Lower scores are better, but for - * furthest neighbor search, larger distances are better. Therefore we must - * invert the given distance. - */ - static inline double ConvertToScore(const double distance) - { - if (distance == DBL_MAX) - return 0.0; - else if (distance == 0.0) - return DBL_MAX; - else - return (1.0 / distance); - } - - /** - * Convert the given score back to a distance. This is the inverse of the - * operation of converting a distance to a score, and again, for furthest - * neighbor search, corresponds to inverting the value. - */ - static inline double ConvertToDistance(const double score) - { - return ConvertToScore(score); - } -}; - -} // namespace neighbor -} // namespace mlpack - -// Include implementation of templated functions. -#include "furthest_neighbor_sort_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/furthest_neighbor_sort_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/furthest_neighbor_sort_impl.hpp deleted file mode 100644 index 437821ace..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/furthest_neighbor_sort_impl.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/*** - * @file furthest_neighbor_sort_impl.hpp - * @author Ryan Curtin - * - * Implementation of templated methods for the FurthestNeighborSort SortPolicy - * class for the NeighborSearch class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_FURTHEST_NEIGHBOR_SORT_IMPL_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_FURTHEST_NEIGHBOR_SORT_IMPL_HPP - -namespace mlpack { -namespace neighbor { - -template -inline double FurthestNeighborSort::BestNodeToNodeDistance( - const TreeType* queryNode, - const TreeType* referenceNode) -{ - // This is not implemented yet for the general case because the trees do not - // accept arbitrary distance metrics. - return queryNode->MaxDistance(*referenceNode); -} - -template -inline double FurthestNeighborSort::BestNodeToNodeDistance( - const TreeType* queryNode, - const TreeType* referenceNode, - const double centerToCenterDistance) -{ - return queryNode->MaxDistance(*referenceNode, centerToCenterDistance); -} - -template -inline double FurthestNeighborSort::BestNodeToNodeDistance( - const TreeType* queryNode, - const TreeType* referenceNode, - const TreeType* referenceChildNode, - const double centerToCenterDistance) -{ - return queryNode->MaxDistance(*referenceNode, centerToCenterDistance) + - referenceChildNode->ParentDistance(); -} - -template -inline double FurthestNeighborSort::BestPointToNodeDistance( - const VecType& point, - const TreeType* referenceNode) -{ - // This is not implemented yet for the general case because the trees do not - // accept arbitrary distance metrics. - return referenceNode->MaxDistance(point); -} - -template -inline double FurthestNeighborSort::BestPointToNodeDistance( - const VecType& point, - const TreeType* referenceNode, - const double pointToCenterDistance) -{ - return referenceNode->MaxDistance(point, pointToCenterDistance); -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/nearest_neighbor_sort.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/nearest_neighbor_sort.hpp deleted file mode 100644 index 9f97cb8d6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/nearest_neighbor_sort.hpp +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @file nearest_neighbor_sort.hpp - * @author Ryan Curtin - * - * Implementation of the SortPolicy class for NeighborSearch; in this case, the - * nearest neighbors are those that are most important. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_SORT_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_NEAREST_NEIGHBOR_SORT_HPP - -#include - -namespace mlpack { -namespace neighbor { - -/** - * This class implements the necessary methods for the SortPolicy template - * parameter of the NeighborSearch class. The sorting policy here is that the - * minimum distance is the best (so, when used with NeighborSearch, the output - * is nearest neighbors). - * - * This class is also meant to serve as a guide to implement a custom - * SortPolicy. All of the methods implemented here must be implemented by any - * other SortPolicy classes. - */ -class NearestNeighborSort -{ - public: - /** - * Return whether or not value is "better" than ref. In this case, that means - * that the value is less than or equal to the reference. - * - * @param value Value to compare - * @param ref Value to compare with - * - * @return bool indicating whether or not (value <= ref). - */ - static inline bool IsBetter(const double value, const double ref) - { - return (value <= ref); - } - - /** - * Return the best possible distance between two nodes. In our case, this is - * the minimum distance between the two tree nodes using the given distance - * function. - */ - template - static double BestNodeToNodeDistance(const TreeType* queryNode, - const TreeType* referenceNode); - - /** - * Return the best possible distance between two nodes, given that the - * distance between the centers of the two nodes has already been calculated. - * This is used in conjunction with trees that have self-children (like cover - * trees). - */ - template - static double BestNodeToNodeDistance(const TreeType* queryNode, - const TreeType* referenceNode, - const double centerToCenterDistance); - - /** - * Return the best possible distance between the query node and the reference - * child node given the base case distance between the query node and the - * reference node. TreeType::ParentDistance() must be implemented to use - * this. - * - * @param queryNode Query node. - * @param referenceNode Reference node. - * @param referenceChildNode Child of reference node which is being inspected. - * @param centerToCenterDistance Distance between centers of query node and - * reference node. - */ - template - static double BestNodeToNodeDistance(const TreeType* queryNode, - const TreeType* referenceNode, - const TreeType* referenceChildNode, - const double centerToCenterDistance); - - /** - * Return the best possible distance between a node and a point. In our case, - * this is the minimum distance between the tree node and the point using the - * given distance function. - */ - template - static double BestPointToNodeDistance(const VecType& queryPoint, - const TreeType* referenceNode); - - /** - * Return the best possible distance between a point and a node, given that - * the distance between the point and the center of the node has already been - * calculated. This is used in conjunction with trees that have - * self-children (like cover trees). - */ - template - static double BestPointToNodeDistance(const VecType& queryPoint, - const TreeType* referenceNode, - const double pointToCenterDistance); - - /** - * Return the best child according to this sort policy. In this case it will - * return the one with the minimum distance. - */ - template - static size_t GetBestChild(const VecType& queryPoint, TreeType& referenceNode) - { - return referenceNode.GetNearestChild(queryPoint); - }; - - /** - * Return the best child according to this sort policy. In this case it will - * return the one with the minimum distance. - */ - template - static size_t GetBestChild(const TreeType& queryNode, TreeType& referenceNode) - { - return referenceNode.GetNearestChild(queryNode); - }; - - /** - * Return what should represent the worst possible distance with this - * particular sort policy. In our case, this should be the maximum possible - * distance, DBL_MAX. - * - * @return DBL_MAX - */ - static inline double WorstDistance() { return DBL_MAX; } - - /** - * Return what should represent the best possible distance with this - * particular sort policy. In our case, this should be the minimum possible - * distance, 0.0. - * - * @return 0.0 - */ - static inline double BestDistance() { return 0.0; } - - /** - * Return the best combination of the two distances. - */ - static inline double CombineBest(const double a, const double b) - { - return std::max(a - b, 0.0); - } - - /** - * Return the worst combination of the two distances. - */ - static inline double CombineWorst(const double a, const double b) - { - if (a == DBL_MAX || b == DBL_MAX) - return DBL_MAX; - return a + b; - } - - /** - * Return the given value relaxed. - * - * @param value Value to relax. - * @param epsilon Relative error (non-negative). - * - * @return double Value relaxed. - */ - static inline double Relax(const double value, const double epsilon) - { - if (value == DBL_MAX) - return DBL_MAX; - return (1 / (1 + epsilon)) * value; - } - - /** - * Convert the given distance into a score. Lower scores are better, so in - * the case of nearest neighbor sort where lower distances are better, we just - * return the distance. - */ - static inline double ConvertToScore(const double distance) - { - return distance; - } - - /** - * Convert the given score to a distance. This is the inverse of the - * operation provided by ConvertToScore(). For nearest neighbor search, there - * is no need for any change. - */ - static inline double ConvertToDistance(const double score) - { - return score; - } -}; - -} // namespace neighbor -} // namespace mlpack - -// Include implementation of templated functions. -#include "nearest_neighbor_sort_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/nearest_neighbor_sort_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/nearest_neighbor_sort_impl.hpp deleted file mode 100644 index 6dcba3de3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/sort_policies/nearest_neighbor_sort_impl.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @file nearest_neighbor_sort_impl.hpp - * @author Ryan Curtin - * - * Implementation of templated methods for the NearestNeighborSort SortPolicy - * class for the NeighborSearch class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_NEIGHBOR_NEAREST_NEIGHBOR_SORT_IMPL_HPP -#define MLPACK_NEIGHBOR_NEAREST_NEIGHBOR_SORT_IMPL_HPP - -namespace mlpack { -namespace neighbor { - -template -inline double NearestNeighborSort::BestNodeToNodeDistance( - const TreeType* queryNode, - const TreeType* referenceNode) -{ - // This is not implemented yet for the general case because the trees do not - // accept arbitrary distance metrics. - return queryNode->MinDistance(*referenceNode); -} - -template -inline double NearestNeighborSort::BestNodeToNodeDistance( - const TreeType* queryNode, - const TreeType* referenceNode, - const double centerToCenterDistance) -{ - return queryNode->MinDistance(*referenceNode, centerToCenterDistance); -} - -template -inline double NearestNeighborSort::BestNodeToNodeDistance( - const TreeType* queryNode, - const TreeType* /* referenceNode */, - const TreeType* referenceChildNode, - const double centerToCenterDistance) -{ - return queryNode->MinDistance(*referenceChildNode, centerToCenterDistance) - - referenceChildNode->ParentDistance(); -} - -template -inline double NearestNeighborSort::BestPointToNodeDistance( - const VecType& point, - const TreeType* referenceNode) -{ - // This is not implemented yet for the general case because the trees do not - // accept arbitrary distance metrics. - return referenceNode->MinDistance(point); -} - -template -inline double NearestNeighborSort::BestPointToNodeDistance( - const VecType& point, - const TreeType* referenceNode, - const double pointToCenterDistance) -{ - return referenceNode->MinDistance(point, pointToCenterDistance); -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/typedef.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/typedef.hpp deleted file mode 100644 index 0da96f47c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/typedef.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @file typedef.hpp - * @author Ryan Curtin - * - * Simple typedefs describing template instantiations of the NeighborSearch - * class which are commonly used. This is meant to be included by - * neighbor_search.h but is a separate file for simplicity. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_NEIGHBOR_SEARCH_TYPEDEF_H -#define MLPACK_NEIGHBOR_SEARCH_TYPEDEF_H - -// In case someone included this directly. -#include "neighbor_search.hpp" - -#include - -#include "sort_policies/nearest_neighbor_sort.hpp" -#include "sort_policies/furthest_neighbor_sort.hpp" - -namespace mlpack { -namespace neighbor { - -/** - * The KNN class is the k-nearest-neighbors method. It returns L2 distances - * (Euclidean distances) for each of the k nearest neighbors. - */ -typedef NeighborSearch KNN; - -/** - * The KFN class is the k-furthest-neighbors method. It returns L2 distances - * (Euclidean distances) for each of the k furthest neighbors. - */ -typedef NeighborSearch KFN; - -/** - * The DefeatistKNN class is the k-nearest-neighbors method considering - * defeatist search. It returns L2 distances (Euclidean distances) for each of - * the k nearest neighbors found. - * @tparam TreeType The tree type to use; must adhere to the TreeType API, - * and implement Defeatist Traversers. - */ -template class TreeType = tree::SPTree> -using DefeatistKNN = NeighborSearch< - NearestNeighborSort, - metric::EuclideanDistance, - arma::mat, - TreeType, - TreeType, - arma::mat>::template DefeatistDualTreeTraverser, - TreeType, - arma::mat>::template DefeatistSingleTreeTraverser>; - -/** - * The SpillKNN class is the k-nearest-neighbors method considering defeatist - * search on SPTree. It returns L2 distances (Euclidean distances) for each of - * the k nearest neighbors found. - */ -typedef DefeatistKNN SpillKNN; - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/unmap.hpp b/src/sdk/mlpack/include/mlpack/methods/neighbor_search/unmap.hpp deleted file mode 100644 index 884df85da..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/neighbor_search/unmap.hpp +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @file unmap.hpp - * @author Ryan Curtin - * - * Convenience methods to unmap results. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NEIGHBOR_SEARCH_UNMAP_HPP -#define MLPACK_METHODS_NEIGHBOR_SEARCH_UNMAP_HPP - -#include - -namespace mlpack { -namespace neighbor { - -/** - * Assuming that the datasets have been mapped using the referenceMap and the - * queryMap (such as during kd-tree construction), unmap the columns of the - * distances and neighbors matrices into neighborsOut and distancesOut, and also - * unmap the entries in each row of neighbors. This is useful for the dual-tree - * case. - * - * @param neighbors Matrix of neighbors resulting from neighbor search. - * @param distances Matrix of distances resulting from neighbor search. - * @param referenceMap Mapping of reference set to old points. - * @param queryMap Mapping of query set to old points. - * @param neighborsOut Matrix to store unmapped neighbors into. - * @param distancesOut Matrix to store unmapped distances into. - * @param squareRoot If true, take the square root of the distances. - */ -void Unmap(const arma::Mat& neighbors, - const arma::mat& distances, - const std::vector& referenceMap, - const std::vector& queryMap, - arma::Mat& neighborsOut, - arma::mat& distancesOut, - const bool squareRoot = false); - -/** - * Assuming that the datasets have been mapped using referenceMap (such as - * during kd-tree construction), unmap the columns of the distances and - * neighbors matrices into neighborsOut and distancesOut, and also unmap the - * entries in each row of neighbors. This is useful for the single-tree case. - * - * @param neighbors Matrix of neighbors resulting from neighbor search. - * @param distances Matrix of distances resulting from neighbor search. - * @param referenceMap Mapping of reference set to old points. - * @param neighborsOut Matrix to store unmapped neighbors into. - * @param distancesOut Matrix to store unmapped distances into. - * @param squareRoot If true, take the square root of the distances. - */ -void Unmap(const arma::Mat& neighbors, - const arma::mat& distances, - const std::vector& referenceMap, - arma::Mat& neighborsOut, - arma::mat& distancesOut, - const bool squareRoot = false); - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/kmeans_selection.hpp b/src/sdk/mlpack/include/mlpack/methods/nystroem_method/kmeans_selection.hpp deleted file mode 100644 index 5acc79a07..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/kmeans_selection.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @file kmeans_selection.hpp - * @author Marcus Edel - * - * Use the centroids of the K-Means clustering method for use in the Nystroem - * method of kernel matrix approximation. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NYSTROEM_METHOD_KMEANS_SELECTION_HPP -#define MLPACK_METHODS_NYSTROEM_METHOD_KMEANS_SELECTION_HPP - -#include -#include - -namespace mlpack { -namespace kernel { - -/** - * Implementation of the kmeans sampling scheme. - * - * @tparam ClusteringType Type of clustering. - * @tparam maxIterations Maximum number of iterations allowed before giving up. - */ -template, size_t maxIterations = 5> -class KMeansSelection -{ - public: - /** - * Use the K-Means clustering method to select the specified number of points - * in the dataset. You are responsible for deleting the returned matrix! - * - * @param data Dataset to sample from. - * @param m Number of points to select. - * @return Matrix pointer in which centroids are stored. - */ - const static arma::mat* Select(const arma::mat& data, const size_t m) - { - arma::Row assignments; - arma::mat* centroids = new arma::mat; - - // Perform the K-Means clustering method. - ClusteringType kmeans(maxIterations); - kmeans.Cluster(data, m, assignments, *centroids); - - return centroids; - } -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/nystroem_method.hpp b/src/sdk/mlpack/include/mlpack/methods/nystroem_method/nystroem_method.hpp deleted file mode 100644 index e2e0bcabb..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/nystroem_method.hpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @file nystroem_method.hpp - * @author Ryan Curtin - * @author Marcus Edel - * - * Implementation of the Nystroem method for approximating a kernel matrix. - * There are many variations on how to do this, so template parameters allow the - * selection of many different techniques. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_HPP -#define MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_HPP - -#include -#include "kmeans_selection.hpp" - -namespace mlpack { -namespace kernel { - -template< - typename KernelType, - typename PointSelectionPolicy = KMeansSelection<> -> -class NystroemMethod -{ - public: - /** - * Create the NystroemMethod object. The constructor here does not really do - * anything. - * - * @param data Data matrix. - * @param kernel Kernel to be used for computation. - * @param rank Rank to be used for matrix approximation. - */ - NystroemMethod(const arma::mat& data, KernelType& kernel, const size_t rank); - - /** - * Apply the low-rank factorization to obtain an output matrix G such that - * K' = G * G^T. - * - * @param output Matrix to store kernel approximation into. - */ - void Apply(arma::mat& output); - - /** - * Construct the kernel matrix with matrix that contains the selected points. - * - * @param data Data matrix pointer. - * @param miniKernel to store the constructed mini-kernel matrix in. - * @param miniKernel to store the constructed semi-kernel matrix in. - */ - void GetKernelMatrix(const arma::mat* data, - arma::mat& miniKernel, - arma::mat& semiKernel); - - /** - * Construct the kernel matrix with the selected points. - * - * @param points Indices of selected points. - * @param miniKernel to store the constructed mini-kernel matrix in. - * @param miniKernel to store the constructed semi-kernel matrix in. - */ - void GetKernelMatrix(const arma::Col& selectedPoints, - arma::mat& miniKernel, - arma::mat& semiKernel); - - private: - //! The reference dataset. - const arma::mat& data; - //! The locally stored kernel, if it is necessary. - KernelType& kernel; - //! Rank used for matrix approximation. - const size_t rank; -}; - -} // namespace kernel -} // namespace mlpack - -// Include implementation. -#include "nystroem_method_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/nystroem_method_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/nystroem_method/nystroem_method_impl.hpp deleted file mode 100644 index 4218811dd..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/nystroem_method_impl.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file nystroem_method_impl.hpp - * @author Ryan Curtin - * @author Marcus Edel - * - * Implementation of the Nystroem method for approximating a kernel matrix. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_IMPL_HPP -#define MLPACK_METHODS_NYSTROEM_METHOD_NYSTROEM_METHOD_IMPL_HPP - -// In case it hasn't been included yet. -#include "nystroem_method.hpp" - -namespace mlpack { -namespace kernel { - -template -NystroemMethod::NystroemMethod( - const arma::mat& data, - KernelType& kernel, - const size_t rank) : - data(data), - kernel(kernel), - rank(rank) -{ } - -template -void NystroemMethod::GetKernelMatrix( - const arma::mat* selectedData, - arma::mat& miniKernel, - arma::mat& semiKernel) -{ - // Assemble mini-kernel matrix. - for (size_t i = 0; i < rank; ++i) - for (size_t j = 0; j < rank; ++j) - miniKernel(i, j) = kernel.Evaluate(selectedData->col(i), - selectedData->col(j)); - - // Construct semi-kernel matrix with interactions between selected data and - // all points. - for (size_t i = 0; i < data.n_cols; ++i) - for (size_t j = 0; j < rank; ++j) - semiKernel(i, j) = kernel.Evaluate(data.col(i), - selectedData->col(j)); - // Clean the memory. - delete selectedData; -} - -template -void NystroemMethod::GetKernelMatrix( - const arma::Col& selectedPoints, - arma::mat& miniKernel, - arma::mat& semiKernel) -{ - // Assemble mini-kernel matrix. - for (size_t i = 0; i < rank; ++i) - for (size_t j = 0; j < rank; ++j) - miniKernel(i, j) = kernel.Evaluate(data.col(selectedPoints(i)), - data.col(selectedPoints(j))); - - // Construct semi-kernel matrix with interactions between selected points and - // all points. - for (size_t i = 0; i < data.n_cols; ++i) - for (size_t j = 0; j < rank; ++j) - semiKernel(i, j) = kernel.Evaluate(data.col(i), - data.col(selectedPoints(j))); -} - -template -void NystroemMethod::Apply(arma::mat& output) -{ - arma::mat miniKernel(rank, rank); - arma::mat semiKernel(data.n_cols, rank); - - GetKernelMatrix(PointSelectionPolicy::Select(data, rank), miniKernel, - semiKernel); - - // Singular value decomposition mini-kernel matrix. - arma::mat U, V; - arma::vec s; - arma::svd(U, s, V, miniKernel); - - // Construct the output matrix. - arma::mat normalization = arma::diagmat(1.0 / sqrt(s)); - output = semiKernel * U * normalization * V; -} - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/ordered_selection.hpp b/src/sdk/mlpack/include/mlpack/methods/nystroem_method/ordered_selection.hpp deleted file mode 100644 index 008d484a5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/ordered_selection.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @file ordered_selection.hpp - * @author Ryan Curtin - * - * Select the first points of the dataset for use in the Nystroem method of - * kernel matrix approximation. This is mostly for testing, but might have - * other uses. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NYSTROEM_METHOD_ORDERED_SELECTION_HPP -#define MLPACK_METHODS_NYSTROEM_METHOD_ORDERED_SELECTION_HPP - -#include - -namespace mlpack { -namespace kernel { - -class OrderedSelection -{ - public: - /** - * Select the specified number of points in the dataset. - * - * @param data Dataset to sample from. - * @param m Number of points to select. - * @return Indices of selected points from the dataset. - */ - const static arma::Col Select(const arma::mat& /* unused */, - const size_t m) - { - // This generates [0 1 2 3 ... (m - 1)]. - return arma::linspace >(0, m - 1, m); - } -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/random_selection.hpp b/src/sdk/mlpack/include/mlpack/methods/nystroem_method/random_selection.hpp deleted file mode 100644 index c670cc789..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/nystroem_method/random_selection.hpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @file random_selection.hpp - * @author Ryan Curtin - * - * Randomly select some points (with replacement) to use for the Nystroem - * method. Replacement is suboptimal, but for rank << number of points, this is - * unlikely. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NYSTROEM_METHOD_RANDOM_SELECTION_HPP -#define MLPACK_METHODS_NYSTROEM_METHOD_RANDOM_SELECTION_HPP - -#include - -namespace mlpack { -namespace kernel { - -class RandomSelection -{ - public: - /** - * Randomly select the specified number of points in the dataset. - * - * @param data Dataset to sample from. - * @param m Number of points to select. - * @return Indices of selected points from the dataset. - */ - const static arma::Col Select(const arma::mat& data, const size_t m) - { - arma::Col selectedPoints(m); - for (size_t i = 0; i < m; ++i) - selectedPoints(i) = math::RandInt(0, data.n_cols); - - return selectedPoints; - } -}; - -} // namespace kernel -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/exact_svd_method.hpp b/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/exact_svd_method.hpp deleted file mode 100644 index dd5fa1e98..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/exact_svd_method.hpp +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @file exact_svd_method.hpp - * @author Ajinkya Kale - * @author Ryan Curtin - * @author Marcus Edel - * - * Implementation of the exact svd method for use in the Principal Components - * Analysis method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_EXACT_SVD_METHOD_HPP -#define MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_EXACT_SVD_METHOD_HPP - -#include - -namespace mlpack { -namespace pca { - -/** - * Implementation of the exact SVD policy. - */ -class ExactSVDPolicy -{ - public: - /** - * Apply Principal Component Analysis to the provided data set using the - * exact SVD method. - * - * @param data Data matrix. - * @param centeredData Centered data matrix. - * @param transformedData Matrix to put results of PCA into. - * @param eigVal Vector to put eigenvalues into. - * @param eigvec Matrix to put eigenvectors (loadings) into. - * @param rank Rank of the decomposition. - */ - void Apply(const arma::mat& data, - const arma::mat& centeredData, - arma::mat& transformedData, - arma::vec& eigVal, - arma::mat& eigvec, - const size_t /* rank */) - { - // This matrix will store the right singular values; we do not need them. - arma::mat v; - - // Do singular value decomposition. Use the economical singular value - // decomposition if the columns are much larger than the rows. - if (data.n_rows < data.n_cols) - { - // Do economical singular value decomposition and compute only the left - // singular vectors. - arma::svd_econ(eigvec, eigVal, v, centeredData, 'l'); - } - else - { - arma::svd(eigvec, eigVal, v, centeredData); - } - - // Now we must square the singular values to get the eigenvalues. - // In addition we must divide by the number of points, because the - // covariance matrix is X * X' / (N - 1). - eigVal %= eigVal / (data.n_cols - 1); - - // Project the samples to the principals. - transformedData = arma::trans(eigvec) * centeredData; - } -}; - -} // namespace pca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/quic_svd_method.hpp b/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/quic_svd_method.hpp deleted file mode 100644 index f3ecc2103..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/quic_svd_method.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file quic_svd_method.hpp - * @author Marcus Edel - * - * Implementation of the QUIC-SVD policy for use in the Principal Components - * Analysis method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_QUIC_SVD_METHOD_HPP -#define MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_QUIC_SVD_METHOD_HPP - -#include -#include - -namespace mlpack { -namespace pca { - -/** - * Implementation of the QUIC-SVD policy. - */ -class QUICSVDPolicy -{ - public: - /** - * Use QUIC-SVD method to perform the principal components analysis (PCA). - * - * @param epsilon Error tolerance fraction for calculated subspace. - * @param delta Cumulative probability for Monte Carlo error lower bound. - */ - QUICSVDPolicy(const double epsilon = 0.03, const double delta = 0.1) : - epsilon(epsilon), - delta(delta) - { - /* Nothing to do here */ - } - - /** - * Apply Principal Component Analysis to the provided data set using the - * QUIC-SVD method. - * - * @param data Data matrix. - * @param centeredData Centered data matrix. - * @param transformedData Matrix to put results of PCA into. - * @param eigVal Vector to put eigenvalues into. - * @param eigvec Matrix to put eigenvectors (loadings) into. - * @param rank Rank of the decomposition. - */ - void Apply(const arma::mat& data, - const arma::mat& centeredData, - arma::mat& transformedData, - arma::vec& eigVal, - arma::mat& eigvec, - const size_t /* rank */) - { - // This matrix will store the right singular values; we do not need them. - arma::mat v, sigma; - - // Do singular value decomposition using the QUIC-SVD algorithm. - svd::QUIC_SVD quicsvd(centeredData, eigvec, v, sigma, epsilon, delta); - - // Now we must square the singular values to get the eigenvalues. - // In addition we must divide by the number of points, because the - // covariance matrix is X * X' / (N - 1). - eigVal = arma::pow(arma::diagvec(sigma), 2) / (data.n_cols - 1); - - // Project the samples to the principals. - transformedData = arma::trans(eigvec) * centeredData; - } - - //! Get the error tolerance fraction for calculated subspace. - double Epsilon() const { return epsilon; } - //! Modify the error tolerance fraction for calculated subspace. - double& Epsilon() { return epsilon; } - - //! Get the cumulative probability for Monte Carlo error lower bound. - double Delta() const { return delta; } - //! Modify the cumulative probability for Monte Carlo error lower bound. - double& Delta() { return delta; } - - private: - //! Error tolerance fraction for calculated subspace. - double epsilon; - - //! Cumulative probability for Monte Carlo error lower bound. - double delta; -}; - -} // namespace pca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/randomized_block_krylov_method.hpp b/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/randomized_block_krylov_method.hpp deleted file mode 100644 index 957cd3bbd..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/randomized_block_krylov_method.hpp +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @file randomized_block_krylov_method.hpp - * @author Marcus Edel - * - * Implementation of the randomized block krylov SVD method for use in the - * Principal Components Analysis method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_RANDOMIZED_BLOCK_KRYLOV_HPP -#define MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_RANDOMIZED_BLOCK_KRYLOV_HPP - -#include -#include - -namespace mlpack { -namespace pca { - -/** - * Implementation of the randomized block krylov SVD policy. - */ -class RandomizedBlockKrylovSVDPolicy -{ - public: - /** - * Use randomized block krylov SVD method to perform the principal components - * analysis (PCA). - * - * @param maxIterations Number of iterations for the power method - * (Default: 2). - * @param blockSize The block size, must be >= rank (Default: rank + 10). - */ - RandomizedBlockKrylovSVDPolicy(const size_t maxIterations = 2, - const size_t blockSize = 0) : - maxIterations(maxIterations), - blockSize(blockSize) - { - /* Nothing to do here */ - } - - /** - * Apply Principal Component Analysis to the provided data set using the - * randomized block krylov SVD method. - * - * @param data Data matrix. - * @param centeredData Centered data matrix. - * @param transformedData Matrix to put results of PCA into. - * @param eigVal Vector to put eigenvalues into. - * @param eigvec Matrix to put eigenvectors (loadings) into. - * @param rank Rank of the decomposition. - */ - void Apply(const arma::mat& data, - const arma::mat& centeredData, - arma::mat& transformedData, - arma::vec& eigVal, - arma::mat& eigvec, - const size_t rank) - { - // This matrix will store the right singular values; we do not need them. - arma::mat v; - - // Do singular value decomposition using the randomized block krylov SVD - // algorithm. - svd::RandomizedBlockKrylovSVD rsvd(maxIterations, blockSize); - rsvd.Apply(centeredData, eigvec, eigVal, v, rank); - - // Now we must square the singular values to get the eigenvalues. - // In addition we must divide by the number of points, because the - // covariance matrix is X * X' / (N - 1). - eigVal %= eigVal / (data.n_cols - 1); - - // Project the samples to the principals. - transformedData = arma::trans(eigvec) * centeredData; - } - - //! Get the number of iterations for the power method. - size_t MaxIterations() const { return maxIterations; } - //! Modify the number of iterations for the power method. - size_t& MaxIterations() { return maxIterations; } - - //! Get the block size. - size_t BlockSize() const { return blockSize; } - //! Modify the block size. - size_t& BlockSize() { return blockSize; } - - private: - //! Locally stored number of iterations for the power method. - size_t maxIterations; - - //! Locally stored block size value. - size_t blockSize; -}; - -} // namespace pca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/randomized_svd_method.hpp b/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/randomized_svd_method.hpp deleted file mode 100644 index 148dfb9e0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/pca/decomposition_policies/randomized_svd_method.hpp +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @file randomized_svd_method.hpp - * @author Marcus Edel - * - * Implementation of the randomized svd method for use in the Principal - * Components Analysis method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_RANDOMIZED_SVD_METHOD_HPP -#define MLPACK_METHODS_PCA_DECOMPOSITION_POLICIES_RANDOMIZED_SVD_METHOD_HPP - -#include -#include - -namespace mlpack { -namespace pca { - -/** - * Implementation of the randomized SVD policy. - */ -class RandomizedSVDPolicy -{ - public: - /** - * Use randomized SVD method to perform the principal components analysis - * (PCA). - * - * @param iteratedPower Size of the normalized power iterations - * (Default: rank + 2). - * @param maxIterations Number of iterations for the power method - * (Default: 2). - */ - RandomizedSVDPolicy(const size_t iteratedPower = 0, - const size_t maxIterations = 2) : - iteratedPower(iteratedPower), - maxIterations(maxIterations) - { - /* Nothing to do here */ - } - - /** - * Apply Principal Component Analysis to the provided data set using the - * randomized SVD. - * - * @param data Data matrix. - * @param centeredData Centered data matrix. - * @param transformedData Matrix to put results of PCA into. - * @param eigVal Vector to put eigenvalues into. - * @param eigvec Matrix to put eigenvectors (loadings) into. - * @param rank Rank of the decomposition. - */ - void Apply(const arma::mat& data, - const arma::mat& centeredData, - arma::mat& transformedData, - arma::vec& eigVal, - arma::mat& eigvec, - const size_t rank) - { - // This matrix will store the right singular values; we do not need them. - arma::mat v; - - // Do singular value decomposition using the randomized SVD algorithm. - svd::RandomizedSVD rsvd(iteratedPower, maxIterations); - rsvd.Apply(data, eigvec, eigVal, v, rank); - - // Now we must square the singular values to get the eigenvalues. - // In addition we must divide by the number of points, because the - // covariance matrix is X * X' / (N - 1). - eigVal %= eigVal / (data.n_cols - 1); - - // Project the samples to the principals. - transformedData = arma::trans(eigvec) * centeredData; - } - - //! Get the size of the normalized power iterations. - size_t IteratedPower() const { return iteratedPower; } - //! Modify the size of the normalized power iterations. - size_t& IteratedPower() { return iteratedPower; } - - //! Get the number of iterations for the power method. - size_t MaxIterations() const { return maxIterations; } - //! Modify the number of iterations for the power method. - size_t& MaxIterations() { return maxIterations; } - - private: - //! Locally stored size of the normalized power iterations. - size_t iteratedPower; - - //! Locally stored number of iterations for the power method. - size_t maxIterations; -}; - -} // namespace pca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/pca/pca.hpp b/src/sdk/mlpack/include/mlpack/methods/pca/pca.hpp deleted file mode 100644 index 033001d11..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/pca/pca.hpp +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @file pca.hpp - * @author Ajinkya Kale - * @author Ryan Curtin - * @author Marcus Edel - * - * Defines the PCA class to perform Principal Components Analysis on the - * specified data set. There are many variations on how to do this, so - * template parameters allow the selection of different techniques. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_PCA_PCA_HPP -#define MLPACK_METHODS_PCA_PCA_HPP - -#include -#include - -namespace mlpack { -namespace pca { - -/** - * This class implements principal components analysis (PCA). This is a - * common, widely-used technique that is often used for either dimensionality - * reduction or transforming data into a better basis. Further information on - * PCA can be found in almost any statistics or machine learning textbook, and - * all over the internet. - */ -template -class PCA -{ - public: - /** - * Create the PCA object, specifying if the data should be scaled in each - * dimension by standard deviation when PCA is performed. - * - * @param scaleData Whether or not to scale the data. - */ - PCA(const bool scaleData = false, - const DecompositionPolicy& decomposition = DecompositionPolicy()); - - /** - * Apply Principal Component Analysis to the provided data set. It is safe - * to pass the same matrix reference for both data and transformedData. - * - * @param data Data matrix. - * @param transformedData Matrix to put results of PCA into. - * @param eigval Vector to put eigenvalues into. - * @param eigvec Matrix to put eigenvectors (loadings) into. - */ - void Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigVal, - arma::mat& eigvec); - - /** - * Apply Principal Component Analysis to the provided data set. It is safe - * to pass the same matrix reference for both data and transformedData. - * - * @param data Data matrix. - * @param transformedData Matrix to store results of PCA in. - * @param eigVal Vector to put eigenvalues into. - */ - void Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigVal); - - /** - * Use PCA for dimensionality reduction on the given dataset. This will save - * the newDimension largest principal components of the data and remove the - * rest. The parameter returned is the amount of variance of the data that - * is retained; this is a value between 0 and 1. For instance, a value of - * 0.9 indicates that 90% of the variance present in the data was retained. - * - * @param data Data matrix. - * @param newDimension New dimension of the data. - * @return Amount of the variance of the data retained (between 0 and 1). - */ - double Apply(arma::mat& data, const size_t newDimension); - - //! This overload is here to make sure int gets casted right to size_t. - inline double Apply(arma::mat& data, const int newDimension) - { - return Apply(data, size_t(newDimension)); - } - - /** - * Use PCA for dimensionality reduction on the given dataset. This will save - * as many dimensions as necessary to retain at least the given amount of - * variance (specified by parameter varRetained). The amount should be - * between 0 and 1; if the amount is 0, then only 1 dimension will be - * retained. If the amount is 1, then all dimensions will be retained. - * - * The method returns the actual amount of variance retained, which will - * always be greater than or equal to the varRetained parameter. - * - * @param data Data matrix. - * @param varRetained Lower bound on amount of variance to retain; should be - * between 0 and 1. - * @return Actual amount of variance retained (between 0 and 1). - */ - double Apply(arma::mat& data, const double varRetained); - - //! Get whether or not this PCA object will scale (by standard deviation) - //! the data when PCA is performed. - bool ScaleData() const { return scaleData; } - //! Modify whether or not this PCA object will scale (by standard deviation) - //! the data when PCA is performed. - bool& ScaleData() { return scaleData; } - - private: - //! Scaling the data is when we reduce the variance of each dimension to 1. - void ScaleData(arma::mat& centeredData) - { - if (scaleData) - { - // Scaling the data is when we reduce the variance of each dimension - // to 1. We do this by dividing each dimension by its standard - // deviation. - arma::vec stdDev = arma::stddev( - centeredData, 0, 1 /* for each dimension */); - - // If there are any zeroes, make them very small. - for (size_t i = 0; i < stdDev.n_elem; ++i) - if (stdDev[i] == 0) - stdDev[i] = 1e-50; - - centeredData /= arma::repmat(stdDev, 1, centeredData.n_cols); - } - } - - //! Whether or not the data will be scaled by standard deviation when PCA is - //! performed. - bool scaleData; - - //! Decomposition method used to perform principal components analysis. - DecompositionPolicy decomposition; -}; // class PCA - -} // namespace pca -} // namespace mlpack - -// Include implementation. -#include "pca_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/pca/pca_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/pca/pca_impl.hpp deleted file mode 100644 index 7ed056f11..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/pca/pca_impl.hpp +++ /dev/null @@ -1,179 +0,0 @@ -/** - * @file pca_impl.hpp - * @author Ajinkya Kale - * @author Ryan Curtin - * @author Marcus Edel - * - * Implementation of PCA class to perform Principal Components Analysis on the - * specified data set. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_PCA_PCA_IMPL_HPP -#define MLPACK_METHODS_PCA_PCA_IMPL_HPP - -#include -#include -#include "pca.hpp" - -using namespace std; - -namespace mlpack { -namespace pca { - -template -PCA::PCA( - const bool scaleData, const DecompositionPolicy& decomposition) : - scaleData(scaleData), - decomposition(decomposition) -{ } - -/** - * Apply Principal Component Analysis to the provided data set. - * - * @param data - Data matrix - * @param transformedData - Data with PCA applied - * @param eigVal - contains eigen values in a column vector - * @param eigvec - PCA Loadings/Coeffs/EigenVectors - */ -template -void PCA::Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigVal, - arma::mat& eigvec) -{ - Timer::Start("pca"); - - // Center the data into a temporary matrix. - arma::mat centeredData; - math::Center(data, centeredData); - - // Scale the data if the user ask for. - ScaleData(centeredData); - - decomposition.Apply(data, centeredData, transformedData, eigVal, eigvec, - data.n_rows); - - Timer::Stop("pca"); -} - -/** - * Apply Principal Component Analysis to the provided data set. - * - * @param data - Data matrix - * @param transformedData - Data with PCA applied - * @param eigVal - contains eigen values in a column vector - */ -template -void PCA::Apply(const arma::mat& data, - arma::mat& transformedData, - arma::vec& eigVal) -{ - arma::mat eigvec; - Apply(data, transformedData, eigVal, eigvec); -} - -/** - * Use PCA for dimensionality reduction on the given dataset. This will save - * the newDimension largest principal components of the data and remove the - * rest. The parameter returned is the amount of variance of the data that is - * retained; this is a value between 0 and 1. For instance, a value of 0.9 - * indicates that 90% of the variance present in the data was retained. - * - * @param data Data matrix. - * @param newDimension New dimension of the data. - * @return Amount of the variance of the data retained (between 0 and 1). - */ -template -double PCA::Apply(arma::mat& data, - const size_t newDimension) -{ - // Parameter validation. - if (newDimension == 0) - Log::Fatal << "PCA::Apply(): newDimension (" << newDimension << ") cannot " - << "be zero!" << endl; - if (newDimension > data.n_rows) - Log::Fatal << "PCA::Apply(): newDimension (" << newDimension << ") cannot " - << "be greater than the existing dimensionality of the data (" - << data.n_rows << ")!" << endl; - - arma::mat eigvec; - arma::vec eigVal; - - Timer::Start("pca"); - - // Center the data into a temporary matrix. - arma::mat centeredData; - math::Center(data, centeredData); - - // Scale the data if the user ask for. - ScaleData(centeredData); - - decomposition.Apply(data, centeredData, data, eigVal, eigvec, newDimension); - - if (newDimension < eigvec.n_rows) - // Drop unnecessary rows. - data.shed_rows(newDimension, data.n_rows - 1); - - // The svd method returns only non-zero eigenvalues so we have to calculate - // the right dimension before calculating the amount of variance retained. - double eigDim = std::min(newDimension - 1, (size_t) eigVal.n_elem - 1); - - Timer::Stop("pca"); - - // Calculate the total amount of variance retained. - return (sum(eigVal.subvec(0, eigDim)) / sum(eigVal)); -} - -/** - * Use PCA for dimensionality reduction on the given dataset. This will save - * as many dimensions as necessary to retain at least the given amount of - * variance (specified by parameter varRetained). The amount should be - * between 0 and 1; if the amount is 0, then only 1 dimension will be - * retained. If the amount is 1, then all dimensions will be retained. - * - * The method returns the actual amount of variance retained, which will - * always be greater than or equal to the varRetained parameter. - */ -template -double PCA::Apply(arma::mat& data, - const double varRetained) -{ - // Parameter validation. - if (varRetained < 0) - Log::Fatal << "PCA::Apply(): varRetained (" << varRetained << ") must be " - << "greater than or equal to 0." << endl; - if (varRetained > 1) - Log::Fatal << "PCA::Apply(): varRetained (" << varRetained << ") should be " - << "less than or equal to 1." << endl; - - arma::mat eigvec; - arma::vec eigVal; - - Apply(data, data, eigVal, eigvec); - - // Calculate the dimension we should keep. - size_t newDimension = 0; - double varSum = 0.0; - eigVal /= arma::sum(eigVal); // Normalize eigenvalues. - while ((varSum < varRetained) && (newDimension < eigVal.n_elem)) - { - varSum += eigVal[newDimension]; - ++newDimension; - } - - // varSum is the actual variance we will retain. - if (newDimension < eigVal.n_elem) - data.shed_rows(newDimension, data.n_rows - 1); - - return varSum; -} - -} // namespace pca -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/perceptron/initialization_methods/random_init.hpp b/src/sdk/mlpack/include/mlpack/methods/perceptron/initialization_methods/random_init.hpp deleted file mode 100644 index c1a2c3253..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/perceptron/initialization_methods/random_init.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @file random_init.hpp - * @author Udit Saxena - * - * Random initialization for perceptron weights. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_PERCEPTRON_INITIALIZATION_METHODS_RANDOM_INIT_HPP -#define MLPACK_METHODS_PERCEPTRON_INITIALIZATION_METHODS_RANDOM_INIT_HPP - -#include - -namespace mlpack { -namespace perceptron { - -/** - * This class is used to initialize weights for the weightVectors matrix in a - * random manner. - */ -class RandomInitialization -{ - public: - RandomInitialization() { } - - inline static void Initialize(arma::mat& weights, - arma::vec& biases, - const size_t numFeatures, - const size_t numClasses) - { - weights.randu(numFeatures, numClasses); - biases.randu(numClasses); - } -}; // class RandomInitialization - -} // namespace perceptron -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/perceptron/initialization_methods/zero_init.hpp b/src/sdk/mlpack/include/mlpack/methods/perceptron/initialization_methods/zero_init.hpp deleted file mode 100644 index 76a5fd6fb..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/perceptron/initialization_methods/zero_init.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @file zero_init.hpp - * @author Udit Saxena - * - * Implementation of ZeroInitialization policy for perceptrons. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_PERCEPTRON_INITIALIZATION_METHODS_ZERO_INIT_HPP -#define MLPACK_METHODS_PERCEPTRON_INITIALIZATION_METHODS_ZERO_INIT_HPP - -#include - -namespace mlpack { -namespace perceptron { - -/** - * This class is used to initialize the matrix weightVectors to zero. - */ -class ZeroInitialization -{ - public: - ZeroInitialization() { } - - inline static void Initialize(arma::mat& weights, - arma::vec& biases, - const size_t numFeatures, - const size_t numClasses) - { - weights.zeros(numFeatures, numClasses); - biases.zeros(numClasses); - } -}; // class ZeroInitialization - -} // namespace perceptron -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/perceptron/learning_policies/simple_weight_update.hpp b/src/sdk/mlpack/include/mlpack/methods/perceptron/learning_policies/simple_weight_update.hpp deleted file mode 100644 index 71a2a752c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/perceptron/learning_policies/simple_weight_update.hpp +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @file simple_weight_update.hpp - * @author Udit Saxena - * - * Simple weight update rule for the perceptron. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef _MLPACK_METHODS_PERCEPTRON_LEARNING_POLICIES_SIMPLE_WEIGHT_UPDATE_HPP -#define _MLPACK_METHODS_PERCEPTRON_LEARNING_POLICIES_SIMPLE_WEIGHT_UPDATE_HPP - -#include - -/** - * This class is used to update the weightVectors matrix according to the simple - * update rule as discussed by Rosenblatt: - * - * if a vector x has been incorrectly classified by a weight w, - * then w = w - x - * and w'= w'+ x - * - * where w' is the weight vector which correctly classifies x. - */ -namespace mlpack { -namespace perceptron { - -class SimpleWeightUpdate -{ - public: - /** - * This function is called to update the weightVectors matrix. It decreases - * the weights of the incorrectly classified class while increasing the weight - * of the correct class it should have been classified to. - * - * @tparam Type of vector (should be an Armadillo vector like arma::vec or - * arma::sp_vec or something similar). - * @param trainingPoint Point that was misclassified. - * @param weights Matrix of weights. - * @param biases Vector of biases. - * @param incorrectClass Index of class that the point was incorrectly - * classified as. - * @param correctClass Index of the true class of the point. - * @param instanceWeight Weight to be given to this particular point during - * training (this is useful for boosting). - */ - template - void UpdateWeights(const VecType& trainingPoint, - arma::mat& weights, - arma::vec& biases, - const size_t incorrectClass, - const size_t correctClass, - const double instanceWeight = 1.0) - { - weights.col(incorrectClass) -= instanceWeight * trainingPoint; - biases(incorrectClass) -= instanceWeight; - - weights.col(correctClass) += instanceWeight * trainingPoint; - biases(correctClass) += instanceWeight; - } -}; - -} // namespace perceptron -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/perceptron/perceptron.hpp b/src/sdk/mlpack/include/mlpack/methods/perceptron/perceptron.hpp deleted file mode 100644 index b852179bc..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/perceptron/perceptron.hpp +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @file perceptron.hpp - * @author Udit Saxena - * - * Definition of Perceptron class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_PERCEPTRON_PERCEPTRON_HPP -#define MLPACK_METHODS_PERCEPTRON_PERCEPTRON_HPP - -#include - -#include "initialization_methods/zero_init.hpp" -#include "initialization_methods/random_init.hpp" -#include "learning_policies/simple_weight_update.hpp" - -namespace mlpack { -namespace perceptron { - -/** - * This class implements a simple perceptron (i.e., a single layer neural - * network). It converges if the supplied training dataset is linearly - * separable. - * - * @tparam LearnPolicy Options of SimpleWeightUpdate and GradientDescent. - * @tparam WeightInitializationPolicy Option of ZeroInitialization and - * RandomInitialization. - */ -template -class Perceptron -{ - public: - /** - * Constructor: create the perceptron with the given number of classes and - * initialize the weight matrix, but do not perform any training. (Call the - * Train() function to perform training.) - * - * @param numClasses Number of classes in the dataset. - * @param dimensionality Dimensionality of the dataset. - * @param maxIterations Maximum number of iterations for the perceptron - * learning algorithm. - */ - Perceptron(const size_t numClasses = 0, - const size_t dimensionality = 0, - const size_t maxIterations = 1000); - - /** - * Constructor: constructs the perceptron by building the weights matrix, - * which is later used in classification. The number of classes should be - * specified separately, and the labels vector should contain values in the - * range [0, numClasses - 1]. The data::NormalizeLabels() function can be - * used if the labels vector does not contain values in the required range. - * - * @param data Input, training data. - * @param labels Labels of dataset. - * @param numClasses Number of classes in the dataset. - * @param maxIterations Maximum number of iterations for the perceptron - * learning algorithm. - */ - Perceptron(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const size_t maxIterations = 1000); - - /** - * Alternate constructor which copies parameters from an already initiated - * perceptron. - * - * @param other The other initiated Perceptron object from which we copy the - * values from. - * @param data The data on which to train this Perceptron object on. - * @param labels The labels of data. - * @param numClasses Number of classes in the data. - * @param instanceWeights Weight vector to use while training. For boosting - * purposes. - */ - Perceptron(const Perceptron& other, - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& instanceWeights); - - /** - * Train the perceptron on the given data for up to the maximum number of - * iterations (specified in the constructor or through MaxIterations()). A - * single iteration corresponds to a single pass through the data, so if you - * want to pass through the dataset only once, set MaxIterations() to 1. - * - * This training does not reset the model weights, so you can call Train() on - * multiple datasets sequentially. - * - * @param data Dataset on which training should be performed. - * @param labels Labels of the dataset. - * @param numClasses Number of classes in the data. - * @param instanceWeights Cost matrix. Stores the cost of mispredicting - * instances. This is useful for boosting. - */ - void Train(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& instanceWeights = arma::rowvec()); - - /** - * Classification function. After training, use the weights matrix to - * classify test, and put the predicted classes in predictedLabels. - * - * @param test Testing data or data to classify. - * @param predictedLabels Vector to store the predicted classes after - * classifying test. - */ - void Classify(const MatType& test, arma::Row& predictedLabels); - - /** - * Serialize the perceptron. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - //! Get the number of classes this perceptron has been trained for. - size_t NumClasses() const { return weights.n_cols; } - - //! Get the weight matrix. - const arma::mat& Weights() const { return weights; } - //! Modify the weight matrix. You had better know what you are doing! - arma::mat& Weights() { return weights; } - - //! Get the biases. - const arma::vec& Biases() const { return biases; } - //! Modify the biases. You had better know what you are doing! - arma::vec& Biases() { return biases; } - - private: - //! The maximum number of iterations during training. - size_t maxIterations; - - /** - * Stores the weights for each of the input class labels. Each column - * corresponds to the weights for one class label, and each row corresponds to - * the weights for one dimension of the input data. The biases are held in a - * separate vector. - */ - arma::mat weights; - - //! The biases for each class. - arma::vec biases; -}; - -} // namespace perceptron -} // namespace mlpack - -#include "perceptron_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/perceptron/perceptron_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/perceptron/perceptron_impl.hpp deleted file mode 100644 index 6e15b53e8..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/perceptron/perceptron_impl.hpp +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @file perceptron_impl.hpp - * @author Udit Saxena - * - * Implementation of Perceptron class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_PERCEPTRON_PERCEPTRON_IMPL_HPP -#define MLPACK_METHODS_PERCEPTRON_PERCEPTRON_IMPL_HPP - -#include "perceptron.hpp" - -namespace mlpack { -namespace perceptron { - -/** - * Construct the perceptron with the given number of classes and maximum number - * of iterations. - */ -template< - typename LearnPolicy, - typename WeightInitializationPolicy, - typename MatType -> -Perceptron::Perceptron( - const size_t numClasses, - const size_t dimensionality, - const size_t maxIterations) : - maxIterations(maxIterations) -{ - WeightInitializationPolicy wip; - wip.Initialize(weights, biases, dimensionality, numClasses); -} - -/** - * Constructor - constructs the perceptron. Or rather, builds the weights - * matrix, which is later used in classification. It adds a bias input vector - * of 1 to the input data to take care of the bias weights. - * - * @param data Input, training data. - * @param labels Labels of dataset. - * @param maxIterations Maximum number of iterations for the perceptron learning - * algorithm. - */ -template< - typename LearnPolicy, - typename WeightInitializationPolicy, - typename MatType -> -Perceptron::Perceptron( - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const size_t maxIterations) : - maxIterations(maxIterations) -{ - // Start training. - Train(data, labels, numClasses); -} - -/** - * Alternate constructor which copies parameters from an already initiated - * perceptron. - * - * @param other The other initiated Perceptron object from which we copy the - * values from. - * @param data The data on which to train this Perceptron object on. - * @param instanceWeights Weight vector to use while training. For boosting - * purposes. - * @param labels The labels of data. - */ -template< - typename LearnPolicy, - typename WeightInitializationPolicy, - typename MatType -> -Perceptron::Perceptron( - const Perceptron& other, - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& instanceWeights) : - maxIterations(other.maxIterations) -{ - Train(data, labels, numClasses, instanceWeights); -} - -/** - * Classification function. After training, use the weights matrix to classify - * test, and put the predicted classes in predictedLabels. - * - * @param test Testing data or data to classify. - * @param predictedLabels Vector to store the predicted classes after - * classifying test. - */ -template< - typename LearnPolicy, - typename WeightInitializationPolicy, - typename MatType -> -void Perceptron::Classify( - const MatType& test, - arma::Row& predictedLabels) -{ - arma::vec tempLabelMat; - arma::uword maxIndex = 0; - - // Could probably be faster if done in batch. - for (size_t i = 0; i < test.n_cols; i++) - { - tempLabelMat = weights.t() * test.col(i) + biases; - tempLabelMat.max(maxIndex); - predictedLabels(0, i) = maxIndex; - } -} - -/** - * Training function. It trains on trainData using the cost matrix - * instanceWeights. - * - * @param data Data to train on. - * @param labels Labels of data. - * @param instanceWeights Cost matrix. Stores the cost of mispredicting - * instances. This is useful for boosting. - */ -template< - typename LearnPolicy, - typename WeightInitializationPolicy, - typename MatType -> -void Perceptron::Train( - const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& instanceWeights) -{ - // Do we need to resize the weights? - if (weights.n_elem != numClasses) - { - WeightInitializationPolicy wip; - wip.Initialize(weights, biases, data.n_rows, numClasses); - } - - size_t j, i = 0; - bool converged = false; - size_t tempLabel; - arma::uword maxIndexRow = 0, maxIndexCol = 0; - arma::mat tempLabelMat; - - LearnPolicy LP; - - const bool hasWeights = (instanceWeights.n_elem > 0); - - while ((i < maxIterations) && (!converged)) - { - // This outer loop is for each iteration, and we use the 'converged' - // variable for noting whether or not convergence has been reached. - i++; - converged = true; - - // Now this inner loop is for going through the dataset in each iteration. - for (j = 0; j < data.n_cols; j++) - { - // Multiply for each variable and check whether the current weight vector - // correctly classifies this. - tempLabelMat = weights.t() * data.col(j) + biases; - - tempLabelMat.max(maxIndexRow, maxIndexCol); - - // Check whether prediction is correct. - if (maxIndexRow != labels(0, j)) - { - // Due to incorrect prediction, convergence set to false. - converged = false; - tempLabel = labels(0, j); - - // Send maxIndexRow for knowing which weight to update, send j to know - // the value of the vector to update it with. Send tempLabel to know - // the correct class. - if (hasWeights) - LP.UpdateWeights(data.col(j), weights, biases, maxIndexRow, tempLabel, - instanceWeights(j)); - else - LP.UpdateWeights(data.col(j), weights, biases, maxIndexRow, - tempLabel); - } - } - } -} - -//! Serialize the perceptron. -template -template -void Perceptron::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // We just need to serialize the maximum number of iterations, the weights, - // and the biases. - ar & BOOST_SERIALIZATION_NVP(maxIterations); - ar & BOOST_SERIALIZATION_NVP(weights); - ar & BOOST_SERIALIZATION_NVP(biases); -} - -} // namespace perceptron -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/quic_svd/quic_svd.hpp b/src/sdk/mlpack/include/mlpack/methods/quic_svd/quic_svd.hpp deleted file mode 100644 index a2b0a200c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/quic_svd/quic_svd.hpp +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @file quic_svd.hpp - * @author Siddharth Agrawal - * - * An implementation of QUIC-SVD. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_QUIC_SVD_QUIC_SVD_HPP -#define MLPACK_METHODS_QUIC_SVD_QUIC_SVD_HPP - -#include -#include - -namespace mlpack { -namespace svd { - -/** - * QUIC-SVD is a matrix factorization technique, which operates in a subspace - * such that A's approximation in that subspace has minimum error(A being the - * data matrix). The subspace is constructed using a cosine tree, which ensures - * minimum representative rank(and thus a fast running time). It follows a - * splitting policy based on Length-squared(LS) sampling and constructs the - * child nodes based on the absolute cosines of the remaining points relative to - * the pivot. The centroids of the points in the child nodes are added to the - * subspace span in each step. Each node is then placed into a queue prioritized - * by its residual error. The subspace approximation error of A after each step - * is calculated using a Monte Carlo estimate. If the error is below a certain - * threshold, the method proceeds to calculate the Singular Value Decomposition - * in the obtained subspace. Otherwise, the same procedure is repeated until we - * obtain a subspace of sufficiently low error. Technical details can be found - * in the following paper: - * - * http://www.cc.gatech.edu/~isbell/papers/isbell-quicsvd-nips-2008.pdf - * - * An example of how to use the interface is shown below: - * - * @code - * arma::mat data; // Data matrix. - * - * const double epsilon = 0.01; // Relative error limit of data in subspace. - * const double delta = 0.1 // Lower error bound for Monte Carlo estimate. - * - * arma::mat u, v, sigma; // Matrices for the factors. data = u * sigma * v.t() - * - * // Get the factorization in the constructor. - * QUIC_SVD(data, u, v, sigma, epsilon, delta); - * @endcode - */ -class QUIC_SVD -{ - public: - /** - * Constructor which implements the QUIC-SVD algorithm. The function calls the - * CosineTree constructor to create a subspace basis, where the original - * matrix's projection has minimum reconstruction error. The constructor then - * uses the ExtractSVD() function to calculate the SVD of the original dataset - * in that subspace. - * - * @param dataset Matrix for which SVD is calculated. - * @param u First unitary matrix. - * @param v Second unitary matrix. - * @param sigma Diagonal matrix of singular values. - * @param epsilon Error tolerance fraction for calculated subspace. - * @param delta Cumulative probability for Monte Carlo error lower bound. - */ - QUIC_SVD(const arma::mat& dataset, - arma::mat& u, - arma::mat& v, - arma::mat& sigma, - const double epsilon = 0.03, - const double delta = 0.1); - - /** - * This function uses the vector subspace created using a cosine tree to - * calculate an approximate SVD of the original matrix. - * - * @param u First unitary matrix. - * @param v Second unitary matrix. - * @param sigma Diagonal matrix of singular values. - */ - void ExtractSVD(arma::mat& u, arma::mat& v, arma::mat& sigma); - - private: - //! Matrix for which cosine tree is constructed. - const arma::mat& dataset; - //! Subspace basis of the input dataset. - arma::mat basis; -}; - -} // namespace svd -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/radical/radical.hpp b/src/sdk/mlpack/include/mlpack/methods/radical/radical.hpp deleted file mode 100644 index cf9f6c1a5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/radical/radical.hpp +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @file radical.hpp - * @author Nishant Mehta - * - * Declaration of Radical class (RADICAL is Robust, Accurate, Direct ICA - * aLgorithm). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_RADICAL_RADICAL_HPP -#define MLPACK_METHODS_RADICAL_RADICAL_HPP - -#include - -namespace mlpack { -namespace radical { - -/** - * An implementation of RADICAL, an algorithm for independent component - * analysis (ICA). - * - * Let X be a matrix where each column is a point and each row a dimension. - * The goal is to find a square unmixing matrix W such that Y = W X and - * the rows of Y are independent components. - * - * For more details, see the following paper: - * - * @code - * @article{learned2003ica, - * title = {ICA Using Spacings Estimates of Entropy}, - * author = {Learned-Miller, E.G. and Fisher III, J.W.}, - * journal = {Journal of Machine Learning Research}, - * volume = {4}, - * pages = {1271--1295}, - * year = {2003} - * } - * @endcode - */ -class Radical -{ - public: - /** - * Set the parameters to RADICAL. - * - * @param noiseStdDev Standard deviation of the Gaussian noise added to the - * replicates of the data points during Radical2D - * @param replicates Number of Gaussian-perturbed replicates to use (per - * point) in Radical2D - * @param angles Number of angles to consider in brute-force search during - * Radical2D - * @param sweeps Number of sweeps. Each sweep calls Radical2D once for each - * pair of dimensions - * @param m The variable m from Vasicek's m-spacing estimator of entropy. - */ - Radical(const double noiseStdDev = 0.175, - const size_t replicates = 30, - const size_t angles = 150, - const size_t sweeps = 0, - const size_t m = 0); - - /** - * Run RADICAL. - * - * @param matX Input data into the algorithm - a matrix where each column is - * a point and each row is a dimension. - * @param matY Estimated independent components - a matrix where each column - * is a point and each row is an estimated independent component. - * @param matW Estimated unmixing matrix, where matY = matW * matX. - */ - void DoRadical(const arma::mat& matX, arma::mat& matY, arma::mat& matW); - - /** - * Vasicek's m-spacing estimator of entropy, with overlap modification from - * (Learned-Miller and Fisher, 2003). - * - * @param x Empirical sample (one-dimensional) over which to estimate entropy. - */ - double Vasicek(arma::vec& x) const; - - /** - * Make replicates of each data point (the number of replicates is set in - * either the constructor or with Replicates()) and perturb data with Gaussian - * noise with standard deviation noiseStdDev. - */ - void CopyAndPerturb(arma::mat& xNew, const arma::mat& x) const; - - //! Two-dimensional version of RADICAL. - double DoRadical2D(const arma::mat& matX); - - //! Get the standard deviation of the additive Gaussian noise. - double NoiseStdDev() const { return noiseStdDev; } - //! Modify the standard deviation of the additive Gaussian noise. - double& NoiseStdDev() { return noiseStdDev; } - - //! Get the number of Gaussian-perturbed replicates used per point. - size_t Replicates() const { return replicates; } - //! Modify the number of Gaussian-perturbed replicates used per point. - size_t& Replicates() { return replicates; } - - //! Get the number of angles considered during brute-force search. - size_t Angles() const { return angles; } - //! Modify the number of angles considered during brute-force search. - size_t& Angles() { return angles; } - - //! Get the number of sweeps. - size_t Sweeps() const { return sweeps; } - //! Modify the number of sweeps. - size_t& Sweeps() { return sweeps; } - - private: - //! Standard deviation of the Gaussian noise added to the replicates of - //! the data points during Radical2D. - double noiseStdDev; - - //! Number of Gaussian-perturbed replicates to use (per point) in Radical2D. - size_t replicates; - - //! Number of angles to consider in brute-force search during Radical2D. - size_t angles; - - //! Number of sweeps; each sweep calls Radical2D once for each pair of - //! dimensions. - size_t sweeps; - - //! Value of m to use for Vasicek's m-spacing estimator of entropy. - size_t m; - - //! Internal matrix, held as member variable to prevent memory reallocations. - arma::mat perturbed; - //! Internal matrix, held as member variable to prevent memory reallocations. - arma::mat candidate; -}; - -void WhitenFeatureMajorMatrix(const arma::mat& matX, - arma::mat& matXWhitened, - arma::mat& matWhitening); - -} // namespace radical -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/random_forest/bootstrap.hpp b/src/sdk/mlpack/include/mlpack/methods/random_forest/bootstrap.hpp deleted file mode 100644 index 25e076084..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/random_forest/bootstrap.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file bootstrap.hpp - * @author Ryan Curtin - * - * Implementation of the Bootstrap() function, which creates a bootstrapped - * dataset from the given input dataset. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANDOM_FOREST_BOOTSTRAP_HPP -#define MLPACK_METHODS_RANDOM_FOREST_BOOTSTRAP_HPP - -namespace mlpack { -namespace tree { - -/** - * Given a dataset, create another dataset via bootstrap sampling, with labels. - */ -template -void Bootstrap(const MatType& dataset, - const LabelsType& labels, - const WeightsType& weights, - MatType& bootstrapDataset, - LabelsType& bootstrapLabels, - WeightsType& bootstrapWeights) -{ - bootstrapDataset.set_size(dataset.n_rows, dataset.n_cols); - bootstrapLabels.set_size(labels.n_elem); - if (UseWeights) - bootstrapWeights.set_size(weights.n_elem); - - // Random sampling with replacement. - arma::uvec indices = arma::randi(dataset.n_cols, - arma::distr_param(0, dataset.n_cols - 1)); - for (size_t i = 0; i < dataset.n_cols; ++i) - { - bootstrapDataset.col(i) = dataset.col(indices[i]); - bootstrapLabels[i] = labels[indices[i]]; - if (UseWeights) - bootstrapWeights[i] = weights[indices[i]]; - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/random_forest/random_forest.hpp b/src/sdk/mlpack/include/mlpack/methods/random_forest/random_forest.hpp deleted file mode 100644 index 74d9349c1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/random_forest/random_forest.hpp +++ /dev/null @@ -1,302 +0,0 @@ -/** - * @file random_forest.hpp - * @author Ryan Curtin - * - * Definition of the RandomForest class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANDOM_FOREST_RANDOM_FOREST_HPP -#define MLPACK_METHODS_RANDOM_FOREST_RANDOM_FOREST_HPP - -#include -#include -#include "bootstrap.hpp" - -namespace mlpack { -namespace tree { - -template, - template class NumericSplitType = BestBinaryNumericSplit, - template class CategoricalSplitType = AllCategoricalSplit, - typename ElemType = double> -class RandomForest -{ - public: - //! Allow access to the underlying decision tree type. - typedef DecisionTree DecisionTreeType; - - /** - * Construct the random forest without any training or specifying the number - * of trees. Predict() will throw an exception until Train() is called. - */ - RandomForest() { } - - /** - * Create a random forest, training on the given labeled training data with - * the given number of trees. The minimumLeafSize parameter is given to each - * individual decision tree during tree building. - * - * @param dataset Dataset to train on. - * @param labels Labels for dataset. - * @param numClasses Number of classes in dataset. - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each tree's leaf nodes. - */ - template - RandomForest(const MatType& dataset, - const arma::Row& labels, - const size_t numClasses, - const size_t numTrees = 50, - const size_t minimumLeafSize = 20); - - /** - * Create a random forest, training on the given labeled training data with - * the given dataset info and the given number of trees. The minimumLeafSize - * parameter is given to each individual decision tree during tree building. - * This constructor can be used to train on categorical data. - * - * @param dataset Dataset to train on. - * @param datasetInfo Dimension info for the dataset. - * @param labels Labels for dataset. - * @param numClasses Number of classes in dataset. - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each tree's leaf nodes. - */ - template - RandomForest(const MatType& dataset, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const size_t numTrees = 50, - const size_t minimumLeafSize = 20); - - /** - * Create a random forest, training on the given weighted labeled training - * data with the given number of trees. The minimumLeafSize parameter is - * given to each individual decision tree during tree building. - * - * @param dataset Dataset to train on. - * @param labels Labels for dataset. - * @param numClasses Number of classes in dataset. - * @param weights Weights (importances) of each point in the dataset. - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each tree's leaf nodes. - */ - template - RandomForest(const MatType& dataset, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees = 50, - const size_t minimumLeafSize = 20); - - /** - * Create a random forest, training on the given weighted labeled training - * data with the given dataset info and the given number of trees. The - * minimumLeafSize parameter is given to each individual decision tree during - * tree building. This can be used for categorical weighted training. - * - * @param dataset Dataset to train on. - * @param datasetInfo Dimension info for the dataset. - * @param labels Labels for dataset. - * @param numClasses Number of classes in dataset. - * @param weights Weights (importances) of each point in the dataset. - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each tree's leaf nodes. - */ - template - RandomForest(const MatType& dataset, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees = 50, - const size_t minimumLeafSize = 20); - - /** - * Train the random forest on the given labeled training data with the given - * number of trees. The minimumLeafSize parameter is given to each individual - * decision tree during tree building. - * - * @param data Dataset to train on. - * @param labels Labels for dataset. - * @param numClasses Number of classes in dataset. - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each tree's leaf nodes. - */ - template - void Train(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const size_t numTrees = 50, - const size_t minimumLeafSize = 20); - - /** - * Train the random forest on the given labeled training data with the given - * dataset info and the given number of trees. The minimumLeafSize parameter - * is given to each individual decision tree during tree building. This - * overload can be used to train on categorical data. - * - * @param data Dataset to train on. - * @param datasetInfo Dimension info for the dataset. - * @param labels Labels for dataset. - * @param numClasses Number of classes in dataset. - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each tree's leaf nodes. - */ - template - void Train(const MatType& data, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const size_t numTrees = 50, - const size_t minimumLeafSize = 20); - - /** - * Train the random forest on the given weighted labeled training data with - * the given number of trees. The minimumLeafSize parameter is given to each - * individual decision tree during tree building. - * - * @param data Dataset to train on. - * @param labels Labels for dataset. - * @param numClasses Number of classes in dataset. - * @param weights Weights (importances) of each point in the dataset. - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each tree's leaf nodes. - */ - template - void Train(const MatType& data, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees = 50, - const size_t minimumLeafSize = 20); - - /** - * Train the random forest on the given weighted labeled training data with - * the given dataset info and the given number of trees. The minimumLeafSize - * parameter is given to each individual decision tree during tree building. - * This overload can be used for categorical weighted training. - * - * @param data Dataset to train on. - * @param datasetInfo Dimension info for the dataset. - * @param labels Labels for dataset. - * @param numClasses Number of classes in dataset. - * @param weights Weights (importances) of each point in the dataset. - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each tree's leaf nodes. - */ - template - void Train(const MatType& data, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees = 50, - const size_t minimumLeafSize = 20); - - /** - * Predict the class of the given point. If the random forest has not been - * trained, this will throw an exception. - * - * @param point Point to be classified. - */ - template - size_t Classify(const VecType& point) const; - - /** - * Predict the class of the given point and return the predicted class - * probabilities for each class. If the random forest has not been trained, - * this will throw an exception. - * - * @param point Point to be classified. - * @param prediction size_t to store predicted class in. - * @param probabilities Output vector of class probabilities. - */ - template - void Classify(const VecType& point, - size_t& prediction, - arma::vec& probabilities) const; - - /** - * Predict the classes of each point in the given dataset. If the random - * forest has not been trained, this will throw an exception. - * - * @param data Dataset to be classified. - * @param predictions Output predictions for each point in the dataset. - */ - template - void Classify(const MatType& data, - arma::Row& predictions) const; - - /** - * Predict the classes of each point in the given dataset, also returning the - * predicted class probabilities for each point. If the random forest has not - * been trained, this will throw an exception. - * - * @param data Dataset to be classified. - * @param predictions Output predictions for each point in the dataset. - * @param probabilities Output matrix of class probabilities for each point. - */ - template - void Classify(const MatType& data, - arma::Row& predictions, - arma::mat& probabilities) const; - - //! Access a tree in the forest. - const DecisionTreeType& Tree(const size_t i) const { return trees[i]; } - //! Modify a tree in the forest (be careful!). - DecisionTreeType& Tree(const size_t i) { return trees[i]; } - - //! Get the number of trees in the forest. - size_t NumTrees() const { return trees.size(); } - - /** - * Serialize the random forest. - */ - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - /** - * Perform the training of the decision tree. The template bool parameters - * control whether or not the datasetInfo or weights arguments should be - * ignored. - * - * @param data Dataset to train on. - * @param datasetInfo Dimension information for the dataset (may be ignored). - * @param labels Labels for the dataset. - * @param numClasses Number of classes in the dataset. - * @param weights Weights for each point in the dataset (may be ignored). - * @param numTrees Number of trees in the forest. - * @param minimumLeafSize Minimum number of points in each leaf node. - * @tparam UseWeights Whether or not to use the weights parameter. - * @tparam UseDatasetInfo Whether or not to use the datasetInfo parameter. - * @tparam MatType The type of data matrix (i.e. arma::mat). - */ - template - void Train(const MatType& data, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees, - const size_t minimumLeafSize); - - //! The trees in the forest. - std::vector trees; -}; - -} // namespace tree -} // namespace mlpack - -// Include implementation. -#include "random_forest_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/random_forest/random_forest_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/random_forest/random_forest_impl.hpp deleted file mode 100644 index e85511681..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/random_forest/random_forest_impl.hpp +++ /dev/null @@ -1,475 +0,0 @@ -/** - * @file random_forest_impl.hpp - * @author Ryan Curtin - * - * Implementation of random forest. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANDOM_FOREST_RANDOM_FOREST_IMPL_HPP -#define MLPACK_METHODS_RANDOM_FOREST_RANDOM_FOREST_IMPL_HPP - -// In case it hasn't been included yet. -#include "random_forest.hpp" - -namespace mlpack { -namespace tree { - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::RandomForest(const MatType& dataset, - const arma::Row& labels, - const size_t numClasses, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Pass off work to the Train() method. - data::DatasetInfo info; // Ignored. - arma::rowvec weights; // Fake weights, not used. - Train(dataset, info, labels, numClasses, weights, numTrees, - minimumLeafSize); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::RandomForest(const MatType& dataset, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Pass off work to the Train() method. - arma::rowvec weights; // Fake weights, not used. - Train(dataset, datasetInfo, labels, numClasses, weights, - numTrees, minimumLeafSize); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::RandomForest(const MatType& dataset, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Pass off work to the Train() method. - data::DatasetInfo info; // Ignored by Train(). - Train(dataset, info, labels, numClasses, weights, numTrees, - minimumLeafSize); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::RandomForest(const MatType& dataset, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Pass off work to the Train() method. - Train(dataset, datasetInfo, labels, numClasses, weights, numTrees, - minimumLeafSize); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Train(const MatType& dataset, - const arma::Row& labels, - const size_t numClasses, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Pass off to Train(). - data::DatasetInfo info; // Ignored by Train(). - arma::rowvec weights; // Ignored by Train(). - Train(dataset, info, labels, numClasses, weights, numTrees, - minimumLeafSize); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Train(const MatType& dataset, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Pass off to Train(). - arma::rowvec weights; // Ignored by Train(). - Train(dataset, datasetInfo, labels, numClasses, weights, - numTrees, minimumLeafSize); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Train(const MatType& dataset, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Pass off to Train(). - data::DatasetInfo info; // Ignored by Train(). - Train(dataset, info, labels, numClasses, weights, numTrees, - minimumLeafSize); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Train(const MatType& dataset, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Pass off to Train(). - Train(dataset, datasetInfo, labels, numClasses, weights, numTrees, - minimumLeafSize); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -size_t RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Classify(const VecType& point) const -{ - // Pass off to another Classify() overload. - size_t predictedClass; - arma::vec probabilities; - Classify(point, predictedClass, probabilities); - - return predictedClass; -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Classify(const VecType& point, - size_t& prediction, - arma::vec& probabilities) const -{ - // Check edge case. - if (trees.size() == 0) - { - probabilities.clear(); - prediction = 0; - - throw std::invalid_argument("RandomForest::Classify(): no random forest " - "trained!"); - } - - probabilities.zeros(trees[0].NumClasses()); - for (size_t i = 0; i < trees.size(); ++i) - { - arma::vec treeProbs; - size_t treePrediction; // Ignored. - trees[i].Classify(point, treePrediction, treeProbs); - - probabilities += treeProbs; - } - - // Find maximum element after renormalizing probabilities. - probabilities /= trees.size(); - arma::uword maxIndex = 0; - probabilities.max(maxIndex); - - // Set prediction. - prediction = (size_t) maxIndex; -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Classify(const MatType& data, - arma::Row& predictions) const -{ - // Check edge case. - if (trees.size() == 0) - { - predictions.clear(); - - throw std::invalid_argument("RandomForest::Classify(): no random forest " - "trained!"); - } - - predictions.set_size(data.n_cols); - - #pragma omp parallel for - for (omp_size_t i = 0; i < data.n_cols; ++i) - predictions[i] = Classify(data.col(i)); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Classify(const MatType& data, - arma::Row& predictions, - arma::mat& probabilities) const -{ - // Check edge case. - if (trees.size() == 0) - { - predictions.clear(); - probabilities.clear(); - - throw std::invalid_argument("RandomForest::Classify(): no random forest " - "trained!"); - } - - probabilities.set_size(trees[0].NumClasses(), data.n_cols); - predictions.set_size(data.n_cols); - #pragma omp parallel for - for (omp_size_t i = 0; i < data.n_cols; ++i) - { - arma::vec probs = probabilities.unsafe_col(i); - Classify(data.col(i), predictions[i], probs); - } -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::serialize(Archive& ar, const unsigned int /* version */) -{ - size_t numTrees; - if (Archive::is_loading::value) - trees.clear(); - else - numTrees = trees.size(); - - ar & BOOST_SERIALIZATION_NVP(numTrees); - - // Allocate space if needed. - if (Archive::is_loading::value) - trees.resize(numTrees); - - ar & BOOST_SERIALIZATION_NVP(trees); -} - -template< - typename FitnessFunction, - typename DimensionSelectionType, - template class NumericSplitType, - template class CategoricalSplitType, - typename ElemType -> -template -void RandomForest< - FitnessFunction, - DimensionSelectionType, - NumericSplitType, - CategoricalSplitType, - ElemType ->::Train(const MatType& dataset, - const data::DatasetInfo& datasetInfo, - const arma::Row& labels, - const size_t numClasses, - const arma::rowvec& weights, - const size_t numTrees, - const size_t minimumLeafSize) -{ - // Train each tree individually. - trees.resize(numTrees); // This will fill the vector with untrained trees. - - #pragma omp parallel for - for (omp_size_t i = 0; i < numTrees; ++i) - { - MatType bootstrapDataset; - arma::Row bootstrapLabels; - arma::rowvec bootstrapWeights; - Bootstrap(dataset, labels, weights, bootstrapDataset, - bootstrapLabels, bootstrapWeights); - - // Now build the decision tree. - if (UseWeights) - { - if (UseDatasetInfo) - { - trees[i].Train(dataset, datasetInfo, labels, numClasses, weights, - minimumLeafSize); - } - else - { - trees[i].Train(dataset, labels, numClasses, weights, minimumLeafSize); - } - } - else - { - if (UseDatasetInfo) - { - trees[i].Train(dataset, datasetInfo, labels, numClasses, - minimumLeafSize); - } - else - { - trees[i].Train(dataset, labels, numClasses, minimumLeafSize); - } - } - } -} - -} // namespace tree -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/randomized_svd/randomized_svd.hpp b/src/sdk/mlpack/include/mlpack/methods/randomized_svd/randomized_svd.hpp deleted file mode 100644 index ce53e887b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/randomized_svd/randomized_svd.hpp +++ /dev/null @@ -1,264 +0,0 @@ -/** - * @file randomized_svd.hpp - * @author Marcus Edel - * - * An implementation of the randomized SVD method. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_RANDOMIZED_SVD_RANDOMIZED_SVD_HPP -#define MLPACK_METHODS_RANDOMIZED_SVD_RANDOMIZED_SVD_HPP - -#include -#include - -namespace mlpack { -namespace svd { - -/** - * Randomized SVD is a matrix factorization that is based on randomized matrix - * approximation techniques, developed in in "Finding structure with randomness: - * Probabilistic algorithms for constructing approximate matrix decompositions". - * - * For more information, see the following. - * - * @code - * @article{Halko2011, - * author = {Halko, N. and Martinsson, P. G. and Tropp, J. A.}, - * title = {Finding Structure with Randomness: Probabilistic Algorithms for - Constructing Approximate Matrix Decompositions}, - * journal = {SIAM Rev.}, - * volume = {53}, - * year = {2011}, - * } - * @endcode - * - * @code - * @article{Szlam2014, - * author = {Arthur Szlam Yuval Kluger and Mark Tygert}, - * title = {An implementation of a randomized algorithm for principal - component analysis}, - * journal = {CoRR}, - * volume = {abs/1412.3510}, - * year = {2014}, - * } - * @endcode - * - * An example of how to use the interface is shown below: - * - * @code - * arma::mat data; // Rating data in the form of coordinate list. - * - * const size_t rank = 20; // Rank used for the decomposition. - * - * // Make a RandomizedSVD object. - * RandomizedSVD rSVD(); - * - * arma::mat u, s, v; - * - * // Use the Apply() method to get a factorization. - * rSVD.Apply(data, u, s, v, rank); - * @endcode - */ -class RandomizedSVD -{ - public: - /** - * Create object for the randomized SVD method. - * - * @param data Data matrix. - * @param u First unitary matrix. - * @param v Second unitary matrix. - * @param sigma Diagonal matrix of singular values. - * @param iteratedPower Size of the normalized power iterations - * (Default: rank + 2). - * @param maxIterations Number of iterations for the power method - * (Default: 2). - * @param rank Rank of the approximation (Default: number of rows.) - * @param eps The eps coefficient to avoid division by zero (numerical - * stability). - */ - RandomizedSVD(const arma::mat& data, - arma::mat& u, - arma::vec& s, - arma::mat& v, - const size_t iteratedPower = 0, - const size_t maxIterations = 2, - const size_t rank = 0, - const double eps = 1e-7); - - /** - * Create object for the randomized SVD method. - * - * @param iteratedPower Size of the normalized power iterations - * (Default: rank + 2). - * @param maxIterations Number of iterations for the power method - * (Default: 2). - * @param eps The eps coefficient to avoid division by zero (numerical - * stability). - */ - RandomizedSVD(const size_t iteratedPower = 0, - const size_t maxIterations = 2, - const double eps = 1e-7); - -/** - * Center the data to apply Principal Component Analysis on given sparse - * matrix dataset using randomized SVD. - * - * @param data Sparse data matrix. - * @param u First unitary matrix. - * @param v Second unitary matrix. - * @param sigma Diagonal matrix of singular values. - * @param rank Rank of the approximation. - */ - void Apply(const arma::sp_mat& data, - arma::mat& u, - arma::vec& s, - arma::mat& v, - const size_t rank); - -/** - * Center the data to apply Principal Component Analysis on given matrix - * dataset using randomized SVD. - * - * @param data Data matrix. - * @param u First unitary matrix. - * @param v Second unitary matrix. - * @param sigma Diagonal matrix of singular values. - * @param rank Rank of the approximation. - */ - void Apply(const arma::mat& data, - arma::mat& u, - arma::vec& s, - arma::mat& v, - const size_t rank); - - /** - * Apply Principal Component Analysis to the provided matrix data set - * using the randomized SVD. - * - * @param data Data matrix. - * @param u First unitary matrix. - * @param v Second unitary matrix. - * @param sigma Diagonal matrix of singular values. - * @param rank Rank of the approximation. - * @param rowMean Centered mean value matrix. - */ - template - void Apply(const MatType& data, - arma::mat& u, - arma::vec& s, - arma::mat& v, - const size_t rank, - MatType rowMean) - { - if (iteratedPower == 0) - iteratedPower = rank + 2; - - arma::mat R, Q, Qdata; - - // Apply the centered data matrix to a random matrix, obtaining Q. - if (data.n_cols >= data.n_rows) - { - R = arma::randn(data.n_rows, iteratedPower); - Q = (data.t() * R) - arma::repmat(arma::trans(R.t() * rowMean), - data.n_cols, 1); - } - else - { - R = arma::randn(data.n_cols, iteratedPower); - Q = (data * R) - (rowMean * (arma::ones(1, data.n_cols) * R)); - } - - // Form a matrix Q whose columns constitute a - // well-conditioned basis for the columns of the earlier Q. - if (maxIterations == 0) - { - arma::qr_econ(Q, v, Q); - } - else - { - arma::lu(Q, v, Q); - } - - // Perform normalized power iterations. - for (size_t i = 0; i < maxIterations; ++i) - { - if (data.n_cols >= data.n_rows) - { - Q = (data * Q) - rowMean * (arma::ones(1, data.n_cols) * Q); - arma::lu(Q, v, Q); - Q = (data.t() * Q) - arma::repmat(rowMean.t() * Q, data.n_cols, 1); - } - else - { - Q = (data.t() * Q) - arma::repmat(rowMean.t() * Q, data.n_cols, 1); - arma::lu(Q, v, Q); - Q = (data * Q) - (rowMean * (arma::ones(1, data.n_cols) * Q)); - } - - // Computing the LU decomposition is more efficient than computing the QR - // decomposition, so we only use it in the last iteration, a pivoted QR - // decomposition which renormalizes Q, ensuring that the columns of Q are - // orthonormal. - if (i < (maxIterations - 1)) - { - arma::lu(Q, v, Q); - } - else - { - arma::qr_econ(Q, v, Q); - } - } - - // Do economical singular value decomposition and compute only the - // approximations of the left singular vectors by using the centered data - // applied to Q. - if (data.n_cols >= data.n_rows) - { - Qdata = (data * Q) - rowMean * (arma::ones(1, data.n_cols) * Q); - arma::svd_econ(u, s, v, Qdata); - v = Q * v; - } - else - { - Qdata = (Q.t() * data) - arma::repmat(Q.t() * rowMean, 1, data.n_cols); - arma::svd_econ(u, s, v, Qdata); - u = Q * u; - } - } - - //! Get the size of the normalized power iterations. - size_t IteratedPower() const { return iteratedPower; } - //! Modify the size of the normalized power iterations. - size_t& IteratedPower() { return iteratedPower; } - - //! Get the number of iterations for the power method. - size_t MaxIterations() const { return maxIterations; } - //! Modify the number of iterations for the power method. - size_t& MaxIterations() { return maxIterations; } - - //! Get the value used for decomposition stability. - double Epsilon() const { return eps; } - //! Modify the value used for decomposition stability. - double& Epsilon() { return eps; } - - private: - //! Locally stored size of the normalized power iterations. - size_t iteratedPower; - - //! Locally stored number of iterations for the power method. - size_t maxIterations; - - //! The value used for numerical stability. - double eps; -}; - -} // namespace svd -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search.hpp b/src/sdk/mlpack/include/mlpack/methods/range_search/range_search.hpp deleted file mode 100644 index 4b0c08f0b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search.hpp +++ /dev/null @@ -1,325 +0,0 @@ -/** - * @file range_search.hpp - * @author Ryan Curtin - * - * Defines the RangeSearch class, which performs a generalized range search on - * points. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_HPP -#define MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_HPP - -#include -#include -#include -#include "range_search_stat.hpp" - -namespace mlpack { -namespace range /** Range-search routines. */ { - -//! Forward declaration. -class TrainVisitor; - -/** - * The RangeSearch class is a template class for performing range searches. It - * is implemented in the style of a generalized tree-independent dual-tree - * algorithm; for more details on the actual algorithm, see the RangeSearchRules - * class. - * - * @tparam MetricType Metric to use for range search calculations. - * @tparam MatType Type of data to use. - * @tparam TreeType Type of tree to use; must satisfy the TreeType policy API. - */ -template class TreeType = tree::KDTree> -class RangeSearch -{ - public: - //! Convenience typedef. - typedef TreeType Tree; - - /** - * Initialize the RangeSearch object with a given reference dataset (this is - * the dataset which is searched). Optionally, perform the computation in - * naive mode or single-tree mode. Additionally, an instantiated metric can be - * given, for cases where the distance metric holds data. - * - * This method will move the matrices to internal copies, which are - * rearranged during tree-building. You can avoid creating an extra copy by - * pre-constructing the trees and passing them in using std::move. - * - * @param referenceSet Reference dataset. - * @param naive Whether the computation should be done in O(n^2) naive mode. - * @param singleMode Whether single-tree computation should be used (as - * opposed to dual-tree computation). - * @param metric Instantiated distance metric. - */ - RangeSearch(MatType referenceSet, - const bool naive = false, - const bool singleMode = false, - const MetricType metric = MetricType()); - - /** - * Initialize the RangeSearch object with the given pre-constructed reference - * tree (this is the tree built on the reference set, which is the set that is - * searched). Optionally, choose to use single-tree mode, which will not - * build a tree on query points. Naive mode is not available as an option for - * this constructor. Additionally, an instantiated distance metric can be - * given, for cases where the distance metric holds data. - * - * There is no copying of the data matrices in this constructor (because - * tree-building is not necessary), so this is the constructor to use when - * copies absolutely must be avoided. - * - * @note - * Because tree-building (at least with BinarySpaceTree) modifies the ordering - * of a matrix, be aware that mapping of the points back to their original - * indices is not done when this constructor is used. - * @endnote - * - * @param referenceTree Pre-built tree for reference points. - * @param referenceSet Set of reference points corresponding to referenceTree. - * @param singleMode Whether single-tree computation should be used (as - * opposed to dual-tree computation). - * @param metric Instantiated distance metric. - */ - RangeSearch(Tree* referenceTree, - const bool singleMode = false, - const MetricType metric = MetricType()); - - /** - * Initialize the RangeSearch object without any reference data. If the - * monochromatic Search() is called before a reference set is set with - * Train(), no results will be returned (since the reference set is empty). - * - * @param naive Whether to use naive search. - * @param singleMode Whether single-tree computation should be used (as - * opposed to dual-tree computation). - * @param metric Instantiated metric. - */ - RangeSearch(const bool naive = false, - const bool singleMode = false, - const MetricType metric = MetricType()); - - /** - * Construct the RangeSearch model as a copy of the given model. Note that - * this may be computationally intensive! - * - * @param other RangeSearch model to copy. - */ - RangeSearch(const RangeSearch& other); - - /** - * Construct the RangeSearch model by taking ownership of the given model. - * - * @param other RangeSearch model to take ownership of. - */ - RangeSearch(RangeSearch&& other); - - /** - * Copy the given RangeSearch model. - * Use std::move to pass in the model if the old copy is no longer needed. - * - * @param other RangeSearch model to copy. - */ - RangeSearch& operator=(RangeSearch other); - - /** - * Destroy the RangeSearch object. If trees were created, they will be - * deleted. - */ - ~RangeSearch(); - - /** - * Set the reference set to a new reference set, and build a tree if - * necessary. This method is called 'Train()' in order to match the rest of - * the mlpack abstractions, even though calling this "training" is maybe a - * bit of a stretch. - * - * Use std::move to pass in the reference set if the old copy is no longer - * needed. - * - * @param referenceSet New set of reference data. - */ - void Train(MatType referenceSet); - - /** - * Set the reference tree to a new reference tree. - */ - void Train(Tree* referenceTree); - - /** - * Search for all reference points in the given range for each point in the - * query set, returning the results in the neighbors and distances objects. - * Each entry in the external vector corresponds to a query point. Each of - * these entries holds a vector which contains the indices and distances of - * the reference points falling into the given range. - * - * That is: - * - * - neighbors.size() and distances.size() both equal the number of query - * points. - * - * - neighbors[i] contains the indices of all the points in the reference set - * which have distances inside the given range to query point i. - * - * - distances[i] contains all of the distances corresponding to the indices - * contained in neighbors[i]. - * - * - neighbors[i] and distances[i] are not sorted in any particular order. - * - * @param querySet Set of query points to search with. - * @param range Range of distances in which to search. - * @param neighbors Object which will hold the list of neighbors for each - * point which fell into the given range, for each query point. - * @param distances Object which will hold the list of distances for each - * point which fell into the given range, for each query point. - */ - void Search(const MatType& querySet, - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances); - - /** - * Given a pre-built query tree, search for all reference points in the given - * range for each point in the query set, returning the results in the - * neighbors and distances objects. - * - * Each entry in the external vector corresponds to a query point. Each of - * these entries holds a vector which contains the indices and distances of - * the reference points falling into the given range. - * - * That is: - * - * - neighbors.size() and distances.size() both equal the number of query - * points. - * - * - neighbors[i] contains the indices of all the points in the reference set - * which have distances inside the given range to query point i. - * - * - distances[i] contains all of the distances corresponding to the indices - * contained in neighbors[i]. - * - * - neighbors[i] and distances[i] are not sorted in any particular order. - * - * If either naive or singleMode are set to true, this will throw an - * invalid_argument exception; passing in a query tree implies dual-tree - * search. - * - * If you want to use the reference tree as the query tree, instead call the - * overload of Search() that does not take a query set. - * - * @param queryTree Tree built on query points. - * @param range Range of distances in which to search. - * @param neighbors Object which will hold the list of neighbors for each - * point which fell into the given range, for each query point. - * @param distances Object which will hold the list of distances for each - * point which fell into the given range, for each query point. - */ - void Search(Tree* queryTree, - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances); - - /** - * Search for all points in the given range for each point in the reference - * set (which was passed to the constructor), returning the results in the - * neighbors and distances objects. This means that the query set and the - * reference set are the same. - * - * Each entry in the external vector corresponds to a query point. Each of - * these entries holds a vector which contains the indices and distances of - * the reference points falling into the given range. - * - * That is: - * - * - neighbors.size() and distances.size() both equal the number of query - * points. - * - * - neighbors[i] contains the indices of all the points in the reference set - * which have distances inside the given range to query point i. - * - * - distances[i] contains all of the distances corresponding to the indices - * contained in neighbors[i]. - * - * - neighbors[i] and distances[i] are not sorted in any particular order. - * - * @param queryTree Tree built on query points. - * @param range Range of distances in which to search. - * @param neighbors Object which will hold the list of neighbors for each - * point which fell into the given range, for each query point. - * @param distances Object which will hold the list of distances for each - * point which fell into the given range, for each query point. - */ - void Search(const math::Range& range, - std::vector>& neighbors, - std::vector>& distances); - - //! Get whether single-tree search is being used. - bool SingleMode() const { return singleMode; } - //! Modify whether single-tree search is being used. - bool& SingleMode() { return singleMode; } - - //! Get whether naive search is being used. - bool Naive() const { return naive; } - //! Modify whether naive search is being used. - bool& Naive() { return naive; } - - //! Get the number of base cases during the last search. - size_t BaseCases() const { return baseCases; } - //! Get the number of scores during the last search. - size_t Scores() const { return scores; } - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int version); - - //! Return the reference set. - const MatType& ReferenceSet() const { return *referenceSet; } - - //! Return the reference tree (or NULL if in naive mode). - Tree* ReferenceTree() { return referenceTree; } - - private: - //! Mappings to old reference indices (used when this object builds trees). - std::vector oldFromNewReferences; - //! Reference tree. - Tree* referenceTree; - //! Reference set (data should be accessed using this). In some situations we - //! may be the owner of this. - const MatType* referenceSet; - - //! If true, this object is responsible for deleting the trees. - bool treeOwner; - - //! If true, O(n^2) naive computation is used. - bool naive; - //! If true, single-tree computation is used. - bool singleMode; - - //! Instantiated distance metric. - MetricType metric; - - //! The total number of base cases during the last search. - size_t baseCases; - //! The total number of scores during the last search. - size_t scores; - - //! For access to mappings when building models. - friend class TrainVisitor; -}; - -} // namespace range -} // namespace mlpack - -// Include implementation. -#include "range_search_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_impl.hpp deleted file mode 100644 index d4cbcc5f2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_impl.hpp +++ /dev/null @@ -1,694 +0,0 @@ -/** - * @file range_search_impl.hpp - * @author Ryan Curtin - * - * Implementation of the RangeSearch class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP -#define MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP - -// Just in case it hasn't been included. -#include "range_search.hpp" - -// The rules for traversal. -#include "range_search_rules.hpp" - -namespace mlpack { -namespace range { - -template -TreeType* BuildTree( - MatType&& dataset, - std::vector& oldFromNew, - const typename std::enable_if< - tree::TreeTraits::RearrangesDataset>::type* = 0) -{ - return new TreeType(std::forward(dataset), oldFromNew); -} - -//! Call the tree constructor that does not do mapping. -template -TreeType* BuildTree( - MatType&& dataset, - const std::vector& /* oldFromNew */, - const typename std::enable_if< - !tree::TreeTraits::RearrangesDataset>::type* = 0) -{ - return new TreeType(std::forward(dataset)); -} - -template class TreeType> -RangeSearch::RangeSearch( - MatType referenceSet, - const bool naive, - const bool singleMode, - const MetricType metric) : - referenceTree(naive ? NULL : BuildTree(std::move(referenceSet), - oldFromNewReferences)), - referenceSet(naive ? new MatType(std::move(referenceSet)) : - &referenceTree->Dataset()), - treeOwner(!naive), - naive(naive), - singleMode(!naive && singleMode), - metric(metric), - baseCases(0), - scores(0) -{ - // Nothing to do. -} - -template class TreeType> -RangeSearch::RangeSearch( - Tree* referenceTree, - const bool singleMode, - const MetricType metric) : - referenceTree(referenceTree), - referenceSet(&referenceTree->Dataset()), - treeOwner(false), - naive(false), - singleMode(singleMode), - metric(metric), - baseCases(0), - scores(0) -{ - // Nothing else to initialize. -} - -template class TreeType> -RangeSearch::RangeSearch( - const bool naive, - const bool singleMode, - const MetricType metric) : - referenceTree(NULL), - referenceSet(new MatType()), // Empty matrix. - treeOwner(false), - naive(naive), - singleMode(singleMode), - metric(metric), - baseCases(0), - scores(0) -{ - // Build the tree on the empty dataset, if necessary. - if (!naive) - { - referenceTree = BuildTree(const_cast(*referenceSet), - oldFromNewReferences); - treeOwner = true; - } -} - -template class TreeType> -RangeSearch::RangeSearch( - const RangeSearch& other) : - oldFromNewReferences(other.oldFromNewReferences), - referenceTree(other.referenceTree ? new Tree(*other.referenceTree) : NULL), - referenceSet(other.referenceTree ? &referenceTree->Dataset() : - new MatType(*other.referenceSet)), - treeOwner(other.referenceTree), - naive(other.naive), - singleMode(other.singleMode), - metric(other.metric), - baseCases(other.baseCases), - scores(other.scores) -{ - // Nothing to do. -} - -template class TreeType> -RangeSearch::RangeSearch(RangeSearch&& other) : - oldFromNewReferences(std::move(other.oldFromNewReferences)), - referenceTree(other.referenceTree), - referenceSet(other.referenceSet), - treeOwner(other.treeOwner), - naive(other.naive), - singleMode(other.singleMode), - metric(std::move(other.metric)), - baseCases(other.baseCases), - scores(other.scores) -{ - // Clear other object. - other.referenceSet = new MatType(); - other.referenceTree = - BuildTree(const_cast(*other.referenceSet), - other.oldFromNewReferences); - other.treeOwner = true; - other.naive = false; - other.singleMode = false; - other.baseCases = 0; - other.scores = 0; -} - -template class TreeType> -RangeSearch& -RangeSearch::operator=(RangeSearch other) -{ - // Clean memory first. - if (treeOwner) - delete referenceTree; - if (naive) - delete referenceSet; - - // Move the other model. - oldFromNewReferences = std::move(other.oldFromNewReferences); - referenceTree = other.referenceTree; - referenceSet = other.referenceSet; - treeOwner = other.treeOwner; - naive = other.naive; - singleMode = other.singleMode; - metric = std::move(other.metric); - baseCases = other.baseCases; - scores = other.scores; - - return *this; -} - -template class TreeType> -RangeSearch::~RangeSearch() -{ - if (treeOwner && referenceTree) - delete referenceTree; - if (naive && referenceSet) - delete referenceSet; -} - -template class TreeType> -void RangeSearch::Train( - MatType referenceSet) -{ - // Clean up the old tree, if we built one. - if (treeOwner && referenceTree) - delete referenceTree; - - // We may need to rebuild the tree. - if (!naive) - { - referenceTree = BuildTree(std::move(referenceSet), - oldFromNewReferences); - treeOwner = true; - } - else - { - treeOwner = false; - } - - // Delete the old reference set, if we owned it. - if (naive && this->referenceSet) - delete this->referenceSet; - - if (!naive) - { - this->referenceSet = &referenceTree->Dataset(); - } - else - { - this->referenceSet = new MatType(std::move(referenceSet)); - } -} - -template class TreeType> -void RangeSearch::Train( - Tree* referenceTree) -{ - if (naive) - throw std::invalid_argument("cannot train on given reference tree when " - "naive search (without trees) is desired"); - - if (treeOwner && referenceTree) - delete this->referenceTree; - - this->referenceTree = referenceTree; - this->referenceSet = &referenceTree->Dataset(); - treeOwner = false; -} - -template class TreeType> -void RangeSearch::Search( - const MatType& querySet, - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances) -{ - if (querySet.n_rows != referenceSet->n_rows) - { - std::ostringstream oss; - oss << "RangeSearch::Search(): dimensionalities of query set (" - << querySet.n_rows << ") and reference set (" << referenceSet->n_rows - << ") do not match!"; - throw std::invalid_argument(oss.str()); - } - - // If there are no points, there is no search to be done. - if (referenceSet->n_cols == 0) - return; - - Timer::Start("range_search/computing_neighbors"); - - // This will hold mappings for query points, if necessary. - std::vector oldFromNewQueries; - - // If we have built the trees ourselves, then we will have to map all the - // indices back to their original indices when this computation is finished. - // To avoid extra copies, we will store the unmapped neighbors and distances - // in a separate object. - std::vector>* neighborPtr = &neighbors; - std::vector>* distancePtr = &distances; - - // Mapping is only necessary if the tree rearranges points. - if (tree::TreeTraits::RearrangesDataset) - { - // Query indices only need to be mapped if we are building the query tree - // ourselves. - if (!singleMode && !naive) - { - distancePtr = new std::vector>; - neighborPtr = new std::vector>; - } - - // Reference indices only need to be mapped if we built the reference tree - // ourselves. - else if (treeOwner) - neighborPtr = new std::vector>; - } - - // Resize each vector. - neighborPtr->clear(); // Just in case there was anything in it. - neighborPtr->resize(querySet.n_cols); - distancePtr->clear(); - distancePtr->resize(querySet.n_cols); - - // Create the helper object for the traversal. - typedef RangeSearchRules RuleType; - - // Reset counts. - baseCases = 0; - scores = 0; - - if (naive) - { - RuleType rules(*referenceSet, querySet, range, *neighborPtr, *distancePtr, - metric); - - // The naive brute-force solution. - for (size_t i = 0; i < querySet.n_cols; ++i) - for (size_t j = 0; j < referenceSet->n_cols; ++j) - rules.BaseCase(i, j); - - baseCases += (querySet.n_cols * referenceSet->n_cols); - } - else if (singleMode) - { - // Create the traverser. - RuleType rules(*referenceSet, querySet, range, *neighborPtr, *distancePtr, - metric); - typename Tree::template SingleTreeTraverser traverser(rules); - - // Now have it traverse for each point. - for (size_t i = 0; i < querySet.n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - baseCases += rules.BaseCases(); - scores += rules.Scores(); - } - else // Dual-tree recursion. - { - // Build the query tree. - Timer::Stop("range_search/computing_neighbors"); - Timer::Start("range_search/tree_building"); - Tree* queryTree = BuildTree(querySet, oldFromNewQueries); - Timer::Stop("range_search/tree_building"); - Timer::Start("range_search/computing_neighbors"); - - // Create the traverser. - RuleType rules(*referenceSet, queryTree->Dataset(), range, *neighborPtr, - *distancePtr, metric); - typename Tree::template DualTreeTraverser traverser(rules); - - traverser.Traverse(*queryTree, *referenceTree); - - baseCases += rules.BaseCases(); - scores += rules.Scores(); - - // Clean up tree memory. - delete queryTree; - } - - Timer::Stop("range_search/computing_neighbors"); - - // Map points back to original indices, if necessary. - if (tree::TreeTraits::RearrangesDataset) - { - if (!singleMode && !naive && treeOwner) - { - // We must map both query and reference indices. - neighbors.clear(); - neighbors.resize(querySet.n_cols); - distances.clear(); - distances.resize(querySet.n_cols); - - for (size_t i = 0; i < distances.size(); i++) - { - // Map distances (copy a column). - const size_t queryMapping = oldFromNewQueries[i]; - distances[queryMapping] = (*distancePtr)[i]; - - // Copy each neighbor individually, because we need to map it. - neighbors[queryMapping].resize(distances[queryMapping].size()); - for (size_t j = 0; j < distances[queryMapping].size(); j++) - neighbors[queryMapping][j] = - oldFromNewReferences[(*neighborPtr)[i][j]]; - } - - // Finished with temporary objects. - delete neighborPtr; - delete distancePtr; - } - else if (!singleMode && !naive) - { - // We must map query indices only. - neighbors.clear(); - neighbors.resize(querySet.n_cols); - distances.clear(); - distances.resize(querySet.n_cols); - - for (size_t i = 0; i < distances.size(); ++i) - { - // Map distances and neighbors (copy a column). - const size_t queryMapping = oldFromNewQueries[i]; - distances[queryMapping] = (*distancePtr)[i]; - neighbors[queryMapping] = (*neighborPtr)[i]; - } - - // Finished with temporary objects. - delete neighborPtr; - delete distancePtr; - } - else if (treeOwner) - { - // We must map reference indices only. - neighbors.clear(); - neighbors.resize(querySet.n_cols); - - for (size_t i = 0; i < neighbors.size(); i++) - { - neighbors[i].resize((*neighborPtr)[i].size()); - for (size_t j = 0; j < neighbors[i].size(); j++) - neighbors[i][j] = oldFromNewReferences[(*neighborPtr)[i][j]]; - } - - // Finished with temporary object. - delete neighborPtr; - } - } -} - -template class TreeType> -void RangeSearch::Search( - Tree* queryTree, - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances) -{ - // If there are no points, there is no search to be done. - if (referenceSet->n_cols == 0) - return; - - Timer::Start("range_search/computing_neighbors"); - - // Get a reference to the query set. - const MatType& querySet = queryTree->Dataset(); - - // Make sure we are in dual-tree mode. - if (singleMode || naive) - throw std::invalid_argument("cannot call RangeSearch::Search() with a " - "query tree when naive or singleMode are set to true"); - - // We won't need to map query indices, but will we need to map distances? - std::vector>* neighborPtr = &neighbors; - - if (treeOwner && tree::TreeTraits::RearrangesDataset) - neighborPtr = new std::vector>; - - // Resize each vector. - neighborPtr->clear(); // Just in case there was anything in it. - neighborPtr->resize(querySet.n_cols); - distances.clear(); - distances.resize(querySet.n_cols); - - // Create the helper object for the traversal. - typedef RangeSearchRules RuleType; - RuleType rules(*referenceSet, queryTree->Dataset(), range, *neighborPtr, - distances, metric); - - // Create the traverser. - typename Tree::template DualTreeTraverser traverser(rules); - - traverser.Traverse(*queryTree, *referenceTree); - - Timer::Stop("range_search/computing_neighbors"); - - baseCases = rules.BaseCases(); - scores = rules.Scores(); - - // Do we need to map indices? - if (treeOwner && tree::TreeTraits::RearrangesDataset) - { - // We must map reference indices only. - neighbors.clear(); - neighbors.resize(querySet.n_cols); - - for (size_t i = 0; i < neighbors.size(); i++) - { - neighbors[i].resize((*neighborPtr)[i].size()); - for (size_t j = 0; j < neighbors[i].size(); j++) - neighbors[i][j] = oldFromNewReferences[(*neighborPtr)[i][j]]; - } - - // Finished with temporary object. - delete neighborPtr; - } -} - -template class TreeType> -void RangeSearch::Search( - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances) -{ - // If there are no points, there is no search to be done. - if (referenceSet->n_cols == 0) - return; - - Timer::Start("range_search/computing_neighbors"); - - // Here, we will use the query set as the reference set. - std::vector>* neighborPtr = &neighbors; - std::vector>* distancePtr = &distances; - - if (tree::TreeTraits::RearrangesDataset && treeOwner) - { - // We will always need to rearrange in this case. - distancePtr = new std::vector>; - neighborPtr = new std::vector>; - } - - // Resize each vector. - neighborPtr->clear(); // Just in case there was anything in it. - neighborPtr->resize(referenceSet->n_cols); - distancePtr->clear(); - distancePtr->resize(referenceSet->n_cols); - - // Create the helper object for the traversal. - typedef RangeSearchRules RuleType; - RuleType rules(*referenceSet, *referenceSet, range, *neighborPtr, - *distancePtr, metric, true /* don't return the query in the results */); - - if (naive) - { - // The naive brute-force solution. - for (size_t i = 0; i < referenceSet->n_cols; ++i) - for (size_t j = 0; j < referenceSet->n_cols; ++j) - rules.BaseCase(i, j); - - baseCases = (referenceSet->n_cols * referenceSet->n_cols); - scores = 0; - } - else if (singleMode) - { - // Create the traverser. - typename Tree::template SingleTreeTraverser traverser(rules); - - // Now have it traverse for each point. - for (size_t i = 0; i < referenceSet->n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - baseCases = rules.BaseCases(); - scores = rules.Scores(); - } - else // Dual-tree recursion. - { - // Create the traverser. - typename Tree::template DualTreeTraverser traverser(rules); - - traverser.Traverse(*referenceTree, *referenceTree); - - baseCases = rules.BaseCases(); - scores = rules.Scores(); - } - - Timer::Stop("range_search/computing_neighbors"); - - // Do we need to map the reference indices? - if (treeOwner && tree::TreeTraits::RearrangesDataset) - { - neighbors.clear(); - neighbors.resize(referenceSet->n_cols); - distances.clear(); - distances.resize(referenceSet->n_cols); - - for (size_t i = 0; i < distances.size(); i++) - { - // Map distances (copy a column). - const size_t refMapping = oldFromNewReferences[i]; - distances[refMapping] = (*distancePtr)[i]; - - // Copy each neighbor individually, because we need to map it. - neighbors[refMapping].resize(distances[refMapping].size()); - for (size_t j = 0; j < distances[refMapping].size(); j++) - { - neighbors[refMapping][j] = oldFromNewReferences[(*neighborPtr)[i][j]]; - } - } - - // Finished with temporary objects. - delete neighborPtr; - delete distancePtr; - } -} - -template class TreeType> -template -void RangeSearch::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // Serialize preferences for search. - ar & BOOST_SERIALIZATION_NVP(naive); - ar & BOOST_SERIALIZATION_NVP(singleMode); - - // Reset base cases and scores if we are loading. - if (Archive::is_loading::value) - { - baseCases = 0; - scores = 0; - } - - // If we are doing naive search, we serialize the dataset. Otherwise we - // serialize the tree. - if (naive) - { - if (Archive::is_loading::value) - { - if (referenceSet) - delete referenceSet; - } - - ar & BOOST_SERIALIZATION_NVP(referenceSet); - ar & BOOST_SERIALIZATION_NVP(metric); - - // If we are loading, set the tree to NULL and clean up memory if necessary. - if (Archive::is_loading::value) - { - if (treeOwner && referenceTree) - delete referenceTree; - - referenceTree = NULL; - oldFromNewReferences.clear(); - treeOwner = false; - } - } - else - { - // Delete the current reference tree, if necessary and if we are loading. - if (Archive::is_loading::value) - { - if (treeOwner && referenceTree) - delete referenceTree; - - // After we load the tree, we will own it. - treeOwner = true; - } - - ar & BOOST_SERIALIZATION_NVP(referenceTree); - ar & BOOST_SERIALIZATION_NVP(oldFromNewReferences); - - // If we are loading, set the dataset accordingly and clean up memory if - // necessary. - if (Archive::is_loading::value) - { - referenceSet = &referenceTree->Dataset(); - metric = referenceTree->Metric(); // Get the metric from the tree. - } - } -} - -} // namespace range -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_rules.hpp b/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_rules.hpp deleted file mode 100644 index 260a86232..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_rules.hpp +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @file range_search_rules.hpp - * @author Ryan Curtin - * - * Rules for range search, so that it can be done with arbitrary tree types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_RULES_HPP -#define MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_RULES_HPP - -#include - -namespace mlpack { -namespace range { - -/** - * The RangeSearchRules class is a template helper class used by RangeSearch - * class when performing range searches. - * - * @tparam MetricType The metric to use for computation. - * @tparam TreeType The tree type to use; must adhere to the TreeType API. - */ -template -class RangeSearchRules -{ - public: - /** - * Construct the RangeSearchRules object. This is usually done from within - * the RangeSearch class at search time. - * - * @param referenceSet Set of reference data. - * @param querySet Set of query data. - * @param range Range to search for. - * @param neighbors Vector to store resulting neighbors in. - * @param distances Vector to store resulting distances in. - * @param metric Instantiated metric. - * @param sameSet If true, the query and reference set are taken to be the - * same, and a query point will not return itself in the results. - */ - RangeSearchRules(const arma::mat& referenceSet, - const arma::mat& querySet, - const math::Range& range, - std::vector >& neighbors, - std::vector >& distances, - MetricType& metric, - const bool sameSet = false); - - /** - * Compute the base case between the given query point and reference point. - * - * @param queryIndex Index of query point. - * @param referenceIndex Index of reference point. - */ - double BaseCase(const size_t queryIndex, const size_t referenceIndex); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - */ - double Score(const size_t queryIndex, TreeType& referenceNode); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). This is used when the score has already - * been calculated, but another recursion may have modified the bounds for - * pruning. So the old score is checked against the new pruning bound. - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - * @param oldScore Old score produced by Score() (or Rescore()). - */ - double Rescore(const size_t queryIndex, - TreeType& referenceNode, - const double oldScore) const; - - /** - * Get the score for recursion order. A low score indicates priority for - * recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - */ - double Score(TreeType& queryNode, TreeType& referenceNode); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). This is used when the score has already - * been calculated, but another recursion may have modified the bounds for - * pruning. So the old score is checked against the new pruning bound. - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - * @param oldScore Old score produced by Score() (or Rescore()). - */ - double Rescore(TreeType& queryNode, - TreeType& referenceNode, - const double oldScore) const; - - typedef typename tree::TraversalInfo TraversalInfoType; - - const TraversalInfoType& TraversalInfo() const { return traversalInfo; } - TraversalInfoType& TraversalInfo() { return traversalInfo; } - - //! Get the number of base cases. - size_t BaseCases() const { return baseCases; } - //! Get the number of scores (that is, calls to RangeDistance()). - size_t Scores() const { return scores; } - - private: - //! The reference set. - const arma::mat& referenceSet; - - //! The query set. - const arma::mat& querySet; - - //! The range of distances for which we are searching. - const math::Range& range; - - //! The vector the resultant neighbor indices should be stored in. - std::vector >& neighbors; - - //! The vector the resultant neighbor distances should be stored in. - std::vector >& distances; - - //! The instantiated metric. - MetricType& metric; - - //! If true, the query and reference set are taken to be the same. - bool sameSet; - - //! The last query index. - size_t lastQueryIndex; - //! The last reference index. - size_t lastReferenceIndex; - - //! Add all the points in the given node to the results for the given query - //! point. If the base case has already been calculated, we make sure to not - //! add that to the results twice. - void AddResult(const size_t queryIndex, - TreeType& referenceNode); - - TraversalInfoType traversalInfo; - - //! The number of base cases. - size_t baseCases; - //! THe number of scores. - size_t scores; -}; - -} // namespace range -} // namespace mlpack - -// Include implementation. -#include "range_search_rules_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_rules_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_rules_impl.hpp deleted file mode 100644 index 65db14a81..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_rules_impl.hpp +++ /dev/null @@ -1,265 +0,0 @@ -/** - * @file range_search_rules_impl.hpp - * @author Ryan Curtin - * - * Implementation of rules for range search with generic trees. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_RULES_IMPL_HPP -#define MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_RULES_IMPL_HPP - -// In case it hasn't been included yet. -#include "range_search_rules.hpp" - -namespace mlpack { -namespace range { - -template -RangeSearchRules::RangeSearchRules( - const arma::mat& referenceSet, - const arma::mat& querySet, - const math::Range& range, - std::vector >& neighbors, - std::vector >& distances, - MetricType& metric, - const bool sameSet) : - referenceSet(referenceSet), - querySet(querySet), - range(range), - neighbors(neighbors), - distances(distances), - metric(metric), - sameSet(sameSet), - lastQueryIndex(querySet.n_cols), - lastReferenceIndex(referenceSet.n_cols), - baseCases(0), - scores(0) -{ - // Nothing to do. -} - -//! The base case. Evaluate the distance between the two points and add to the -//! results if necessary. -template -inline force_inline -double RangeSearchRules::BaseCase( - const size_t queryIndex, - const size_t referenceIndex) -{ - // If the datasets are the same, don't return the point as in its own range. - if (sameSet && (queryIndex == referenceIndex)) - return 0.0; - - // If we have just performed this base case, don't do it again. - if ((lastQueryIndex == queryIndex) && (lastReferenceIndex == referenceIndex)) - return 0.0; // No value to return... this shouldn't do anything bad. - - const double distance = metric.Evaluate(querySet.unsafe_col(queryIndex), - referenceSet.unsafe_col(referenceIndex)); - ++baseCases; - - // Update last indices, so we don't accidentally perform a base case twice. - lastQueryIndex = queryIndex; - lastReferenceIndex = referenceIndex; - - if (range.Contains(distance)) - { - neighbors[queryIndex].push_back(referenceIndex); - distances[queryIndex].push_back(distance); - } - - return distance; -} - -//! Single-tree scoring function. -template -double RangeSearchRules::Score(const size_t queryIndex, - TreeType& referenceNode) -{ - // We must get the minimum and maximum distances and store them in this - // object. - math::Range distances; - - if (tree::TreeTraits::FirstPointIsCentroid) - { - // In this situation, we calculate the base case. So we should check to be - // sure we haven't already done that. - double baseCase; - if (tree::TreeTraits::HasSelfChildren && - (referenceNode.Parent() != NULL) && - (referenceNode.Point(0) == referenceNode.Parent()->Point(0))) - { - // If the tree has self-children and this is a self-child, the base case - // was already calculated. - baseCase = referenceNode.Parent()->Stat().LastDistance(); - lastQueryIndex = queryIndex; - lastReferenceIndex = referenceNode.Point(0); - } - else - { - // We must calculate the base case by hand. - baseCase = BaseCase(queryIndex, referenceNode.Point(0)); - } - - // This may be possibly loose for non-ball bound trees. - distances.Lo() = baseCase - referenceNode.FurthestDescendantDistance(); - distances.Hi() = baseCase + referenceNode.FurthestDescendantDistance(); - - // Update last distance calculation. - referenceNode.Stat().LastDistance() = baseCase; - } - else - { - distances = referenceNode.RangeDistance(querySet.unsafe_col(queryIndex)); - ++scores; - } - - // If the ranges do not overlap, prune this node. - if (!distances.Contains(range)) - return DBL_MAX; - - // In this case, all of the points in the reference node will be part of the - // results. - if ((distances.Lo() >= range.Lo()) && (distances.Hi() <= range.Hi())) - { - AddResult(queryIndex, referenceNode); - return DBL_MAX; // We don't need to go any deeper. - } - - // Otherwise the score doesn't matter. Recursion order is irrelevant in - // range search. - return 0.0; -} - -//! Single-tree rescoring function. -template -double RangeSearchRules::Rescore( - const size_t /* queryIndex */, - TreeType& /* referenceNode */, - const double oldScore) const -{ - // If it wasn't pruned before, it isn't pruned now. - return oldScore; -} - -//! Dual-tree scoring function. -template -double RangeSearchRules::Score(TreeType& queryNode, - TreeType& referenceNode) -{ - math::Range distances; - if (tree::TreeTraits::FirstPointIsCentroid) - { - // It is possible that the base case has already been calculated. - double baseCase = 0.0; - if ((traversalInfo.LastQueryNode() != NULL) && - (traversalInfo.LastReferenceNode() != NULL) && - (traversalInfo.LastQueryNode()->Point(0) == queryNode.Point(0)) && - (traversalInfo.LastReferenceNode()->Point(0) == referenceNode.Point(0))) - { - baseCase = traversalInfo.LastBaseCase(); - - // Make sure that if BaseCase() is called, we don't duplicate results. - lastQueryIndex = queryNode.Point(0); - lastReferenceIndex = referenceNode.Point(0); - } - else - { - // We must calculate the base case. - baseCase = BaseCase(queryNode.Point(0), referenceNode.Point(0)); - } - - distances.Lo() = baseCase - queryNode.FurthestDescendantDistance() - - referenceNode.FurthestDescendantDistance(); - distances.Hi() = baseCase + queryNode.FurthestDescendantDistance() - + referenceNode.FurthestDescendantDistance(); - - // Update the last distances performed for the query and reference node. - traversalInfo.LastBaseCase() = baseCase; - } - else - { - // Just perform the calculation. - distances = referenceNode.RangeDistance(queryNode); - ++scores; - } - - // If the ranges do not overlap, prune this node. - if (!distances.Contains(range)) - return DBL_MAX; - - // In this case, all of the points in the reference node will be part of all - // the results for each point in the query node. - if ((distances.Lo() >= range.Lo()) && (distances.Hi() <= range.Hi())) - { - for (size_t i = 0; i < queryNode.NumDescendants(); ++i) - AddResult(queryNode.Descendant(i), referenceNode); - return DBL_MAX; // We don't need to go any deeper. - } - - // Otherwise the score doesn't matter. Recursion order is irrelevant in range - // search. - traversalInfo.LastQueryNode() = &queryNode; - traversalInfo.LastReferenceNode() = &referenceNode; - return 0.0; -} - -//! Dual-tree rescoring function. -template -double RangeSearchRules::Rescore( - TreeType& /* queryNode */, - TreeType& /* referenceNode */, - const double oldScore) const -{ - // If it wasn't pruned before, it isn't pruned now. - return oldScore; -} - -//! Add all the points in the given node to the results for the given query -//! point. -template -void RangeSearchRules::AddResult(const size_t queryIndex, - TreeType& referenceNode) -{ - // Some types of trees calculate the base case evaluation before Score() is - // called, so if the base case has already been calculated, then we must avoid - // adding that point to the results again. - size_t baseCaseMod = 0; - if (tree::TreeTraits::FirstPointIsCentroid && - (queryIndex == lastQueryIndex) && - (referenceNode.Point(0) == lastReferenceIndex)) - { - baseCaseMod = 1; - } - - // Resize distances and neighbors vectors appropriately. We have to use - // reserve() and not resize(), because we don't know if we will encounter the - // case where the datasets and points are the same (and we skip in that case). - const size_t oldSize = neighbors[queryIndex].size(); - neighbors[queryIndex].reserve(oldSize + referenceNode.NumDescendants() - - baseCaseMod); - distances[queryIndex].reserve(oldSize + referenceNode.NumDescendants() - - baseCaseMod); - - for (size_t i = baseCaseMod; i < referenceNode.NumDescendants(); ++i) - { - if ((&referenceSet == &querySet) && - (queryIndex == referenceNode.Descendant(i))) - continue; - - const double distance = metric.Evaluate(querySet.unsafe_col(queryIndex), - referenceNode.Dataset().unsafe_col(referenceNode.Descendant(i))); - - neighbors[queryIndex].push_back(referenceNode.Descendant(i)); - distances[queryIndex].push_back(distance); - } -} - -} // namespace range -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_stat.hpp b/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_stat.hpp deleted file mode 100644 index ff0cc70f6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/range_search/range_search_stat.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file range_search_stat.hpp - * @author Ryan Curtin - * - * Statistic class for RangeSearch, which just holds the last visited node and - * the corresponding base case result. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_STAT_HPP -#define MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_STAT_HPP - -#include - -namespace mlpack { -namespace range { - -/** - * Statistic class for RangeSearch, to be set to the StatisticType of the tree - * type that range search is being performed with. This class just holds the - * last visited node and the corresponding base case result. - */ -class RangeSearchStat -{ - public: - /** - * Initialize the statistic. - */ - RangeSearchStat() : lastDistance(0.0) { } - - /** - * Initialize the statistic given a tree node that this statistic belongs to. - * In this case, we ignore the node. - */ - template - RangeSearchStat(TreeType& /* node */) : - lastDistance(0.0) { } - - //! Get the last distance evaluation. - double LastDistance() const { return lastDistance; } - //! Modify the last distance evaluation. - double& LastDistance() { return lastDistance; } - - //! Serialize the statistic. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(lastDistance); - } - - private: - //! The last distance evaluation. - double lastDistance; -}; - -} // namespace range -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/range_search/rs_model.hpp b/src/sdk/mlpack/include/mlpack/methods/range_search/rs_model.hpp deleted file mode 100644 index 9e429a14b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/range_search/rs_model.hpp +++ /dev/null @@ -1,395 +0,0 @@ -/** - * @file rs_model.hpp - * @author Ryan Curtin - * - * This is a model for range search. It is useful in that it provides an easy - * way to serialize a model, abstracts away the different types of trees, and - * also reflects the RangeSearch API and automatically directs to the right - * tree types. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_HPP -#define MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_HPP - -#include -#include -#include -#include -#include -#include "range_search.hpp" - -namespace mlpack { -namespace range { - -/** - * Alias template for Range Search. - */ -template class TreeType> -using RSType = RangeSearch; - -/** - * MonoSearchVisitor executes a monochromatic range search on the given - * RSType. Range Search is performed on the reference set itself, no querySet. - */ -class MonoSearchVisitor : public boost::static_visitor -{ - private: - //! The range to search for. - const math::Range& range; - //! Output neighbors. - std::vector>& neighbors; - //! Output distances. - std::vector>& distances; - - public: - //! Perform monochromatic search with the given RangeSearch object. - template - void operator()(RSType* rs) const; - - //! Construct the MonoSearchVisitor with the given parameters. - MonoSearchVisitor(const math::Range& range, - std::vector>& neighbors, - std::vector>& distances): - range(range), - neighbors(neighbors), - distances(distances) - {}; -}; - -/** - * BiSearchVisitor executes a bichromatic range search on the given RSType. - * We use template specialization to differentiate those tree types that - * accept leafSize as a parameter. In these cases, before doing range search, - * a query tree with proper leafSize is built from the querySet. - */ -class BiSearchVisitor : public boost::static_visitor -{ - private: - //! The query set for the bichromatic search. - const arma::mat& querySet; - //! Range to search neighbours for. - const math::Range& range; - //! The result vector for neighbors. - std::vector>& neighbors; - //! The result vector for distances. - std::vector>& distances; - //! The number of points in a leaf (for BinarySpaceTrees). - const size_t leafSize; - - //! Bichromatic range search on the given RSType considering the leafSize. - template - void SearchLeaf(RSType* rs) const; - - public: - //! Alias template necessary for visual c++ compiler. - template class TreeType> - using RSTypeT = RSType; - - //! Default Bichromatic range search on the given RSType instance. - template class TreeType> - void operator()(RSTypeT* rs) const; - - //! Bichromatic range search on the given RSType specialized for KDTrees. - void operator()(RSTypeT* rs) const; - - //! Bichromatic range search on the given RSType specialized for BallTrees. - void operator()(RSTypeT* rs) const; - - //! Bichromatic range search specialized for octrees. - void operator()(RSTypeT* rs) const; - - //! Construct the BiSearchVisitor. - BiSearchVisitor(const arma::mat& querySet, - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances, - const size_t leafSize); -}; - -/** - * TrainVisitor sets the reference set to a new reference set on the given - * RSType. We use template specialization to differentiate those tree types that - * accept leafSize as a parameter. In these cases, a reference tree with proper - * leafSize is built from the referenceSet. - */ -class TrainVisitor : public boost::static_visitor -{ - private: - //! The reference set to use for training. - arma::mat&& referenceSet; - //! The leaf size, used only by BinarySpaceTree. - size_t leafSize; - //! Train on the given RsType considering the leafSize. - template - void TrainLeaf(RSType* rs) const; - - public: - //! Alias template necessary for visual c++ compiler. - template class TreeType> - using RSTypeT = RSType; - - //! Default Train on the given RSType instance. - template class TreeType> - void operator()(RSTypeT* rs) const; - - //! Train on the given RSType specialized for KDTrees. - void operator()(RSTypeT* rs) const; - - //! Train on the given RSType specialized for BallTrees. - void operator()(RSTypeT* rs) const; - - //! Train specialized for octrees. - void operator()(RSTypeT* rs) const; - - //! Construct the TrainVisitor object with the given reference set, leafSize - TrainVisitor(arma::mat&& referenceSet, - const size_t leafSize); -}; - -/** - * ReferenceSetVisitor exposes the referenceSet of the given RSType. - */ -class ReferenceSetVisitor : public boost::static_visitor -{ - public: - //! Return the reference set. - template - const arma::mat& operator()(RSType* rs) const; -}; - -/** - * DeleteVisitor deletes the given RSType instance. - */ -class DeleteVisitor : public boost::static_visitor -{ - public: - //! Delete the RSType object. - template - void operator()(RSType* rs) const; -}; - -/** - * SingleModeVisitor exposes the SingleMode() method of the given RSType. - */ -class SingleModeVisitor : public boost::static_visitor -{ - public: - /** - * Get a reference to the singleMode parameter of the given RangeSeach - * object. - */ - template - bool& operator()(RSType* rs) const; -}; - -/** - * NaiveVisitor exposes the Naive() method of the given RSType. - */ -class NaiveVisitor : public boost::static_visitor -{ - public: - /** - * Get a reference to the naive parameter of the given RangeSearch object. - */ - template - bool& operator()(RSType* rs) const; -}; - -class RSModel -{ - public: - enum TreeTypes - { - KD_TREE, - COVER_TREE, - R_TREE, - R_STAR_TREE, - BALL_TREE, - X_TREE, - HILBERT_R_TREE, - R_PLUS_TREE, - R_PLUS_PLUS_TREE, - VP_TREE, - RP_TREE, - MAX_RP_TREE, - UB_TREE, - OCTREE - }; - - private: - TreeTypes treeType; - size_t leafSize; - - //! If true, we randomly project the data into a new basis before search. - bool randomBasis; - //! Random projection matrix. - arma::mat q; - - /** - * rSearch holds an instance of the RangeSearch class for the current - * treeType. It is initialized every time BuildModel is executed. - * We access to the contained value through the visitor classes defined above. - */ - boost::variant*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*, - RSType*> rSearch; - - public: - /** - * Initialize the RSModel with the given type and whether or not a random - * basis should be used. - * - * @param treeType Type of tree to use. - * @param randomBasis Whether or not to use a random basis. - */ - RSModel(const TreeTypes treeType = TreeTypes::KD_TREE, - const bool randomBasis = false); - - /** - * Copy the given RSModel. - * - * @param other RSModel to copy. - */ - RSModel(const RSModel& other); - - /** - * Take ownership of the given RSModel. - * - * @param other RSModel to take ownership of. - */ - RSModel(RSModel&& other); - - /** - * Copy the given RSModel. - * - * Use std::move to pass in the model if the old copy is no longer needed. - * - * @param other RSModel to copy. - */ - RSModel& operator=(RSModel other); - - /** - * Clean memory, if necessary. - */ - ~RSModel(); - - //! Serialize the range search model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - //! Expose the dataset. - const arma::mat& Dataset() const; - - //! Get whether the model is in single-tree search mode. - bool SingleMode() const; - //! Modify whether the model is in single-tree search mode. - bool& SingleMode(); - - //! Get whether the model is in naive search mode. - bool Naive() const; - //! Modify whether the model is in naive search mode. - bool& Naive(); - - //! Get the leaf size (applicable to everything but the cover tree). - size_t LeafSize() const { return leafSize; } - //! Modify the leaf size (applicable to everything but the cover tree). - size_t& LeafSize() { return leafSize; } - - //! Get the type of tree. - TreeTypes TreeType() const { return treeType; } - //! Modify the type of tree (don't do this after the model has been built). - TreeTypes& TreeType() { return treeType; } - - //! Get whether a random basis is used. - bool RandomBasis() const { return randomBasis; } - //! Modify whether a random basis is used (don't do this after the model has - //! been built). - bool& RandomBasis() { return randomBasis; } - - /** - * Build the reference tree on the given dataset with the given parameters. - * This takes possession of the reference set to avoid a copy. - * - * @param referenceSet Set of reference points. - * @param leafSize Leaf size of tree (ignored for the cover tree). - * @param naive Whether naive search should be used. - * @param singleMode Whether single-tree search should be used. - */ - void BuildModel(arma::mat&& referenceSet, - const size_t leafSize, - const bool naive, - const bool singleMode); - - /** - * Perform range search. This takes possession of the query set, so the query - * set will not be usable after the search. For more information on the - * output format, see RangeSearch<>::Search(). - * - * @param querySet Set of query points. - * @param range Range to search for. - * @param neighbors Output: neighbors falling within the desired range. - * @param distances Output: distances of neighbors. - */ - void Search(arma::mat&& querySet, - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances); - - /** - * Perform monochromatic range search, with the reference set as the query - * set. For more information on the output format, see - * RangeSearch<>::Search(). - * - * @param range Range to search for. - * @param neighbors Output: neighbors falling within the desired range. - * @param distances Output: distances of neighbors. - */ - void Search(const math::Range& range, - std::vector>& neighbors, - std::vector>& distances); - - private: - /** - * Return a string representing the name of the tree. This is used for - * logging output. - */ - std::string TreeName() const; - - /** - * Clean up memory. - */ - void CleanMemory(); -}; - -} // namespace range -} // namespace mlpack - -// Include implementation (of serialize() and inline functions). -#include "rs_model_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/range_search/rs_model_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/range_search/rs_model_impl.hpp deleted file mode 100644 index 23879f278..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/range_search/rs_model_impl.hpp +++ /dev/null @@ -1,494 +0,0 @@ -/** - * @file rs_model_impl.hpp - * @author Ryan Curtin - * - * Implementation of serialize() and inline functions for RSModel. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_IMPL_HPP -#define MLPACK_METHODS_RANGE_SEARCH_RS_MODEL_IMPL_HPP - -// In case it hasn't been included yet. -#include "rs_model.hpp" - -#include -#include - -namespace mlpack { -namespace range { - -/** - * Initialize the RSModel with the given tree type and whether or not a random - * basis should be used. - */ -inline RSModel::RSModel(TreeTypes treeType, bool randomBasis) : - treeType(treeType), - leafSize(0), - randomBasis(randomBasis) -{ - // Nothing to do. -} - -// Copy constructor. -inline RSModel::RSModel(const RSModel& other) : - treeType(other.treeType), - leafSize(other.leafSize), - randomBasis(other.randomBasis), - q(other.q), - rSearch(other.rSearch) -{ - // Nothing to do. -} - -// Move constructor. -inline RSModel::RSModel(RSModel&& other) : - treeType(other.treeType), - leafSize(other.leafSize), - randomBasis(other.randomBasis), - q(std::move(other.q)), - rSearch(std::move(other.rSearch)) -{ - // Reset other model. - other.treeType = TreeTypes::KD_TREE; - other.leafSize = 0; - other.randomBasis = false; - other.rSearch = decltype(other.rSearch)(); -} - -inline RSModel& RSModel::operator=(RSModel other) -{ - boost::apply_visitor(DeleteVisitor(), rSearch); - - treeType = other.treeType; - leafSize = other.leafSize; - randomBasis = other.randomBasis; - q = std::move(other.q); - rSearch = std::move(other.rSearch); - - return *this; -} - -// Clean memory, if necessary. -inline RSModel::~RSModel() -{ - boost::apply_visitor(DeleteVisitor(), rSearch); -} - -inline void RSModel::BuildModel(arma::mat&& referenceSet, - const size_t leafSize, - const bool naive, - const bool singleMode) -{ - // Initialize random basis if necessary. - if (randomBasis) - { - Log::Info << "Creating random basis..." << std::endl; - math::RandomBasis(q, referenceSet.n_rows); - } - - this->leafSize = leafSize; - - // Clean memory, if necessary. - boost::apply_visitor(DeleteVisitor(), rSearch); - - // Do we need to modify the reference set? - if (randomBasis) - referenceSet = q * referenceSet; - - if (!naive) - { - Timer::Start("tree_building"); - Log::Info << "Building reference tree..." << std::endl; - } - - switch (treeType) - { - case KD_TREE: - rSearch = new RSType (naive, singleMode); - break; - - case COVER_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case R_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case R_STAR_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case BALL_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case X_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case HILBERT_R_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case R_PLUS_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case R_PLUS_PLUS_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case VP_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case RP_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case MAX_RP_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case UB_TREE: - rSearch = new RSType(naive, singleMode); - break; - - case OCTREE: - rSearch = new RSType(naive, singleMode); - break; - } - - TrainVisitor tn(std::move(referenceSet), leafSize); - boost::apply_visitor(tn, rSearch); - - if (!naive) - { - Timer::Stop("tree_building"); - Log::Info << "Tree built." << std::endl; - } -} - -// Perform range search. -inline void RSModel::Search(arma::mat&& querySet, - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances) -{ - // We may need to map the query set randomly. - if (randomBasis) - querySet = q * querySet; - - Log::Info << "Search for points in the range [" << range.Lo() << ", " - << range.Hi() << "] with "; - if (!Naive() && !SingleMode()) - Log::Info << "dual-tree " << TreeName() << " search..." << std::endl; - else if (!Naive()) - Log::Info << "single-tree " << TreeName() << " search..." << std::endl; - else - Log::Info << "brute-force (naive) search..." << std::endl; - - - BiSearchVisitor search(querySet, range, neighbors, distances, - leafSize); - boost::apply_visitor(search, rSearch); -} - -// Perform range search (monochromatic case). -inline void RSModel::Search(const math::Range& range, - std::vector>& neighbors, - std::vector>& distances) -{ - Log::Info << "Search for points in the range [" << range.Lo() << ", " - << range.Hi() << "] with "; - if (!Naive() && !SingleMode()) - Log::Info << "dual-tree " << TreeName() << " search..." << std::endl; - else if (!Naive()) - Log::Info << "single-tree " << TreeName() << " search..." << std::endl; - else - Log::Info << "brute-force (naive) search..." << std::endl; - - MonoSearchVisitor search(range, neighbors, distances); - boost::apply_visitor(search, rSearch); -} - -// Get the name of the tree type. -inline std::string RSModel::TreeName() const -{ - switch (treeType) - { - case KD_TREE: - return "kd-tree"; - case COVER_TREE: - return "cover tree"; - case R_TREE: - return "R tree"; - case R_STAR_TREE: - return "R* tree"; - case BALL_TREE: - return "ball tree"; - case X_TREE: - return "X tree"; - case HILBERT_R_TREE: - return "Hilbert R tree"; - case R_PLUS_TREE: - return "R+ tree"; - case R_PLUS_PLUS_TREE: - return "R++ tree"; - case VP_TREE: - return "vantage point tree"; - case RP_TREE: - return "random projection tree (mean split)"; - case MAX_RP_TREE: - return "random projection tree (max split)"; - case UB_TREE: - return "UB tree"; - case OCTREE: - return "octree"; - default: - return "unknown tree"; - } -} - -// Clean memory. -inline void RSModel::CleanMemory() -{ - boost::apply_visitor(DeleteVisitor(), rSearch); -} - -//! Monochromatic range search on the given RSType instance. -template -void MonoSearchVisitor::operator()(RSType* rs) const -{ - if (rs) - return rs->Search(range, neighbors, distances); - throw std::runtime_error("no range search model initialized"); -} - -//! Save parameters for bichromatic range search. -BiSearchVisitor::BiSearchVisitor(const arma::mat& querySet, - const math::Range& range, - std::vector>& neighbors, - std::vector>& distances, - const size_t leafSize): - querySet(querySet), - range(range), - neighbors(neighbors), - distances(distances), - leafSize(leafSize) -{} - -//! Default Bichromatic range search on the given RSType instance. -template class TreeType> -void BiSearchVisitor::operator()(RSTypeT* rs) const -{ - if (rs) - return rs->Search(querySet, range, neighbors, distances); - throw std::runtime_error("no range search model initialized"); -} - -//! Bichromatic range search on the given RSType specialized for KDTrees. -void BiSearchVisitor::operator()(RSTypeT* rs) const -{ - if (rs) - return SearchLeaf(rs); - throw std::runtime_error("no range search model initialized"); -} - -//! Bichromatic range search on the given RSType specialized for BallTrees. -void BiSearchVisitor::operator()(RSTypeT* rs) const -{ - if (rs) - return SearchLeaf(rs); - throw std::runtime_error("no range search model initialized"); -} - -//! Bichromatic range search specialized for Ocrees. -void BiSearchVisitor::operator()(RSTypeT* rs) const -{ - if (rs) - return SearchLeaf(rs); - throw std::runtime_error("no range search model initialized"); -} - -//! Bichromatic range search on the given RSType considering the leafSize. -template -void BiSearchVisitor::SearchLeaf(RSType* rs) const -{ - if (!rs->Naive() && !rs->SingleMode()) - { - // Build a second tree and search. - Timer::Start("tree_building"); - Log::Info << "Building query tree..." << std::endl; - std::vector oldFromNewQueries; - typename RSType::Tree queryTree(std::move(querySet), oldFromNewQueries, - leafSize); - Log::Info << "Tree built." << std::endl; - Timer::Stop("tree_building"); - - std::vector> neighborsOut; - std::vector> distancesOut; - rs->Search(&queryTree, range, neighborsOut, distancesOut); - - // Remap the query points. - neighbors.resize(queryTree.Dataset().n_cols); - distances.resize(queryTree.Dataset().n_cols); - for (size_t i = 0; i < queryTree.Dataset().n_cols; ++i) - { - neighbors[oldFromNewQueries[i]] = neighborsOut[i]; - distances[oldFromNewQueries[i]] = distancesOut[i]; - } - } - else - rs->Search(querySet, range, neighbors, distances); -} - -//! Save parameters for Train. -TrainVisitor::TrainVisitor(arma::mat&& referenceSet, - const size_t leafSize) : - referenceSet(std::move(referenceSet)), - leafSize(leafSize) -{} - -//! Default Train on the given RSType instance. -template class TreeType> -void TrainVisitor::operator()(RSTypeT* rs) const -{ - if (rs) - return rs->Train(std::move(referenceSet)); - throw std::runtime_error("no range search model initialized"); -} - -//! Train on the given RSType specialized for KDTrees. -void TrainVisitor::operator()(RSTypeT* rs) const -{ - if (rs) - return TrainLeaf(rs); - throw std::runtime_error("no range search model initialized"); -} - -//! Train on the given RSType specialized for BallTrees. -void TrainVisitor::operator()(RSTypeT* rs) const -{ - if (rs) - return TrainLeaf(rs); - throw std::runtime_error("no range search model initialized"); -} - -//! Train specialized for Octrees. -void TrainVisitor::operator()(RSTypeT* rs) const -{ - if (rs) - return TrainLeaf(rs); - throw std::runtime_error("no range search model initialized"); -} - -//! Train on the given RSType considering the leafSize. -template -void TrainVisitor::TrainLeaf(RSType* rs) const -{ - if (rs->Naive()) - rs->Train(std::move(referenceSet)); - else - { - std::vector oldFromNewReferences; - typename RSType::Tree* tree = - new typename RSType::Tree(std::move(referenceSet), oldFromNewReferences, - leafSize); - rs->Train(tree); - - // Give the model ownership of the tree and the mappings. - rs->treeOwner = true; - rs->oldFromNewReferences = std::move(oldFromNewReferences); - } -} - -//! Expose the referenceSet of the given RSType. -template -const arma::mat& ReferenceSetVisitor::operator()(RSType* rs) const -{ - if (rs) - return rs->ReferenceSet(); - throw std::runtime_error("no range search model initialized"); -} - -//! For cleaning memory -template -void DeleteVisitor::operator()(RSType* rs) const -{ - if (rs) - delete rs; -} - -//! Return whether single mode enabled -template -bool& SingleModeVisitor::operator()(RSType* rs) const -{ - if (rs) - return rs->SingleMode(); - throw std::runtime_error("no range search model initialized"); -} - -//! Exposes Naive() function of given RSType -template -bool& NaiveVisitor::operator()(RSType* rs) const -{ - if (rs) - return rs->Naive(); - throw std::runtime_error("no range search model initialized"); -} - -// Serialize the model. -template -void RSModel::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(treeType); - ar & BOOST_SERIALIZATION_NVP(randomBasis); - ar & BOOST_SERIALIZATION_NVP(q); - - // This should never happen, but just in case... - if (Archive::is_loading::value) - boost::apply_visitor(DeleteVisitor(), rSearch); - - // We'll only need to serialize one of the model objects, based on the type. - ar & BOOST_SERIALIZATION_NVP(rSearch); -} - -inline const arma::mat& RSModel::Dataset() const -{ - return boost::apply_visitor(ReferenceSetVisitor(), rSearch); -} - -inline bool RSModel::SingleMode() const -{ - return boost::apply_visitor(SingleModeVisitor(), rSearch); -} - -inline bool& RSModel::SingleMode() -{ - return boost::apply_visitor(SingleModeVisitor(), rSearch); -} - -inline bool RSModel::Naive() const -{ - return boost::apply_visitor(NaiveVisitor(), rSearch); -} - -inline bool& RSModel::Naive() -{ - return boost::apply_visitor(NaiveVisitor(), rSearch); -} - -} // namespace range -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_model.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_model.hpp deleted file mode 100644 index 4a3f526ec..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_model.hpp +++ /dev/null @@ -1,441 +0,0 @@ -/** - * @file ra_model.hpp - * @author Ryan Curtin - * - * This is a model for rank-approximate nearest neighbor search. It provides an - * easy way to serialize a rank-approximate neighbor search model by abstracting - * the types of trees and reflecting the RASearch API. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANN_RA_MODEL_HPP -#define MLPACK_METHODS_RANN_RA_MODEL_HPP - -#include -#include -#include -#include -#include -#include "ra_search.hpp" - -namespace mlpack { -namespace neighbor { - -/** - * Alias template for RASearch - */ -template class TreeType> -using RAType = RASearch; - -/** - * MonoSearchVisitor executes a monochromatic neighbor search on the given - * RAType. We don't make any difference for different instantiation of RAType. - */ -class MonoSearchVisitor : public boost::static_visitor -{ - private: - //! Number of neighbors to search for. - const size_t k; - //! Result matrix for neighbors. - arma::Mat& neighbors; - //! Result matrix for distances. - arma::mat& distances; - - public: - //! Perform monochromatic nearest neighbor search. - template - void operator()(RAType* ra) const; - - //! Construct the MonoSearchVisitor object with the given parameters. - MonoSearchVisitor(const size_t k, - arma::Mat& neighbors, - arma::mat& distances) : - k(k), - neighbors(neighbors), - distances(distances) - {}; -}; - -/** - * BiSearchVisitor executes a bichromatic neighbor search on the given RAType. - * We use template specialization to differentiate those tree types types that - * accept leafSize as a parameter. In these cases, before doing neighbor search - * a query tree with proper leafSize is built from the querySet. - */ -template -class BiSearchVisitor : public boost::static_visitor -{ - private: - //! The query set for the bichromatic search. - const arma::mat& querySet; - //! The number of neighbors to search for. - const size_t k; - //! The results matrix for neighbors. - arma::Mat& neighbors; - //! The result matrix for distances. - arma::mat& distances; - //! The number of points in a leaf (for BinarySpaceTrees). - const size_t leafSize; - - //! Bichromatic neighbor search on the given RAType considering leafSize. - template - void SearchLeaf(RAType* ra) const; - - public: - //! Alias template necessary for visual c++ compiler. - template class TreeType> - using RATypeT = RAType; - - //! Default Bichromatic neighbor search on the given RAType instance. - template class TreeType> - void operator()(RATypeT* ra) const; - - //! Bichromatic search on the given RAType specialized for KDTrees. - void operator()(RATypeT* ra) const; - - //! Bichromatic search on the given RAType specialized for octrees. - void operator()(RATypeT* ra) const; - - //! Construct the BiSearchVisitor. - BiSearchVisitor(const arma::mat& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances, - const size_t leafSize); -}; - -/** - * TrainVisitor sets the reference set to a new reference set on the given - * RAType. We use template specialization to differentiate those trees that - * accept leafSize as a parameter. In these cases, a reference tree with proper - * leafSize is built from the referenceSet. - */ -template -class TrainVisitor : public boost::static_visitor -{ - private: - //! The reference set to use for training. - arma::mat&& referenceSet; - //! The leaf size, used only by BinarySpaceTree. - size_t leafSize; - - //! Train on the given RAType considering the leafSize. - template - void TrainLeaf(RAType* ra) const; - - public: - //! Alias template necessary for visual c++ compiler. - template class TreeType> - using RATypeT = RAType; - - //! Default Train on the given RAType instance. - template class TreeType> - void operator()(RATypeT* ra) const; - - //! Train on the given RAType specialized for KDTrees. - void operator()(RATypeT* ra) const; - - //! Train on the given RAType specialized for Octrees. - void operator()(RATypeT* ra) const; - - //! Construct the TrainVisitor object with the given reference set, leafSize - //! for BinarySpaceTrees. - TrainVisitor(arma::mat&& referenceSet, - const size_t leafSize); -}; - -/** - * Exposes the SingleSampleLimit() method of the given RAType. - */ -class SingleSampleLimitVisitor : public boost::static_visitor -{ - public: - template - size_t& operator()(RAType* ra) const; -}; - -/** - * Exposes the FirstLeafExact() method of the given RAType. - */ -class FirstLeafExactVisitor : public boost::static_visitor -{ - public: - template - bool& operator()(RAType* ra) const; -}; - -/** - * Exposes the SampleAtLeaves() method of the given RAType. - */ -class SampleAtLeavesVisitor : public boost::static_visitor -{ - public: - //! Return SampleAtLeaves (whether or not sampling is done at leaves). - template - bool& operator()(RAType *) const; -}; - -/** - * Exposes the Alpha() method of the given RAType. - */ -class AlphaVisitor : public boost::static_visitor -{ - public: - //! Return Alpha parameter. - template - double& operator()(RAType* ra) const; -}; - -/** - * Exposes the Tau() method of the given RAType. - */ -class TauVisitor : public boost::static_visitor -{ - public: - //! Get a reference to the Tau parameter. - template - double& operator()(RAType* ra) const; -}; - -/** - * Exposes the SingleMode() method of the given RAType. - */ -class SingleModeVisitor : public boost::static_visitor -{ - public: - //! Get a reference to the SingleMode parameter of the given RASearch object. - template - bool& operator()(RAType* ra) const; -}; - -/** - * Exposes the referenceSet of the given RAType. - */ -class ReferenceSetVisitor : public boost::static_visitor -{ - public: - //! Return the reference set. - template - const arma::mat& operator()(RAType* ra) const; -}; - -/** - * DeleteVisitor deletes the give RAType Instance. - */ -class DeleteVisitor : public boost::static_visitor -{ - public: - //! Delete the RAType Object. - template void operator()(RAType* ra) const; -}; - -/** - * NaiveVisitor exposes the Naive() method of the given RAType. - */ -class NaiveVisitor : public boost::static_visitor -{ - public: - /** - * Get a reference to the naive parameter of the given RASearch object. - */ - template - bool& operator()(RAType* ra) const; -}; - -/** - * The RAModel class provides an abstraction for the RASearch class, abstracting - * away the TreeType parameter and allowing it to be specified at runtime in - * this class. This class is written for the sake of the 'allkrann' program, - * but is not necessarily restricted to that use. - * - * @param SortPolicy Sorting policy for neighbor searching (see RASearch). - */ -template -class RAModel -{ - public: - /** - * The list of tree types we can use with RASearch. Does not include ball - * trees; see #338. - */ - enum TreeTypes - { - KD_TREE, - COVER_TREE, - R_TREE, - R_STAR_TREE, - X_TREE, - HILBERT_R_TREE, - R_PLUS_TREE, - R_PLUS_PLUS_TREE, - UB_TREE, - OCTREE - }; - - private: - //! The type of tree being used. - TreeTypes treeType; - //! The leaf size of the tree being used (useful only for the kd-tree). - size_t leafSize; - - //! If true, randomly project into a new basis. - bool randomBasis; - //! The basis to project into. - arma::mat q; - - //! The rank-approximate model. - boost::variant*, - RAType*, - RAType*, - RAType*, - RAType*, - RAType*, - RAType*, - RAType*, - RAType*, - RAType*> raSearch; - - public: - /** - * Initialize the RAModel with the given type and whether or not a random - * basis should be used. - */ - RAModel(TreeTypes treeType = TreeTypes::KD_TREE, bool randomBasis = false); - - /** - * Copy the given RAModel. - * - * @param other RAModel to copy. - */ - RAModel(const RAModel& other); - - /** - * Take ownership of the given RAModel. - * - * @param other RAModel to take ownership of. - */ - RAModel(RAModel&& other); - - /** - * Copy the given RAModel. - * - * @param other RAModel to copy. - */ - RAModel& operator=(const RAModel& other); - - /** - * Take ownership of the given RAModel. - * - * @param other RAModel to take ownership of. - */ - RAModel& operator=(RAModel&& other); - - //! Clean memory, if necessary. - ~RAModel(); - - //! Serialize the model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - //! Expose the dataset. - const arma::mat& Dataset() const; - - //! Get whether or not single-tree search is being used. - bool SingleMode() const; - //! Modify whether or not single-tree search is being used. - bool& SingleMode(); - - //! Get whether or not naive search is being used. - bool Naive() const; - //! Modify whether or not naive search is being used. - bool& Naive(); - - //! Get the rank-approximation in percentile of the data. - double Tau() const; - //! Modify the rank-approximation in percentile of the data. - double& Tau(); - - //! Get the desired success probability. - double Alpha() const; - //! Modify the desired success probability. - double& Alpha(); - - //! Get whether or not sampling is done at the leaves. - bool SampleAtLeaves() const; - //! Modify whether or not sampling is done at the leaves. - bool& SampleAtLeaves(); - - //! Get whether or not we traverse to the first leaf without approximation. - bool FirstLeafExact() const; - //! Modify whether or not we traverse to the first leaf without approximation. - bool& FirstLeafExact(); - - //! Get the limit on the size of a node that can be approximated. - size_t SingleSampleLimit() const; - //! Modify the limit on the size of a node that can be approximation. - size_t& SingleSampleLimit(); - - //! Get the leaf size (only relevant when the kd-tree is used). - size_t LeafSize() const; - //! Modify the leaf size (only relevant when the kd-tree is used). - size_t& LeafSize(); - - //! Get the type of tree being used. - TreeTypes TreeType() const; - //! Modify the type of tree being used. - TreeTypes& TreeType(); - - //! Get whether or not a random basis is being used. - bool RandomBasis() const; - //! Modify whether or not a random basis is being used. Be sure to rebuild - //! the model using BuildModel(). - bool& RandomBasis(); - - //! Build the reference tree. - void BuildModel(arma::mat&& referenceSet, - const size_t leafSize, - const bool naive, - const bool singleMode); - - //! Perform rank-approximate neighbor search, taking ownership of the query - //! set. - void Search(arma::mat&& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - /** - * Perform rank-approximate neighbor search, using the reference set as the - * query set. - */ - void Search(const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - //! Get the name of the tree type. - std::string TreeName() const; -}; - -} // namespace neighbor -} // namespace mlpack - -#include "ra_model_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_model_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_model_impl.hpp deleted file mode 100644 index 6f1c7d412..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_model_impl.hpp +++ /dev/null @@ -1,627 +0,0 @@ -/** - * @file ra_model_impl.hpp - * @author Ryan Curtin - * - * Implementation of the RAModel class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANN_RA_MODEL_IMPL_HPP -#define MLPACK_METHODS_RANN_RA_MODEL_IMPL_HPP - -// In case it hasn't been included yet. -#include "ra_model.hpp" -#include -#include - -namespace mlpack { -namespace neighbor { - -//! Monochromatic search for the given RAType instance. -template -void MonoSearchVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->Search(k, neighbors, distances); - throw std::runtime_error("no rank-approximate model initialized"); -} - -//! Save the parameters for the rank-approximate search. -template -BiSearchVisitor::BiSearchVisitor(const arma::mat& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances, - const size_t leafSize) : - querySet(querySet), - k(k), - neighbors(neighbors), - distances(distances), - leafSize(leafSize) -{}; - -//! Default Bichromatic search on the given RAType instance. -template -template class TreeType> -void BiSearchVisitor::operator()(RATypeT* ra) const -{ - if (ra) - return ra->Search(querySet, k, neighbors, distances); - throw std::runtime_error("no rank-approximate model initialized"); -} - -//! Bichromatic search on the given RAType specialized for KDTrees. -template -void BiSearchVisitor::operator()(RATypeT* ra) const -{ - if (ra) - return SearchLeaf(ra); - throw std::runtime_error("no rank-approximate search model initialized"); -} - -//! Bichromatic search on the given RAType specialized for Octrees. -template -void BiSearchVisitor::operator()(RATypeT* ra) const -{ - if (ra) - return SearchLeaf(ra); - throw std::runtime_error("no rank-approximate search model initialized"); -} - -//! Bichromatic search on the given RAType considering the leafSize. -template -template -void BiSearchVisitor::SearchLeaf(RAType* ra) const -{ - if (!ra->Naive() && !ra->SingleMode()) - { - // Build a second tree and search - Timer::Start("tree_building"); - Log::Info << "Building query tree...."<< std::endl; - std::vector oldFromNewQueries; - typename RAType::Tree queryTree(std::move(querySet), oldFromNewQueries, - leafSize); - Log::Info << "Tree Built." << std::endl; - Timer::Stop("tree_building"); - - arma::Mat neighborsOut; - arma::mat distancesOut; - ra->Search(&queryTree, k, neighborsOut, distancesOut); - - // Unmap the query points. - distances.set_size(distancesOut.n_rows, distancesOut.n_cols); - neighbors.set_size(neighborsOut.n_rows, neighborsOut.n_cols); - for (size_t i = 0; i < oldFromNewQueries.size(); ++i) - { - neighbors.col(oldFromNewQueries[i]) = neighborsOut.col(i); - distances.col(oldFromNewQueries[i]) = distancesOut.col(i); - } - } - else - { - // Search without building a second tree. - ra->Search(querySet, k, neighbors, distances); - } -} - -//! Save parameters for the Train. -template -TrainVisitor::TrainVisitor(arma::mat&& referenceSet, - const size_t leafSize) : - referenceSet(std::move(referenceSet)), - leafSize(leafSize) -{}; - -//! Default Train on the given RAType instance. -template -template class TreeType> -void TrainVisitor::operator()(RATypeT* ra) const -{ - if (ra) - return ra->Train(std::move(referenceSet)); - throw std::runtime_error("no rank-approximate search model initialized"); -} - -//! Train on the given RAType specialized for KDTrees. -template -void TrainVisitor::operator()(RATypeT* ra) const -{ - if (ra) - return TrainLeaf(ra); - throw std::runtime_error("no rank-approximate search model initialized"); -} - -//! Train on the given RAType specialized for Octrees. -template -void TrainVisitor::operator()(RATypeT* ra) const -{ - if (ra) - return TrainLeaf(ra); - throw std::runtime_error("no rank-approximate search model is initialized"); -} - -//! Train on the given RAType considering the leafSize. -template -template -void TrainVisitor::TrainLeaf(RAType* ra) const -{ - // Build tree, if necessary - if (ra->Naive()) - { - ra->Train(std::move(referenceSet)); - } - else - { - std::vector oldFromNewReferences; - typename RAType::Tree* tree = - new typename RAType::Tree(std::move(referenceSet), oldFromNewReferences, - leafSize); - ra->Train(tree); - - // Give the model ownership of the tree and the mappings. - ra->treeOwner = true; - ra->oldFromNewReferences = std::move(oldFromNewReferences); - } -} - -//! Exposes the SingleSampleLimit() method of the given RAType. -template -size_t& SingleSampleLimitVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->SingleSampleLimit(); - throw std::runtime_error("no rank-approximate search model is initialized"); -} - -//! Exposes the FirstLeafExact() method of the given RAType. -template -bool& FirstLeafExactVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->FirstLeafExact(); - throw std::runtime_error("no rank-approximate search model is initialized"); -} - -//! Exposes the SampleAtLeaves() method of the given RAType. -template -bool& SampleAtLeavesVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->SampleAtLeaves(); - throw std::runtime_error("no rank-approximate search model is initialized"); -} - -//! Exposes the Alpha() method of the given RAType instance. -template -double& AlphaVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->Alpha(); - throw std::runtime_error("no rank-approximate model is initialized"); -} - -//! Exposes the Tau() method of the given RAType instance. -template -double& TauVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->Tau(); - throw std::runtime_error("no rank-approximate model is initialized"); -} - -//! Exposes the SingleMode() method of the given RAType. -template -bool& SingleModeVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->SingleMode(); - throw std::runtime_error("no rank-approximate model is initialized"); -} - -//! Exposes the referenceSet of the given RAType. -template -const arma::mat& ReferenceSetVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->ReferenceSet(); - throw std::runtime_error("no rank-approximate model is initialized"); -} - -//! Exposes the Naive() method of the given RAType instance. -template -bool& NaiveVisitor::operator()(RAType* ra) const -{ - if (ra) - return ra->Naive(); - throw std::runtime_error("no rank-approximate search model is initialized"); -} - -//! For cleaning memory -template -void DeleteVisitor::operator()(RSType* rs) const -{ - if (rs) - delete rs; -} - -template -RAModel::RAModel(const TreeTypes treeType, const bool randomBasis) : - treeType(treeType), - leafSize(20), - randomBasis(randomBasis) -{ - // Nothing to do. -} - -// Copy constructor. -template -RAModel::RAModel(const RAModel& other) : - treeType(other.treeType), - leafSize(other.leafSize), - randomBasis(other.randomBasis), - q(other.q), - raSearch(other.raSearch) -{ - // Nothing to do. -} - -// Move constructor. -template -RAModel::RAModel(RAModel&& other) : - treeType(other.treeType), - leafSize(other.leafSize), - randomBasis(other.randomBasis), - q(std::move(other.q)), - raSearch(std::move(other.raSearch)) -{ - // Clear other model. - other.treeType = TreeTypes::KD_TREE; - other.leafSize = 20; - other.randomBasis = false; - other.raSearch = decltype(other.raSearch)(); -} - -// Copy operator. -template -RAModel& RAModel::operator=(const RAModel& other) -{ - // Clear current model. - boost::apply_visitor(DeleteVisitor(), raSearch); - - treeType = other.treeType; - leafSize = other.leafSize; - randomBasis = other.randomBasis; - q = other.q; - raSearch = other.raSearch; - - return *this; -} - -template -RAModel& RAModel::operator=(RAModel&& other) -{ - boost::apply_visitor(DeleteVisitor(), raSearch); - - treeType = other.treeType; - leafSize = other.leafSize; - randomBasis = other.randomBasis; - q = std::move(other.q); - raSearch = std::move(other.raSearch); - - // Reset other model. - other.treeType = TreeTypes::KD_TREE; - other.leafSize = 20; - other.randomBasis = false; - other.raSearch = decltype(other.raSearch)(); - - return *this; -} - -// Clean memory, if necessary -template -RAModel::~RAModel() -{ - boost::apply_visitor(DeleteVisitor(), raSearch); -} - -template -template -void RAModel::serialize(Archive& ar, - const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(treeType); - ar & BOOST_SERIALIZATION_NVP(randomBasis); - ar & BOOST_SERIALIZATION_NVP(q); - - // This should never happen, but just in case, be clean with memory. - if (Archive::is_loading::value) - { - boost::apply_visitor(DeleteVisitor(), raSearch); - } - - // We only need to serialize one of the kRANN objects. - ar & BOOST_SERIALIZATION_NVP(raSearch); -} - -template -const arma::mat& RAModel::Dataset() const -{ - return boost::apply_visitor(ReferenceSetVisitor(), raSearch); -} - -template -bool RAModel::Naive() const -{ - return boost::apply_visitor(NaiveVisitor(), raSearch); -} - -template -bool& RAModel::Naive() -{ - return boost::apply_visitor(NaiveVisitor(), raSearch); -} - -template -bool RAModel::SingleMode() const -{ - return boost::apply_visitor(SingleModeVisitor(), raSearch); -} - -template -bool& RAModel::SingleMode() -{ - return boost::apply_visitor(SingleModeVisitor(), raSearch); -} - -template -double RAModel::Tau() const -{ - return boost::apply_visitor(TauVisitor(), raSearch); -} - -template -double& RAModel::Tau() -{ - return boost::apply_visitor(TauVisitor(), raSearch); -} - -template -double RAModel::Alpha() const -{ - return boost::apply_visitor(AlphaVisitor(), raSearch); -} - -template -double& RAModel::Alpha() -{ - return boost::apply_visitor(AlphaVisitor(), raSearch); -} - -template -bool RAModel::SampleAtLeaves() const -{ - return boost::apply_visitor(SampleAtLeavesVisitor(), raSearch); -} - -template -bool& RAModel::SampleAtLeaves() -{ - return boost::apply_visitor(SampleAtLeavesVisitor(), raSearch); -} - -template -bool RAModel::FirstLeafExact() const -{ - return boost::apply_visitor(FirstLeafExactVisitor(), raSearch); -} - -template -bool& RAModel::FirstLeafExact() -{ - return boost::apply_visitor(FirstLeafExactVisitor(), raSearch); -} - -template -size_t RAModel::SingleSampleLimit() const -{ - return boost::apply_visitor(SingleSampleLimitVisitor(), raSearch); -} - -template -size_t& RAModel::SingleSampleLimit() -{ - return boost::apply_visitor(SingleSampleLimitVisitor(), raSearch); -} - -template -size_t RAModel::LeafSize() const -{ - return leafSize; -} - -template -size_t& RAModel::LeafSize() -{ - return leafSize; -} - -template -typename RAModel::TreeTypes RAModel::TreeType() const -{ - return treeType; -} - -template -typename RAModel::TreeTypes& RAModel::TreeType() -{ - return treeType; -} - -template -bool RAModel::RandomBasis() const -{ - return randomBasis; -} - -template -bool& RAModel::RandomBasis() -{ - return randomBasis; -} - -template -void RAModel::BuildModel(arma::mat&& referenceSet, - const size_t leafSize, - const bool naive, - const bool singleMode) -{ - // Initialize random basis, if necessary. - if (randomBasis) - { - Log::Info << "Creating random basis..." << std::endl; - math::RandomBasis(q, referenceSet.n_rows); - } - - // Clean memory, if necessary. - boost::apply_visitor(DeleteVisitor(), raSearch); - - this->leafSize = leafSize; - - if (randomBasis) - referenceSet = q * referenceSet; - - if (!naive) - { - Timer::Start("tree_building"); - Log::Info << "Building reference tree..." << std::endl; - } - - switch (treeType) - { - case KD_TREE: - raSearch = new RAType(naive, singleMode); - break; - case COVER_TREE: - raSearch = new RAType(naive, - singleMode); - break; - case R_TREE: - raSearch = new RAType(naive, singleMode); - break; - case R_STAR_TREE: - raSearch = new RAType(naive, singleMode); - break; - case X_TREE: - raSearch = new RAType(naive, singleMode); - break; - case HILBERT_R_TREE: - raSearch = new RAType(naive, singleMode); - break; - case R_PLUS_TREE: - raSearch = new RAType(naive, singleMode); - break; - case R_PLUS_PLUS_TREE: - raSearch = new RAType(naive, - singleMode); - break; - case UB_TREE: - raSearch = new RAType(naive, singleMode); - break; - case OCTREE: - raSearch = new RAType(naive, singleMode); - break; - } - - TrainVisitor tn(std::move(referenceSet), leafSize); - boost::apply_visitor(tn, raSearch); - - if (!naive) - { - Timer::Stop("tree_building"); - Log::Info << "Tree built." << std::endl; - } -} - -template -void RAModel::Search(arma::mat&& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - // Apply the random basis if necessary. - if (randomBasis) - querySet = q * querySet; - - Log::Info << "Searching for " << k << " approximate nearest neighbors with "; - if (!Naive() && !SingleMode()) - Log::Info << "dual-tree rank-approximate " << TreeName() << " search..."; - else if (!Naive()) - Log::Info << "single-tree rank-approximate " << TreeName() << " search..."; - else - Log::Info << "brute-force (naive) rank-approximate search..."; - Log::Info << std::endl; - - BiSearchVisitor search(querySet, k, neighbors, distances, - leafSize); - boost::apply_visitor(search, raSearch); -} - -template -void RAModel::Search(const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - Log::Info << "Searching for " << k << " approximate nearest neighbors with "; - if (!Naive() && !SingleMode()) - Log::Info << "dual-tree rank-approximate " << TreeName() << " search..."; - else if (!Naive()) - Log::Info << "single-tree rank-approximate " << TreeName() << " search..."; - else - Log::Info << "brute-force (naive) rank-approximate search..."; - Log::Info << std::endl; - - MonoSearchVisitor search(k, neighbors, distances); - boost::apply_visitor(search, raSearch); -} - -template -std::string RAModel::TreeName() const -{ - switch (treeType) - { - case KD_TREE: - return "kd-tree"; - case COVER_TREE: - return "cover tree"; - case R_TREE: - return "R tree"; - case R_STAR_TREE: - return "R* tree"; - case X_TREE: - return "X tree"; - case HILBERT_R_TREE: - return "Hilbert R tree"; - case R_PLUS_TREE: - return "R+ tree"; - case R_PLUS_PLUS_TREE: - return "R++ tree"; - case UB_TREE: - return "UB tree"; - case OCTREE: - return "octree"; - default: - return "unknown tree"; - } -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_query_stat.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_query_stat.hpp deleted file mode 100644 index ed0d83050..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_query_stat.hpp +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file ra_query_stat.hpp - * @author Parikshit Ram - * - * Defines the RAQueryStat class, which is the statistic used for - * rank-approximate nearest neighbor search (RASearch). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANN_RA_QUERY_STAT_HPP -#define MLPACK_METHODS_RANN_RA_QUERY_STAT_HPP - -#include - -#include - -#include -#include - -namespace mlpack { -namespace neighbor { - -/** - * Extra data for each node in the tree. For neighbor searches, each node only - * needs to store a bound on neighbor distances. - * - * Every query is required to make a minimum number of samples to guarantee the - * desired approximation error. The 'numSamplesMade' keeps track of the minimum - * number of samples made by all queries in the node in question. - */ -template -class RAQueryStat -{ - public: - /** - * Initialize the statistic with the worst possible distance according to our - * sorting policy. - */ - RAQueryStat() : bound(SortPolicy::WorstDistance()), numSamplesMade(0) { } - - /** - * Initialization for a node. - */ - template - RAQueryStat(const TreeType& /* node */) : - bound(SortPolicy::WorstDistance()), - numSamplesMade(0) - { } - - //! Get the bound. - double Bound() const { return bound; } - //! Modify the bound. - double& Bound() { return bound; } - - //! Get the number of samples made. - size_t NumSamplesMade() const { return numSamplesMade; } - //! Modify the number of samples made. - size_t& NumSamplesMade() { return numSamplesMade; } - - //! Serialize the statistic. - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(bound); - ar & BOOST_SERIALIZATION_NVP(numSamplesMade); - } - - private: - //! The bound on the node's neighbor distances. - double bound; - //! The minimum number of samples made by any query in this node. - size_t numSamplesMade; -}; - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_search.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_search.hpp deleted file mode 100644 index 2f1e58378..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_search.hpp +++ /dev/null @@ -1,408 +0,0 @@ -/** - * @file ra_search.hpp - * @author Parikshit Ram - * - * Defines the RASearch class, which performs an abstract rank-approximate - * nearest/farthest neighbor query on two datasets. - * - * The details of this method can be found in the following paper: - * - * @inproceedings{ram2009rank, - * title={{Rank-Approximate Nearest Neighbor Search: Retaining Meaning and - * Speed in High Dimensions}}, - * author={{Ram, P. and Lee, D. and Ouyang, H. and Gray, A. G.}}, - * booktitle={{Advances of Neural Information Processing Systems}}, - * year={2009} - * } - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANN_RA_SEARCH_HPP -#define MLPACK_METHODS_RANN_RA_SEARCH_HPP - -#include - -#include - -#include -#include - -#include "ra_query_stat.hpp" -#include "ra_util.hpp" - -namespace mlpack { -namespace neighbor { - -// Forward declaration. -template -class TrainVisitor; - -/** - * The RASearch class: This class provides a generic manner to perform - * rank-approximate search via random-sampling. If the 'naive' option is chosen, - * this rank-approximate search will be done by randomly sampling from the whole - * set. If the 'naive' option is not chosen, the sampling is done in a - * stratified manner in the tree as mentioned in the algorithms in Figure 2 of - * the following paper: - * - * @inproceedings{ram2009rank, - * title={{Rank-Approximate Nearest Neighbor Search: Retaining Meaning and - * Speed in High Dimensions}}, - * author={{Ram, P. and Lee, D. and Ouyang, H. and Gray, A. G.}}, - * booktitle={{Advances of Neural Information Processing Systems}}, - * year={2009} - * } - * - * RASearch is currently known to not work with ball trees (#356). - * - * @tparam SortPolicy The sort policy for distances; see NearestNeighborSort. - * @tparam MetricType The metric to use for computation. - * @tparam TreeType The tree type to use. - */ -template class TreeType = tree::KDTree> -class RASearch -{ - public: - //! Convenience typedef. - typedef TreeType, MatType> Tree; - - /** - * Initialize the RASearch object, passing both a reference dataset (this is - * the dataset that will be searched). Optionally, perform the computation in - * naive mode or single-tree mode. An initialized distance metric can be - * given, for cases where the metric has internal data (i.e. the - * distance::MahalanobisDistance class). - * - * This method will copy the matrices to internal copies, which are rearranged - * during tree-building. If you don't need to keep the reference dataset, - * you can use std::move() to remove the overhead of making copies. Using - * std::move() transfers the ownership of the dataset. - * - * tau, the rank-approximation parameter, specifies that we are looking for k - * neighbors with probability alpha of being in the top tau percent of nearest - * neighbors. So, as an example, if our dataset has 1000 points, and we want - * 5 nearest neighbors with 95% probability of being in the top 5% of nearest - * neighbors (or, the top 50 nearest neighbors), we set k = 5, tau = 5, and - * alpha = 0.95. - * - * The method will fail (and throw a std::invalid_argument exception) if the - * value of tau is too low: tau must be set such that the number of points in - * the corresponding percentile of the data is greater than k. Thus, if we - * choose tau = 0.1 with a dataset of 1000 points and k = 5, then we are - * attempting to choose 5 nearest neighbors out of the closest 1 point -- this - * is invalid. - * - * @param referenceSet Set of reference points. - * @param naive If true, the rank-approximate search will be performed by - * directly sampling the whole set instead of using the stratified - * sampling on the tree. - * @param singleMode If true, single-tree search will be used (as opposed to - * dual-tree search). This is useful when Search() will be called with - * few query points. - * @param metric An optional instance of the MetricType class. - * @param tau The rank-approximation in percentile of the data. The default - * value is 5%. - * @param alpha The desired success probability. The default value is 0.95. - * @param sampleAtLeaves Sample at leaves for faster but less accurate - * computation. This defaults to 'false'. - * @param firstLeafExact Traverse to the first leaf without approximation. - * This can ensure that the query definitely finds its (near) duplicate - * if there exists one. This defaults to 'false' for now. - * @param singleSampleLimit The limit on the largest node that can be - * approximated by sampling. This defaults to 20. - */ - RASearch(MatType referenceSet, - const bool naive = false, - const bool singleMode = false, - const double tau = 5, - const double alpha = 0.95, - const bool sampleAtLeaves = false, - const bool firstLeafExact = false, - const size_t singleSampleLimit = 20, - const MetricType metric = MetricType()); - - /** - * Initialize the RASearch object with the given pre-constructed reference - * tree. It is assumed that the points in the tree's dataset correspond to - * the reference set. Optionally, choose to use single-tree mode. Naive mode - * is not available as an option for this constructor; instead, to run naive - * computation, use a different constructor. Additionally, an instantiated - * distance metric can be given, for cases where the distance metric holds - * data. - * - * There is no copying of the data matrices in this constructor (because - * tree-building is not necessary), so this is the constructor to use when - * copies absolutely must be avoided. - * - * tau, the rank-approximation parameter, specifies that we are looking for k - * neighbors with probability alpha of being in the top tau percent of nearest - * neighbors. So, as an example, if our dataset has 1000 points, and we want - * 5 nearest neighbors with 95% probability of being in the top 5% of nearest - * neighbors (or, the top 50 nearest neighbors), we set k = 5, tau = 5, and - * alpha = 0.95. - * - * The method will fail (and throw a std::invalid_argument exception) if the - * value of tau is too low: tau must be set such that the number of points in - * the corresponding percentile of the data is greater than k. Thus, if we - * choose tau = 0.1 with a dataset of 1000 points and k = 5, then we are - * attempting to choose 5 nearest neighbors out of the closest 1 point -- this - * is invalid. - * - * @note - * Tree-building may (at least with BinarySpaceTree) modify the ordering - * of a matrix, so be aware that the results you get from Search() will - * correspond to the modified matrix. - * @endnote - * - * @param referenceTree Pre-built tree for reference points. - * @param singleMode Whether single-tree computation should be used (as - * opposed to dual-tree computation). - * @param tau The rank-approximation in percentile of the data. The default - * value is 5%. - * @param alpha The desired success probability. The default value is 0.95. - * @param sampleAtLeaves Sample at leaves for faster but less accurate - * computation. This defaults to 'false'. - * @param firstLeafExact Traverse to the first leaf without approximation. - * This can ensure that the query definitely finds its (near) duplicate - * if there exists one. This defaults to 'false' for now. - * @param singleSampleLimit The limit on the largest node that can be - * approximated by sampling. This defaults to 20. - * @param metric Instantiated distance metric. - */ - RASearch(Tree* referenceTree, - const bool singleMode = false, - const double tau = 5, - const double alpha = 0.95, - const bool sampleAtLeaves = false, - const bool firstLeafExact = false, - const size_t singleSampleLimit = 20, - const MetricType metric = MetricType()); - - /** - * Create an RASearch object with no reference data. If Search() is called - * before a reference set is set with Train(), an exception will be thrown. - * - * @param naive Whether naive (brute-force) search should be used. - * @param singleMode Whether single-tree computation should be used (as - * opposed to dual-tree computation). - * @param tau The rank-approximation in percentile of the data. The default - * value is 5%. - * @param alpha The desired success probability. The default value is 0.95. - * @param sampleAtLeaves Sample at leaves for faster but less accurate - * computation. This defaults to 'false'. - * @param firstLeafExact Traverse to the first leaf without approximation. - * This can ensure that the query definitely finds its (near) duplicate - * if there exists one. This defaults to 'false' for now. - * @param singleSampleLimit The limit on the largest node that can be - * approximated by sampling. This defaults to 20. - * @param metric Instantiated distance metric. - */ - RASearch(const bool naive = false, - const bool singleMode = false, - const double tau = 5, - const double alpha = 0.95, - const bool sampleAtLeaves = false, - const bool firstLeafExact = false, - const size_t singleSampleLimit = 20, - const MetricType metric = MetricType()); - - /** - * Delete the RASearch object. The tree is the only member we are - * responsible for deleting. The others will take care of themselves. - */ - ~RASearch(); - - /** - * "Train" the model on the given reference set. If tree-based search is - * being used (if Naive() is false), the reference tree is rebuilt. Thus, a - * copy of the reference dataset is made. If you don't need to keep the - * dataset, you can avoid copying by using std::move(). This transfers the - * ownership of the dataset. - * - * @param referenceSet New reference set to use. - */ - void Train(MatType referenceSet); - - /** - * Set the reference tree to a new reference tree. - */ - void Train(Tree* referenceTree); - - /** - * Compute the rank approximate nearest neighbors of each query point in the - * query set and store the output in the given matrices. The matrices will be - * set to the size of n columns by k rows, where n is the number of points in - * the query dataset and k is the number of neighbors being searched for. - * - * If querySet is small or only contains one point, it can be faster to do - * single-tree search; single-tree search can be set with the SingleMode() - * function or in the constructor. - * - * @param querySet Set of query points (can be a single point). - * @param k Number of neighbors to search for. - * @param neighbors Matrix storing lists of neighbors for each query point. - * @param distances Matrix storing distances of neighbors for each query - * point. - */ - void Search(const MatType& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - /** - * Compute the rank approximate nearest neighbors of each point in the - * pre-built query tree and store the output in the given matrices. The - * matrices will be set to the size of n columns by k rows, where n is the - * number of points in the query dataset and k is the number of neighbors - * being searched for. - * - * If singleMode or naive is enabled, then this method will throw a - * std::invalid_argument exception; calling this function implies a dual-tree - * algorithm. - * - * @note - * If the tree type you are using modifies the data matrix, be aware that the - * results returned from this function will be with respect to the modified - * data matrix. - * @endnote - * - * @param queryTree Tree built on query points. - * @param k Number of neighbors to search for. - * @param neighbors Matrix storing lists of neighbors for each query point. - * @param distances Matrix storing distances of neighbors for each query - * point. - */ - void Search(Tree* queryTree, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - /** - * Compute the rank approximate nearest neighbors of each point in the - * reference set (that is, the query set is taken to be the reference set), - * and store the output in the given matrices. The matrices will be set to - * the size of n columns by k rows, where n is the number of points in the - * query dataset and k is the number of neighbors being searched for. - * - * @param k Number of neighbors to search for. - * @param neighbors Matrix storing lists of neighbors for each point. - * @param distances Matrix storing distances of neighbors for each query - * point. - */ - void Search(const size_t k, - arma::Mat& neighbors, - arma::mat& distances); - - /** - * This function recursively resets the RAQueryStat of the given query tree to - * set 'bound' to SortPolicy::WorstDistance and 'numSamplesMade' to 0. This - * allows a user to perform multiple searches with the same query tree, - * possibly with different levels of approximation without requiring to build - * a new pair of trees for every new (approximate) search. - * - * If Search() is called multiple times with the same query tree without - * calling ResetQueryTree(), the results may not satisfy the theoretical - * guarantees provided by the rank-approximate neighbor search algorithm. - * - * @param queryTree Tree whose statistics should be reset. - */ - void ResetQueryTree(Tree* queryTree) const; - - //! Access the reference set. - const MatType& ReferenceSet() const { return *referenceSet; } - - //! Get whether or not naive (brute-force) search is used. - bool Naive() const { return naive; } - //! Modify whether or not naive (brute-force) search is used. - bool& Naive() { return naive; } - - //! Get whether or not single-tree search is used. - bool SingleMode() const { return singleMode; } - //! Modify whether or not single-tree search is used. - bool& SingleMode() { return singleMode; } - - //! Get the rank-approximation in percentile of the data. - double Tau() const { return tau; } - //! Modify the rank-approximation in percentile of the data. - double& Tau() { return tau; } - - //! Get the desired success probability. - double Alpha() const { return alpha; } - //! Modify the desired success probability. - double& Alpha() { return alpha; } - - //! Get whether or not sampling is done at the leaves. - bool SampleAtLeaves() const { return sampleAtLeaves; } - //! Modify whether or not sampling is done at the leaves. - bool& SampleAtLeaves() { return sampleAtLeaves; } - - //! Get whether or not we traverse to the first leaf without approximation. - bool FirstLeafExact() const { return firstLeafExact; } - //! Modify whether or not we traverse to the first leaf without approximation. - bool& FirstLeafExact() { return firstLeafExact; } - - //! Get the limit on the size of a node that can be approximated. - size_t SingleSampleLimit() const { return singleSampleLimit; } - //! Modify the limit on the size of a node that can be approximation. - size_t& SingleSampleLimit() { return singleSampleLimit; } - - //! Serialize the object. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Permutations of reference points during tree building. - std::vector oldFromNewReferences; - //! Pointer to the root of the reference tree. - Tree* referenceTree; - //! Reference dataset. In some situations we may own this dataset. - const MatType* referenceSet; - - //! If true, this object created the trees and is responsible for them. - bool treeOwner; - //! If true, we are responsible for deleting the dataset. - bool setOwner; - - //! Indicates if naive random sampling on the set is being used. - bool naive; - //! Indicates if single-tree search is being used (opposed to dual-tree). - bool singleMode; - - //! The rank-approximation in percentile of the data (between 0 and 100). - double tau; - //! The desired success probability (between 0 and 1). - double alpha; - //! Whether or not sampling is done at the leaves. Faster, but less accurate. - bool sampleAtLeaves; - //! If true, we will traverse to the first leaf without approximation. - bool firstLeafExact; - //! The limit on the number of points in the largest node that can be - //! approximated by sampling. - size_t singleSampleLimit; - - //! Instantiation of kernel. - MetricType metric; - - //! For access to mappings when building models. - template - friend class TrainVisitor; -}; // class RASearch - -} // namespace neighbor -} // namespace mlpack - -// Include implementation. -#include "ra_search_impl.hpp" - -// Include convenient typedefs. -#include "ra_typedef.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_impl.hpp deleted file mode 100644 index c74032937..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_impl.hpp +++ /dev/null @@ -1,679 +0,0 @@ -/** - * @file ra_search_impl.hpp - * @author Parikshit Ram - * - * Implementation of RASearch class to perform rank-approximate - * all-nearest-neighbors on two specified data sets. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANN_RA_SEARCH_IMPL_HPP -#define MLPACK_METHODS_RANN_RA_SEARCH_IMPL_HPP - -#include - -#include "ra_search_rules.hpp" - -namespace mlpack { -namespace neighbor { - -namespace aux { - -//! Call the tree constructor that does mapping. -template -TreeType* BuildTree( - MatType&& dataset, - std::vector& oldFromNew, - typename std::enable_if< - tree::TreeTraits::RearrangesDataset>::type* = 0) -{ - return new TreeType(std::forward(dataset), oldFromNew); -} - -//! Call the tree constructor that does not do mapping. -template -TreeType* BuildTree( - MatType&& dataset, - const std::vector& /* oldFromNew */, - const typename std::enable_if< - !tree::TreeTraits::RearrangesDataset>::type* = 0) -{ - return new TreeType(std::forward(dataset)); -} - -} // namespace aux - -// Construct the object, taking ownership of the data matrix. -template class TreeType> -RASearch:: -RASearch(MatType referenceSetIn, - const bool naive, - const bool singleMode, - const double tau, - const double alpha, - const bool sampleAtLeaves, - const bool firstLeafExact, - const size_t singleSampleLimit, - const MetricType metric) : - referenceTree(naive ? NULL : aux::BuildTree( - std::move(referenceSetIn), oldFromNewReferences)), - referenceSet(naive ? new MatType(std::move(referenceSetIn)) : - &referenceTree->Dataset()), - treeOwner(!naive), - setOwner(naive), - naive(naive), - singleMode(!naive && singleMode), // No single mode if naive. - tau(tau), - alpha(alpha), - sampleAtLeaves(sampleAtLeaves), - firstLeafExact(firstLeafExact), - singleSampleLimit(singleSampleLimit), - metric(metric) -{ - // Nothing to do. -} - -// Construct the object. -template class TreeType> -RASearch:: -RASearch(Tree* referenceTree, - const bool singleMode, - const double tau, - const double alpha, - const bool sampleAtLeaves, - const bool firstLeafExact, - const size_t singleSampleLimit, - const MetricType metric) : - referenceTree(referenceTree), - referenceSet(&referenceTree->Dataset()), - treeOwner(false), - setOwner(false), - naive(false), - singleMode(singleMode), - tau(tau), - alpha(alpha), - sampleAtLeaves(sampleAtLeaves), - firstLeafExact(firstLeafExact), - singleSampleLimit(singleSampleLimit), - metric(metric) -// Nothing else to initialize. -{ } - -// Empty constructor. -template class TreeType> -RASearch:: -RASearch(const bool naive, - const bool singleMode, - const double tau, - const double alpha, - const bool sampleAtLeaves, - const bool firstLeafExact, - const size_t singleSampleLimit, - const MetricType metric) : - referenceTree(NULL), - referenceSet(new MatType()), - treeOwner(false), - setOwner(true), - naive(naive), - singleMode(singleMode), - tau(tau), - alpha(alpha), - sampleAtLeaves(sampleAtLeaves), - firstLeafExact(firstLeafExact), - singleSampleLimit(singleSampleLimit), - metric(metric) -{ - // Build the tree on the empty dataset, if necessary. - if (!naive) - { - referenceTree = aux::BuildTree(*referenceSet, oldFromNewReferences); - treeOwner = true; - } -} - -/** - * The tree and the dataset are the only members we may be responsible for - * deleting. The others will take care of themselves. - */ -template class TreeType> -RASearch:: -~RASearch() -{ - if (treeOwner && referenceTree) - delete referenceTree; - if (setOwner) - delete referenceSet; -} - -// Train on a new reference set. -template class TreeType> -void RASearch::Train( - MatType referenceSet) -{ - // Clean up the old tree, if we built one. - if (treeOwner && referenceTree) - delete referenceTree; - - // We may need to rebuild the tree. - if (!naive) - { - referenceTree = aux::BuildTree(std::move(referenceSet), - oldFromNewReferences); - treeOwner = true; - } - else - { - treeOwner = false; - } - - // Delete the old reference set, if we owned it. - if (setOwner && this->referenceSet) - delete this->referenceSet; - - if (!naive) - { - this->referenceSet = &referenceTree->Dataset(); - setOwner = false; - } - else - { - this->referenceSet = new MatType(std::move(referenceSet)); - setOwner = true; - } -} - -//! Set the reference tree to a new reference tree. -template class TreeType> -void RASearch::Train( - Tree* referenceTree) -{ - if (naive) - throw std::invalid_argument("cannot train on given reference tree when " - "naive search (without trees) is desired"); - - if (treeOwner && referenceTree) - delete this->referenceTree; - if (setOwner && referenceSet) - delete this->referenceSet; - - this->referenceTree = referenceTree; - this->referenceSet = &referenceTree->Dataset(); - treeOwner = false; - setOwner = false; -} - -/** - * Computes the best neighbors and stores them in resultingNeighbors and - * distances. - */ -template class TreeType> -void RASearch:: -Search(const MatType& querySet, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - if (k > referenceSet->n_cols) - { - std::stringstream ss; - ss << "requested value of k (" << k << ") is greater than the number of " - << "points in the reference set (" << referenceSet->n_cols << ")"; - throw std::invalid_argument(ss.str()); - } - - Timer::Start("computing_neighbors"); - - // This will hold mappings for query points, if necessary. - std::vector oldFromNewQueries; - - // If we have built the trees ourselves, then we will have to map all the - // indices back to their original indices when this computation is finished. - // To avoid an extra copy, we will store the neighbors and distances in a - // separate matrix. - arma::Mat* neighborPtr = &neighbors; - arma::mat* distancePtr = &distances; - - // Mapping is only required if this tree type rearranges points and we are not - // in naive mode. - if (tree::TreeTraits::RearrangesDataset) - { - if (!singleMode && !naive) - { - distancePtr = new arma::mat; // Query indices need to be mapped. - neighborPtr = new arma::Mat; - } - - else if (treeOwner) - neighborPtr = new arma::Mat; // All indices need mapping. - } - - // Set the size of the neighbor and distance matrices. - neighborPtr->set_size(k, querySet.n_cols); - distancePtr->set_size(k, querySet.n_cols); - - typedef RASearchRules RuleType; - - if (naive) - { - RuleType rules(*referenceSet, querySet, k, metric, tau, alpha, naive, - sampleAtLeaves, firstLeafExact, singleSampleLimit, false); - - // Find how many samples from the reference set we need and sample uniformly - // from the reference set without replacement. - const size_t numSamples = RAUtil::MinimumSamplesReqd(referenceSet->n_cols, - k, tau, alpha); - arma::uvec distinctSamples; - math::ObtainDistinctSamples(0, referenceSet->n_cols, numSamples, - distinctSamples); - - // Run the base case on each combination of query point and sampled - // reference point. - for (size_t i = 0; i < querySet.n_cols; ++i) - for (size_t j = 0; j < distinctSamples.n_elem; ++j) - rules.BaseCase(i, (size_t) distinctSamples[j]); - - rules.GetResults(*neighborPtr, *distancePtr); - } - else if (singleMode) - { - RuleType rules(*referenceSet, querySet, k, metric, tau, alpha, naive, - sampleAtLeaves, firstLeafExact, singleSampleLimit, false); - - // If the reference root node is a leaf, then the sampling has already been - // done in the RASearchRules constructor. This happens when naive = true. - if (!referenceTree->IsLeaf()) - { - Log::Info << "Performing single-tree traversal..." << std::endl; - - // Create the traverser. - typename Tree::template SingleTreeTraverser traverser(rules); - - // Now have it traverse for each point. - for (size_t i = 0; i < querySet.n_cols; ++i) - traverser.Traverse(i, *referenceTree); - - Log::Info << "Single-tree traversal complete." << std::endl; - Log::Info << "Average number of distance calculations per query point: " - << (rules.NumDistComputations() / querySet.n_cols) << "." - << std::endl; - } - - rules.GetResults(*neighborPtr, *distancePtr); - } - else // Dual-tree recursion. - { - Log::Info << "Performing dual-tree traversal..." << std::endl; - - // Build the query tree. - Timer::Stop("computing_neighbors"); - Timer::Start("tree_building"); - Tree* queryTree = aux::BuildTree(const_cast(querySet), - oldFromNewQueries); - Timer::Stop("tree_building"); - Timer::Start("computing_neighbors"); - - RuleType rules(*referenceSet, queryTree->Dataset(), k, metric, tau, alpha, - naive, sampleAtLeaves, firstLeafExact, singleSampleLimit, false); - typename Tree::template DualTreeTraverser traverser(rules); - - Log::Info << "Query statistic pre-search: " - << queryTree->Stat().NumSamplesMade() << std::endl; - - traverser.Traverse(*queryTree, *referenceTree); - - Log::Info << "Dual-tree traversal complete." << std::endl; - Log::Info << "Average number of distance calculations per query point: " - << (rules.NumDistComputations() / querySet.n_cols) << "." << std::endl; - - rules.GetResults(*neighborPtr, *distancePtr); - - delete queryTree; - } - - Timer::Stop("computing_neighbors"); - - // Map points back to original indices, if necessary. - if (tree::TreeTraits::RearrangesDataset) - { - if (!singleMode && !naive && treeOwner) - { - // We must map both query and reference indices. - neighbors.set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - for (size_t i = 0; i < distances.n_cols; i++) - { - // Map distances (copy a column). - distances.col(oldFromNewQueries[i]) = distancePtr->col(i); - - // Map indices of neighbors. - for (size_t j = 0; j < distances.n_rows; j++) - { - neighbors(j, oldFromNewQueries[i]) = - oldFromNewReferences[(*neighborPtr)(j, i)]; - } - } - - // Finished with temporary matrices. - delete neighborPtr; - delete distancePtr; - } - else if (!singleMode && !naive) - { - // We must map query indices only. - neighbors.set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - for (size_t i = 0; i < distances.n_cols; ++i) - { - // Map distances (copy a column). - const size_t queryMapping = oldFromNewQueries[i]; - distances.col(queryMapping) = distancePtr->col(i); - neighbors.col(queryMapping) = neighborPtr->col(i); - } - - // Finished with temporary matrices. - delete neighborPtr; - delete distancePtr; - } - else if (treeOwner) - { - // We must map reference indices only. - neighbors.set_size(k, querySet.n_cols); - - // Map indices of neighbors. - for (size_t i = 0; i < neighbors.n_cols; i++) - for (size_t j = 0; j < neighbors.n_rows; j++) - neighbors(j, i) = oldFromNewReferences[(*neighborPtr)(j, i)]; - - // Finished with temporary matrix. - delete neighborPtr; - } - } -} - -template class TreeType> -void RASearch::Search( - Tree* queryTree, - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - Timer::Start("computing_neighbors"); - - // Get a reference to the query set. - const MatType& querySet = queryTree->Dataset(); - - // Make sure we are in dual-tree mode. - if (singleMode || naive) - throw std::invalid_argument("cannot call NeighborSearch::Search() with a " - "query tree when naive or singleMode are set to true"); - - // We won't need to map query indices, but will we need to map distances? - arma::Mat* neighborPtr = &neighbors; - - if (treeOwner && tree::TreeTraits::RearrangesDataset) - neighborPtr = new arma::Mat; - - neighborPtr->set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - // Create the helper object for the tree traversal. - typedef RASearchRules RuleType; - RuleType rules(*referenceSet, queryTree->Dataset(), k, metric, tau, alpha, - naive, sampleAtLeaves, firstLeafExact, singleSampleLimit, false); - - // Create the traverser. - typename Tree::template DualTreeTraverser traverser(rules); - traverser.Traverse(*queryTree, *referenceTree); - - rules.GetResults(*neighborPtr, distances); - - Timer::Stop("computing_neighbors"); - - // Do we need to map indices? - if (treeOwner && tree::TreeTraits::RearrangesDataset) - { - // We must map reference indices only. - neighbors.set_size(k, querySet.n_cols); - - // Map indices of neighbors. - for (size_t i = 0; i < neighbors.n_cols; i++) - for (size_t j = 0; j < neighbors.n_rows; j++) - neighbors(j, i) = oldFromNewReferences[(*neighborPtr)(j, i)]; - - // Finished with temporary matrix. - delete neighborPtr; - } -} - -template class TreeType> -void RASearch::Search( - const size_t k, - arma::Mat& neighbors, - arma::mat& distances) -{ - Timer::Start("computing_neighbors"); - - arma::Mat* neighborPtr = &neighbors; - arma::mat* distancePtr = &distances; - - if (tree::TreeTraits::RearrangesDataset && treeOwner) - { - // We will always need to rearrange in this case. - distancePtr = new arma::mat; - neighborPtr = new arma::Mat; - } - - // Initialize results. - neighborPtr->set_size(k, referenceSet->n_cols); - distancePtr->set_size(k, referenceSet->n_cols); - - // Create the helper object for the tree traversal. - typedef RASearchRules RuleType; - RuleType rules(*referenceSet, *referenceSet, k, metric, tau, alpha, naive, - sampleAtLeaves, firstLeafExact, singleSampleLimit, true /* same sets */); - - if (naive) - { - // Find how many samples from the reference set we need and sample uniformly - // from the reference set without replacement. - const size_t numSamples = RAUtil::MinimumSamplesReqd(referenceSet->n_cols, - k, tau, alpha); - arma::uvec distinctSamples; - math::ObtainDistinctSamples(0, referenceSet->n_cols, numSamples, - distinctSamples); - - // The naive brute-force solution. - for (size_t i = 0; i < referenceSet->n_cols; ++i) - for (size_t j = 0; j < referenceSet->n_cols; ++j) - rules.BaseCase(i, j); - } - else if (singleMode) - { - // Create the traverser. - typename Tree::template SingleTreeTraverser traverser(rules); - - // Now have it traverse for each point. - for (size_t i = 0; i < referenceSet->n_cols; ++i) - traverser.Traverse(i, *referenceTree); - } - else - { - // Create the traverser. - typename Tree::template DualTreeTraverser traverser(rules); - - traverser.Traverse(*referenceTree, *referenceTree); - } - - rules.GetResults(*neighborPtr, *distancePtr); - - Timer::Stop("computing_neighbors"); - - // Do we need to map the reference indices? - if (treeOwner && tree::TreeTraits::RearrangesDataset) - { - neighbors.set_size(k, referenceSet->n_cols); - distances.set_size(k, referenceSet->n_cols); - - for (size_t i = 0; i < distances.n_cols; ++i) - { - // Map distances (copy a column). - const size_t refMapping = oldFromNewReferences[i]; - distances.col(refMapping) = distancePtr->col(i); - - // Map each neighbor's index. - for (size_t j = 0; j < distances.n_rows; ++j) - neighbors(j, refMapping) = oldFromNewReferences[(*neighborPtr)(j, i)]; - } - - // Finished with temporary matrices. - delete neighborPtr; - delete distancePtr; - } -} - -template class TreeType> -void RASearch::ResetQueryTree( - Tree* queryNode) const -{ - queryNode->Stat().Bound() = SortPolicy::WorstDistance(); - queryNode->Stat().NumSamplesMade() = 0; - - for (size_t i = 0; i < queryNode->NumChildren(); i++) - ResetQueryTree(&queryNode->Child(i)); -} - -template class TreeType> -template -void RASearch::serialize( - Archive& ar, - const unsigned int /* version */) -{ - // Serialize preferences for search. - ar & BOOST_SERIALIZATION_NVP(naive); - ar & BOOST_SERIALIZATION_NVP(singleMode); - - ar & BOOST_SERIALIZATION_NVP(tau); - ar & BOOST_SERIALIZATION_NVP(alpha); - ar & BOOST_SERIALIZATION_NVP(sampleAtLeaves); - ar & BOOST_SERIALIZATION_NVP(firstLeafExact); - ar & BOOST_SERIALIZATION_NVP(singleSampleLimit); - - // If we are doing naive search, we serialize the dataset. Otherwise we - // serialize the tree. - if (naive) - { - if (Archive::is_loading::value) - { - if (setOwner && referenceSet) - delete referenceSet; - - setOwner = true; - } - - ar & BOOST_SERIALIZATION_NVP(referenceSet); - ar & BOOST_SERIALIZATION_NVP(metric); - - // If we are loading, set the tree to NULL and clean up memory if necessary. - if (Archive::is_loading::value) - { - if (treeOwner && referenceTree) - delete referenceTree; - - referenceTree = NULL; - oldFromNewReferences.clear(); - treeOwner = false; - } - } - else - { - // Delete the current reference tree, if necessary and if we are loading. - if (Archive::is_loading::value) - { - if (treeOwner && referenceTree) - delete referenceTree; - - // After we load the tree, we will own it. - treeOwner = true; - } - - ar & BOOST_SERIALIZATION_NVP(referenceTree); - ar & BOOST_SERIALIZATION_NVP(oldFromNewReferences); - - // If we are loading, set the dataset accordingly and clean up memory if - // necessary. - if (Archive::is_loading::value) - { - if (setOwner && referenceSet) - delete referenceSet; - - referenceSet = &referenceTree->Dataset(); - metric = referenceTree->Metric(); - setOwner = false; - } - } -} - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_rules.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_rules.hpp deleted file mode 100644 index d9d530d1e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_rules.hpp +++ /dev/null @@ -1,338 +0,0 @@ -/** - * @file ra_search_rules.hpp - * @author Parikshit Ram - * - * Defines the pruning rules and base case rules necessary to perform a - * tree-based rank-approximate search (with an arbitrary tree) for the RASearch - * class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANN_RA_SEARCH_RULES_HPP -#define MLPACK_METHODS_RANN_RA_SEARCH_RULES_HPP - -#include - -#include - -namespace mlpack { -namespace neighbor { - -/** - * The RASearchRules class is a template helper class used by RASearch class - * when performing rank-approximate search via random-sampling. - * - * @tparam SortPolicy The sort policy for distances. - * @tparam MetricType The metric to use for computation. - * @tparam TreeType The tree type to use; must adhere to the TreeType API. - */ -template -class RASearchRules -{ - public: - /** - * Construct the RASearchRules object. This is usually done from within - * the RASearch class at search time. - * - * @param referenceSet Set of reference data. - * @param querySet Set of query data. - * @param k Number of neighbors to search for. - * @param metric Instantiated metric. - * @param tau The rank-approximation in percentile of the data. - * @param alpha The desired success probability. - * @param naive If true, the rank-approximate search will be performed by - * directly sampling the whole set instead of using the stratified - * sampling on the tree. - * @param sampleAtLeaves Sample at leaves for faster but less accurate - * computation. - * @param firstLeafExact Traverse to the first leaf without approximation. - * @param singleSampleLimit The limit on the largest node that can be - * approximated by sampling. - * @param sameSet If true, the query and reference set are taken to be the - * same, and a query point will not return itself in the results. - */ - RASearchRules(const arma::mat& referenceSet, - const arma::mat& querySet, - const size_t k, - MetricType& metric, - const double tau = 5, - const double alpha = 0.95, - const bool naive = false, - const bool sampleAtLeaves = false, - const bool firstLeafExact = false, - const size_t singleSampleLimit = 20, - const bool sameSet = false); - - /** - * Store the list of candidates for each query point in the given matrices. - * - * @param neighbors Matrix storing lists of neighbors for each query point. - * @param distances Matrix storing distances of neighbors for each query - * point. - */ - void GetResults(arma::Mat& neighbors, arma::mat& distances); - - /** - * Get the distance from the query point to the reference point. - * This will update the list of candidates with the new point if appropriate. - * - * @param queryIndex Index of query point. - * @param referenceIndex Index of reference point. - */ - double BaseCase(const size_t queryIndex, const size_t referenceIndex); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * For rank-approximation, the scoring function first checks if pruning - * by distance is possible. - * If yes, then the node is given the score of - * 'DBL_MAX' and the expected number of samples from that node are - * added to the number of samples made for the query. - * - * If no, then the function tries to see if the node can be pruned by - * approximation. If number of samples required from this node is small - * enough, then that number of samples are acquired from this node - * and the score is set to be 'DBL_MAX'. - * - * If the pruning by approximation is not possible either, the algorithm - * continues with the usual tree-traversal. - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - */ - double Score(const size_t queryIndex, TreeType& referenceNode); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursion, while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * For rank-approximation, the scoring function first checks if pruning - * by distance is possible. - * If yes, then the node is given the score of - * 'DBL_MAX' and the expected number of samples from that node are - * added to the number of samples made for the query. - * - * If no, then the function tries to see if the node can be pruned by - * approximation. If number of samples required from this node is small - * enough, then that number of samples are acquired from this node - * and the score is set to be 'DBL_MAX'. - * - * If the pruning by approximation is not possible either, the algorithm - * continues with the usual tree-traversal. - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - * @param baseCaseResult Result of BaseCase(queryIndex, referenceNode). - */ - double Score(const size_t queryIndex, - TreeType& referenceNode, - const double baseCaseResult); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that the node should not be - * recursed into at all (it should be pruned). This is used when the score - * has already been calculated, but another recursion may have modified the - * bounds for pruning. So the old score is checked against the new pruning - * bound. - * - * For rank-approximation, it also checks if the number of samples left - * for a query to satisfy the rank constraint is small enough at this - * point of the algorithm, then this node is approximated by sampling - * and given a new score of 'DBL_MAX'. - * - * @param queryIndex Index of query point. - * @param referenceNode Candidate node to be recursed into. - * @param oldScore Old score produced by Score() (or Rescore()). - */ - double Rescore(const size_t queryIndex, - TreeType& referenceNode, - const double oldScore); - - /** - * Get the score for recursion order. A low score indicates priority for - * recursionm while DBL_MAX indicates that the node should not be recursed - * into at all (it should be pruned). - * - * For the rank-approximation, we check if the referenceNode can be - * approximated by sampling. If it can be, enough samples are made for - * every query in the queryNode. No further query-tree traversal is - * performed. - * - * The 'NumSamplesMade' query stat is propagated up the tree. And then - * if pruning occurs (by distance or by sampling), the 'NumSamplesMade' - * stat is not propagated down the tree. If no pruning occurs, the - * stat is propagated down the tree. - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - */ - double Score(TreeType& queryNode, TreeType& referenceNode); - - /** - * Get the score for recursion order, passing the base case result (in the - * situation where it may be needed to calculate the recursion order). A low - * score indicates priority for recursion, while DBL_MAX indicates that the - * node should not be recursed into at all (it should be pruned). - * - * For the rank-approximation, we check if the referenceNode can be - * approximated by sampling. If it can be, enough samples are made for - * every query in the queryNode. No further query-tree traversal is - * performed. - * - * The 'NumSamplesMade' query stat is propagated up the tree. And then - * if pruning occurs (by distance or by sampling), the 'NumSamplesMade' - * stat is not propagated down the tree. If no pruning occurs, the - * stat is propagated down the tree. - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - * @param baseCaseResult Result of BaseCase(queryIndex, referenceNode). - */ - double Score(TreeType& queryNode, - TreeType& referenceNode, - const double baseCaseResult); - - /** - * Re-evaluate the score for recursion order. A low score indicates priority - * for recursion, while DBL_MAX indicates that the node should not be - * recursed into at all (it should be pruned). This is used when the score - * has already been calculated, but another recursion may have modified the - * bounds for pruning. So the old score is checked against the new pruning - * bound. - * - * For the rank-approximation, we check if the referenceNode can be - * approximated by sampling. If it can be, enough samples are made for - * every query in the queryNode. No further query-tree traversal is - * performed. - * - * The 'NumSamplesMade' query stat is propagated up the tree. And then - * if pruning occurs (by distance or by sampling), the 'NumSamplesMade' - * stat is not propagated down the tree. If no pruning occurs, the - * stat is propagated down the tree. - * - * @param queryNode Candidate query node to recurse into. - * @param referenceNode Candidate reference node to recurse into. - * @param oldScore Old score produced by Socre() (or Rescore()). - */ - double Rescore(TreeType& queryNode, - TreeType& referenceNode, - const double oldScore); - - - size_t NumDistComputations() { return numDistComputations; } - size_t NumEffectiveSamples() - { - if (numSamplesMade.n_elem == 0) - return 0; - else - return arma::sum(numSamplesMade); - } - - typedef typename tree::TraversalInfo TraversalInfoType; - - const TraversalInfoType& TraversalInfo() const { return traversalInfo; } - TraversalInfoType& TraversalInfo() { return traversalInfo; } - - private: - //! The reference set. - const arma::mat& referenceSet; - - //! The query set. - const arma::mat& querySet; - - //! Candidate represents a possible candidate neighbor (distance, index). - typedef std::pair Candidate; - - //! Compare two candidates based on the distance. - struct CandidateCmp { - bool operator()(const Candidate& c1, const Candidate& c2) - { - return !SortPolicy::IsBetter(c2.first, c1.first); - }; - }; - - //! Use a priority queue to represent the list of candidate neighbors. - typedef std::priority_queue, CandidateCmp> - CandidateList; - - //! Set of candidate neighbors for each point. - std::vector candidates; - - //! Number of neighbors to search for. - const size_t k; - - //! The instantiated metric. - MetricType& metric; - - //! Whether to sample at leaves or just use all of it. - bool sampleAtLeaves; - - //! Whether to do exact computation on the first leaf before any sampling. - bool firstLeafExact; - - //! The limit on the largest node that can be approximated by sampling. - size_t singleSampleLimit; - - //! The minimum number of samples required per query. - size_t numSamplesReqd; - - //! The number of samples made for every query. - arma::Col numSamplesMade; - - //! The sampling ratio. - double samplingRatio; - - //! The number of distance calculations performed during search. - size_t numDistComputations; - - //! If the query and reference set are identical, this is true. - bool sameSet; - - TraversalInfoType traversalInfo; - - /** - * Helper function to insert a point into the list of candidate points. - * - * @param queryIndex Index of point whose neighbors we are inserting into. - * @param neighbor Index of reference point which is being inserted. - * @param distance Distance from query point to reference point. - */ - void InsertNeighbor(const size_t queryIndex, - const size_t neighbor, - const double distance); - - /** - * Perform actual scoring for single-tree case. - */ - double Score(const size_t queryIndex, - TreeType& referenceNode, - const double distance, - const double bestDistance); - - /** - * Perform actual scoring for dual-tree case. - */ - double Score(TreeType& queryNode, - TreeType& referenceNode, - const double distance, - const double bestDistance); - - static_assert(tree::TreeTraits::UniqueNumDescendants, "TreeType " - "must provide a unique number of descendants points."); -}; // class RASearchRules - -} // namespace neighbor -} // namespace mlpack - -// Include implementation. -#include "ra_search_rules_impl.hpp" - -#endif // MLPACK_METHODS_RANN_RA_SEARCH_RULES_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_rules_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_rules_impl.hpp deleted file mode 100644 index 2a617871b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_search_rules_impl.hpp +++ /dev/null @@ -1,828 +0,0 @@ -/** - * @file ra_search_rules_impl.hpp - * @author Parikshit Ram - * - * Implementation of RASearchRules. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANN_RA_SEARCH_RULES_IMPL_HPP -#define MLPACK_METHODS_RANN_RA_SEARCH_RULES_IMPL_HPP - -// In case it hasn't been included yet. -#include "ra_search_rules.hpp" - -namespace mlpack { -namespace neighbor { - -template -RASearchRules:: -RASearchRules(const arma::mat& referenceSet, - const arma::mat& querySet, - const size_t k, - MetricType& metric, - const double tau, - const double alpha, - const bool naive, - const bool sampleAtLeaves, - const bool firstLeafExact, - const size_t singleSampleLimit, - const bool sameSet) : - referenceSet(referenceSet), - querySet(querySet), - k(k), - metric(metric), - sampleAtLeaves(sampleAtLeaves), - firstLeafExact(firstLeafExact), - singleSampleLimit(singleSampleLimit), - sameSet(sameSet) -{ - // Validate tau to make sure that the rank approximation is greater than the - // number of neighbors requested. - - // The rank approximation. - const size_t n = referenceSet.n_cols; - const size_t t = (size_t) std::ceil(tau * (double) n / 100.0); - if (t < k) - { - Log::Warn << "Rank-approximation percentile " << tau << " corresponds to " - << t << " points, which is less than k (" << k << ")."; - Log::Fatal << "Cannot return " << k << " approximate nearest neighbors " - << "from the nearest " << t << " points. Increase tau!" << std::endl; - } - else if (t == k) - Log::Warn << "Rank-approximation percentile " << tau << " corresponds to " - << t << " points; because k = " << k << ", this is exact search!" - << std::endl; - - Timer::Start("computing_number_of_samples_reqd"); - numSamplesReqd = RAUtil::MinimumSamplesReqd(n, k, tau, alpha); - Timer::Stop("computing_number_of_samples_reqd"); - - // Initialize some statistics to be collected during the search. - numSamplesMade = arma::zeros >(querySet.n_cols); - numDistComputations = 0; - samplingRatio = (double) numSamplesReqd / (double) n; - - Log::Info << "Minimum samples required per query: " << numSamplesReqd << - ", sampling ratio: " << samplingRatio << std::endl; - - // Let's build the list of candidate neighbors for each query point. - // It will be initialized with k candidates: (WorstDistance, size_t() - 1) - // The list of candidates will be updated when visiting new points with the - // BaseCase() method. - const Candidate def = std::make_pair(SortPolicy::WorstDistance(), - size_t() - 1); - - std::vector vect(k, def); - CandidateList pqueue(CandidateCmp(), std::move(vect)); - - candidates.reserve(querySet.n_cols); - for (size_t i = 0; i < querySet.n_cols; i++) - candidates.push_back(pqueue); - - if (naive) // No tree traversal; just do naive sampling here. - { - // Sample enough points. - arma::uvec distinctSamples; - for (size_t i = 0; i < querySet.n_cols; ++i) - { - math::ObtainDistinctSamples(0, n, numSamplesReqd, distinctSamples); - for (size_t j = 0; j < distinctSamples.n_elem; j++) - BaseCase(i, (size_t) distinctSamples[j]); - } - } -} - -template -void RASearchRules::GetResults( - arma::Mat& neighbors, - arma::mat& distances) -{ - neighbors.set_size(k, querySet.n_cols); - distances.set_size(k, querySet.n_cols); - - for (size_t i = 0; i < querySet.n_cols; i++) - { - CandidateList& pqueue = candidates[i]; - for (size_t j = 1; j <= k; j++) - { - neighbors(k - j, i) = pqueue.top().second; - distances(k - j, i) = pqueue.top().first; - pqueue.pop(); - } - } -}; - -template -inline force_inline -double RASearchRules::BaseCase( - const size_t queryIndex, - const size_t referenceIndex) -{ - // If the datasets are the same, then this search is only using one dataset - // and we should not return identical points. - if (sameSet && (queryIndex == referenceIndex)) - return 0.0; - - double distance = metric.Evaluate(querySet.unsafe_col(queryIndex), - referenceSet.unsafe_col(referenceIndex)); - - InsertNeighbor(queryIndex, referenceIndex, distance); - - numSamplesMade[queryIndex]++; - - numDistComputations++; - - return distance; -} - -template -inline double RASearchRules::Score( - const size_t queryIndex, - TreeType& referenceNode) -{ - const arma::vec queryPoint = querySet.unsafe_col(queryIndex); - const double distance = SortPolicy::BestPointToNodeDistance(queryPoint, - &referenceNode); - const double bestDistance = candidates[queryIndex].top().first; - - return Score(queryIndex, referenceNode, distance, bestDistance); -} - -template -inline double RASearchRules::Score( - const size_t queryIndex, - TreeType& referenceNode, - const double baseCaseResult) -{ - const arma::vec queryPoint = querySet.unsafe_col(queryIndex); - const double distance = SortPolicy::BestPointToNodeDistance(queryPoint, - &referenceNode, baseCaseResult); - const double bestDistance = candidates[queryIndex].top().first; - - return Score(queryIndex, referenceNode, distance, bestDistance); -} - -template -inline double RASearchRules::Score( - const size_t queryIndex, - TreeType& referenceNode, - const double distance, - const double bestDistance) -{ - // If this is better than the best distance we've seen so far, maybe there - // will be something down this node. Also check if enough samples are already - // made for this query. - if (SortPolicy::IsBetter(distance, bestDistance) - && numSamplesMade[queryIndex] < numSamplesReqd) - { - // We cannot prune this node; try approximating it by sampling. - - // If we are required to visit the first leaf (to find possible duplicates), - // make sure we do not approximate. - if (numSamplesMade[queryIndex] > 0 || !firstLeafExact) - { - // Check if this node can be approximated by sampling. - size_t samplesReqd = (size_t) std::ceil(samplingRatio * - (double) referenceNode.NumDescendants()); - samplesReqd = std::min(samplesReqd, - numSamplesReqd - numSamplesMade[queryIndex]); - - if (samplesReqd > singleSampleLimit && !referenceNode.IsLeaf()) - { - // If too many samples required and not at a leaf, then can't prune. - return distance; - } - else - { - if (!referenceNode.IsLeaf()) - { - // Then samplesReqd <= singleSampleLimit. - // Hence, approximate the node by sampling enough number of points. - arma::uvec distinctSamples; - math::ObtainDistinctSamples(0, referenceNode.NumDescendants(), - samplesReqd, distinctSamples); - for (size_t i = 0; i < distinctSamples.n_elem; i++) - // The counting of the samples are done in the 'BaseCase' function - // so no book-keeping is required here. - BaseCase(queryIndex, referenceNode.Descendant(distinctSamples[i])); - - // Node approximated, so we can prune it. - return DBL_MAX; - } - else // We are at a leaf. - { - if (sampleAtLeaves) // If allowed to sample at leaves. - { - // Approximate node by sampling enough number of points. - arma::uvec distinctSamples; - math::ObtainDistinctSamples(0, referenceNode.NumDescendants(), - samplesReqd, distinctSamples); - for (size_t i = 0; i < distinctSamples.n_elem; i++) - // The counting of the samples are done in the 'BaseCase' function - // so no book-keeping is required here. - BaseCase(queryIndex, - referenceNode.Descendant(distinctSamples[i])); - - // (Leaf) node approximated, so we can prune it. - return DBL_MAX; - } - else - { - // Not allowed to sample from leaves, so cannot prune. - return distance; - } - } - } - } - else - { - // Try first to visit the first leaf to boost your accuracy and find - // (near) duplicates if they exist. - return distance; - } - } - else - { - // Either there cannot be anything better in this node, or enough number of - // samples are already made. So prune it. - - // Add 'fake' samples from this node; they are fake because the distances to - // these samples need not be computed. - - // If enough samples are already made, this step does not change the result - // of the search. - numSamplesMade[queryIndex] += (size_t) std::floor( - samplingRatio * (double) referenceNode.NumDescendants()); - - return DBL_MAX; - } -} - -template -inline double RASearchRules:: -Rescore(const size_t queryIndex, - TreeType& referenceNode, - const double oldScore) -{ - // If we are already pruning, still prune. - if (oldScore == DBL_MAX) - return oldScore; - - // Just check the score again against the distances. - const double bestDistance = candidates[queryIndex].top().first; - - // If this is better than the best distance we've seen so far, - // maybe there will be something down this node. - // Also check if enough samples are already made for this query. - if (SortPolicy::IsBetter(oldScore, bestDistance) - && numSamplesMade[queryIndex] < numSamplesReqd) - { - // We cannot prune this node; thus, we try approximating this node by - // sampling. - - // Here, we assume that since we are re-scoring, the algorithm has already - // sampled some candidates, and if specified, also traversed to the first - // leaf. So no check regarding that is made any more. - - // Check if this node can be approximated by sampling. - size_t samplesReqd = (size_t) std::ceil(samplingRatio * - (double) referenceNode.NumDescendants()); - samplesReqd = std::min(samplesReqd, numSamplesReqd - - numSamplesMade[queryIndex]); - - if (samplesReqd > singleSampleLimit && !referenceNode.IsLeaf()) - { - // If too many samples are required and we are not at a leaf, then we - // can't prune. - return oldScore; - } - else - { - if (!referenceNode.IsLeaf()) - { - // Then, samplesReqd <= singleSampleLimit. Hence, approximate the node - // by sampling enough number of points. - arma::uvec distinctSamples; - math::ObtainDistinctSamples(0, referenceNode.NumDescendants(), - samplesReqd, distinctSamples); - for (size_t i = 0; i < distinctSamples.n_elem; i++) - // The counting of the samples are done in the 'BaseCase' function so - // no book-keeping is required here. - BaseCase(queryIndex, referenceNode.Descendant(distinctSamples[i])); - - // Node approximated, so we can prune it. - return DBL_MAX; - } - else // We are at a leaf. - { - if (sampleAtLeaves) - { - // Approximate node by sampling enough points. - arma::uvec distinctSamples; - math::ObtainDistinctSamples(0, referenceNode.NumDescendants(), - samplesReqd, distinctSamples); - for (size_t i = 0; i < distinctSamples.n_elem; i++) - // The counting of the samples are done in the 'BaseCase' function - // so no book-keeping is required here. - BaseCase(queryIndex, referenceNode.Descendant(distinctSamples[i])); - - // (Leaf) node approximated, so we can prune it. - return DBL_MAX; - } - else - { - // We cannot sample from leaves, so we cannot prune. - return oldScore; - } - } - } - } - else - { - // Either there cannot be anything better in this node, or enough number of - // samples are already made, so prune it. - - // Add 'fake' samples from this node; they are fake because the distances to - // these samples need not be computed. If enough samples are already made, - // this step does not change the result of the search. - numSamplesMade[queryIndex] += (size_t) std::floor(samplingRatio * - (double) referenceNode.NumDescendants()); - - return DBL_MAX; - } -} // Rescore(point, node, oldScore) - -template -inline double RASearchRules::Score( - TreeType& queryNode, - TreeType& referenceNode) -{ - // First try to find the distance bound to check if we can prune by distance. - - // Calculate the best node-to-node distance. - const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode, - &referenceNode); - - double pointBound = DBL_MAX; - double childBound = DBL_MAX; - const double maxDescendantDistance = queryNode.FurthestDescendantDistance(); - - for (size_t i = 0; i < queryNode.NumPoints(); i++) - { - const double bound = candidates[queryNode.Point(i)].top().first - + maxDescendantDistance; - if (bound < pointBound) - pointBound = bound; - } - - for (size_t i = 0; i < queryNode.NumChildren(); i++) - { - const double bound = queryNode.Child(i).Stat().Bound(); - if (bound < childBound) - childBound = bound; - } - - // Update the bound. - queryNode.Stat().Bound() = std::min(pointBound, childBound); - const double bestDistance = queryNode.Stat().Bound(); - - return Score(queryNode, referenceNode, distance, bestDistance); -} - -template -inline double RASearchRules::Score( - TreeType& queryNode, - TreeType& referenceNode, - const double baseCaseResult) -{ - // First try to find the distance bound to check if we can prune - // by distance. - - // Find the best node-to-node distance. - const double distance = SortPolicy::BestNodeToNodeDistance(&queryNode, - &referenceNode, baseCaseResult); - - double pointBound = DBL_MAX; - double childBound = DBL_MAX; - const double maxDescendantDistance = queryNode.FurthestDescendantDistance(); - - for (size_t i = 0; i < queryNode.NumPoints(); i++) - { - const double bound = candidates[queryNode.Point(i)].top().first - + maxDescendantDistance; - if (bound < pointBound) - pointBound = bound; - } - - for (size_t i = 0; i < queryNode.NumChildren(); i++) - { - const double bound = queryNode.Child(i).Stat().Bound(); - if (bound < childBound) - childBound = bound; - } - - // update the bound - queryNode.Stat().Bound() = std::min(pointBound, childBound); - const double bestDistance = queryNode.Stat().Bound(); - - return Score(queryNode, referenceNode, distance, bestDistance); -} - -template -inline double RASearchRules::Score( - TreeType& queryNode, - TreeType& referenceNode, - const double distance, - const double bestDistance) -{ - // Update the number of samples made for this node -- propagate up from child - // nodes if child nodes have made samples that the parent node is not aware - // of. Remember, we must propagate down samples made to the child nodes if - // 'queryNode' descend is deemed necessary. - - // Only update from children if a non-leaf node, obviously. - if (!queryNode.IsLeaf()) - { - size_t numSamplesMadeInChildNodes = std::numeric_limits::max(); - - // Find the minimum number of samples made among all children. - for (size_t i = 0; i < queryNode.NumChildren(); i++) - { - const size_t numSamples = queryNode.Child(i).Stat().NumSamplesMade(); - if (numSamples < numSamplesMadeInChildNodes) - numSamplesMadeInChildNodes = numSamples; - } - - // The number of samples made for a node is propagated up from the child - // nodes if the child nodes have made samples that the parent (which is the - // current 'queryNode') is not aware of. - queryNode.Stat().NumSamplesMade() = std::max( - queryNode.Stat().NumSamplesMade(), numSamplesMadeInChildNodes); - } - - // Now check if the node-pair interaction can be pruned. - - // If this is better than the best distance we've seen so far, maybe there - // will be something down this node. Also check if enough samples are already - // made for this 'queryNode'. - if (SortPolicy::IsBetter(distance, bestDistance) - && queryNode.Stat().NumSamplesMade() < numSamplesReqd) - { - // We cannot prune this node; try approximating this node by sampling. - - // If we are required to visit the first leaf (to find possible duplicates), - // make sure we do not approximate. - if (queryNode.Stat().NumSamplesMade() > 0 || !firstLeafExact) - { - // Check if this node can be approximated by sampling. - size_t samplesReqd = (size_t) std::ceil(samplingRatio - * (double) referenceNode.NumDescendants()); - samplesReqd = std::min(samplesReqd, numSamplesReqd - - queryNode.Stat().NumSamplesMade()); - - if (samplesReqd > singleSampleLimit && !referenceNode.IsLeaf()) - { - // If too many samples are required and we are not at a leaf, then we - // can't prune. Since query tree descent is necessary now, propagate - // the number of samples made down to the children. - - // Iterate through all children and propagate the number of samples made - // to the children. Only update if the parent node has made samples the - // children have not seen. - for (size_t i = 0; i < queryNode.NumChildren(); i++) - queryNode.Child(i).Stat().NumSamplesMade() = std::max( - queryNode.Stat().NumSamplesMade(), - queryNode.Child(i).Stat().NumSamplesMade()); - - return distance; - } - else - { - if (!referenceNode.IsLeaf()) - { - // Then samplesReqd <= singleSampleLimit. Hence, approximate node by - // sampling enough number of points for every query in the query node. - arma::uvec distinctSamples; - for (size_t i = 0; i < queryNode.NumDescendants(); ++i) - { - const size_t queryIndex = queryNode.Descendant(i); - math::ObtainDistinctSamples(0, referenceNode.NumDescendants(), - samplesReqd, distinctSamples); - for (size_t j = 0; j < distinctSamples.n_elem; j++) - // The counting of the samples are done in the 'BaseCase' function - // so no book-keeping is required here. - BaseCase(queryIndex, - referenceNode.Descendant(distinctSamples[j])); - } - - // Update the number of samples made for the queryNode and also update - // the number of sample made for the child nodes. - queryNode.Stat().NumSamplesMade() += samplesReqd; - - // Since we are not going to descend down the query tree for this - // reference node, there is no point updating the number of samples - // made for the child nodes of this query node. - - // Node is approximated, so we can prune it. - return DBL_MAX; - } - else - { - if (sampleAtLeaves) - { - // Approximate node by sampling enough number of points for every - // query in the query node. - arma::uvec distinctSamples; - for (size_t i = 0; i < queryNode.NumDescendants(); ++i) - { - const size_t queryIndex = queryNode.Descendant(i); - math::ObtainDistinctSamples(0, referenceNode.NumDescendants(), - samplesReqd, distinctSamples); - for (size_t j = 0; j < distinctSamples.n_elem; j++) - // The counting of the samples are done in the 'BaseCase' - // function so no book-keeping is required here. - BaseCase(queryIndex, - referenceNode.Descendant(distinctSamples[j])); - } - - // Update the number of samples made for the queryNode and also - // update the number of sample made for the child nodes. - queryNode.Stat().NumSamplesMade() += samplesReqd; - - // Since we are not going to descend down the query tree for this - // reference node, there is no point updating the number of samples - // made for the child nodes of this query node. - - // (Leaf) node is approximated, so we can prune it. - return DBL_MAX; - } - else - { - // We cannot sample from leaves, so we cannot prune. Propagate the - // number of samples made down to the children. - - // Go through all children and propagate the number of - // samples made to the children. - for (size_t i = 0; i < queryNode.NumChildren(); i++) - queryNode.Child(i).Stat().NumSamplesMade() = std::max( - queryNode.Stat().NumSamplesMade(), - queryNode.Child(i).Stat().NumSamplesMade()); - - return distance; - } - } - } - } - else - { - // We must first visit the first leaf to boost accuracy. - // Go through all children and propagate the number of - // samples made to the children. - for (size_t i = 0; i < queryNode.NumChildren(); i++) - queryNode.Child(i).Stat().NumSamplesMade() = std::max( - queryNode.Stat().NumSamplesMade(), - queryNode.Child(i).Stat().NumSamplesMade()); - - return distance; - } - } - else - { - // Either there cannot be anything better in this node, or enough number of - // samples are already made, so prune it. - - // Add 'fake' samples from this node; fake because the distances to - // these samples need not be computed. If enough samples are already made, - // this step does not change the result of the search since this queryNode - // will never be descended anymore. - queryNode.Stat().NumSamplesMade() += (size_t) std::floor(samplingRatio * - (double) referenceNode.NumDescendants()); - - // Since we are not going to descend down the query tree for this reference - // node, there is no point updating the number of samples made for the child - // nodes of this query node. - - return DBL_MAX; - } -} - -template -inline double RASearchRules:: -Rescore(TreeType& queryNode, - TreeType& referenceNode, - const double oldScore) -{ - if (oldScore == DBL_MAX) - return oldScore; - - // First try to find the distance bound to check if we can prune by distance. - double pointBound = DBL_MAX; - double childBound = DBL_MAX; - const double maxDescendantDistance = queryNode.FurthestDescendantDistance(); - - for (size_t i = 0; i < queryNode.NumPoints(); i++) - { - const double bound = candidates[queryNode.Point(i)].top().first - + maxDescendantDistance; - if (bound < pointBound) - pointBound = bound; - } - - for (size_t i = 0; i < queryNode.NumChildren(); i++) - { - const double bound = queryNode.Child(i).Stat().Bound(); - if (bound < childBound) - childBound = bound; - } - - // Update the bound. - queryNode.Stat().Bound() = std::min(pointBound, childBound); - const double bestDistance = queryNode.Stat().Bound(); - - // Now check if the node-pair interaction can be pruned by sampling. - // Update the number of samples made for that node. Propagate up from child - // nodes if child nodes have made samples that the parent node is not aware - // of. Remember, we must propagate down samples made to the child nodes if - // the parent samples. - - // Only update from children if a non-leaf node, obviously. - if (!queryNode.IsLeaf()) - { - size_t numSamplesMadeInChildNodes = std::numeric_limits::max(); - - // Find the minimum number of samples made among all children - for (size_t i = 0; i < queryNode.NumChildren(); i++) - { - const size_t numSamples = queryNode.Child(i).Stat().NumSamplesMade(); - if (numSamples < numSamplesMadeInChildNodes) - numSamplesMadeInChildNodes = numSamples; - } - - // The number of samples made for a node is propagated up from the child - // nodes if the child nodes have made samples that the parent (which is the - // current 'queryNode') is not aware of. - queryNode.Stat().NumSamplesMade() = std::max( - queryNode.Stat().NumSamplesMade(), numSamplesMadeInChildNodes); - } - - // Now check if the node-pair interaction can be pruned by sampling. - - // If this is better than the best distance we've seen so far, maybe there - // will be something down this node. Also check if enough samples are already - // made for this query. - if (SortPolicy::IsBetter(oldScore, bestDistance) && - queryNode.Stat().NumSamplesMade() < numSamplesReqd) - { - // We cannot prune this node, so approximate by sampling. - - // Here we assume that since we are re-scoring, the algorithm has already - // sampled some candidates, and if specified, also traversed to the first - // leaf. So no checks regarding that are made any more. - size_t samplesReqd = (size_t) std::ceil( - samplingRatio * (double) referenceNode.NumDescendants()); - samplesReqd = std::min(samplesReqd, - numSamplesReqd - queryNode.Stat().NumSamplesMade()); - - if (samplesReqd > singleSampleLimit && !referenceNode.IsLeaf()) - { - // If too many samples are required and we are not at a leaf, then we - // can't prune. - - // Since query tree descent is necessary now, propagate the number of - // samples made down to the children. - - // Go through all children and propagate the number of samples made to the - // children. Only update if the parent node has made samples the children - // have not seen. - for (size_t i = 0; i < queryNode.NumChildren(); i++) - queryNode.Child(i).Stat().NumSamplesMade() = std::max( - queryNode.Stat().NumSamplesMade(), - queryNode.Child(i).Stat().NumSamplesMade()); - - return oldScore; - } - else - { - if (!referenceNode.IsLeaf()) // If not a leaf, - { - // then samplesReqd <= singleSampleLimit. Hence, approximate the node - // by sampling enough points for every query in the query node. - arma::uvec distinctSamples; - for (size_t i = 0; i < queryNode.NumDescendants(); ++i) - { - const size_t queryIndex = queryNode.Descendant(i); - math::ObtainDistinctSamples(0, referenceNode.NumDescendants(), - samplesReqd, distinctSamples); - for (size_t j = 0; j < distinctSamples.n_elem; j++) - // The counting of the samples are done in the 'BaseCase' - // function so no book-keeping is required here. - BaseCase(queryIndex, referenceNode.Descendant(distinctSamples[j])); - } - - // Update the number of samples made for the query node and also update - // the number of samples made for the child nodes. - queryNode.Stat().NumSamplesMade() += samplesReqd; - - // Since we are not going to descend down the query tree for this - // reference node, there is no point updating the number of samples made - // for the child nodes of this query node. - - // Node approximated, so we can prune it. - return DBL_MAX; - } - else // We are at a leaf. - { - if (sampleAtLeaves) - { - // Approximate node by sampling enough points for every query in the - // query node. - arma::uvec distinctSamples; - for (size_t i = 0; i < queryNode.NumDescendants(); ++i) - { - const size_t queryIndex = queryNode.Descendant(i); - math::ObtainDistinctSamples(0, referenceNode.NumDescendants(), - samplesReqd, distinctSamples); - for (size_t j = 0; j < distinctSamples.n_elem; j++) - // The counting of the samples are done in BaseCase() so no - // book-keeping is required here. - BaseCase(queryIndex, - referenceNode.Descendant(distinctSamples[j])); - } - - // Update the number of samples made for the query node and also - // update the number of samples made for the child nodes. - queryNode.Stat().NumSamplesMade() += samplesReqd; - - // Since we are not going to descend down the query tree for this - // reference node, there is no point updating the number of samples - // made for the child nodes of this query node. - - // (Leaf) node approximated, so we can prune it. - return DBL_MAX; - } - else - { - // We cannot sample from leaves, so we cannot prune. - // Propagate the number of samples made down to the children. - for (size_t i = 0; i < queryNode.NumChildren(); i++) - queryNode.Child(i).Stat().NumSamplesMade() = std::max( - queryNode.Stat().NumSamplesMade(), - queryNode.Child(i).Stat().NumSamplesMade()); - - return oldScore; - } - } - } - } - else - { - // Either there cannot be anything better in this node, or enough samples - // are already made, so prune it. - - // Add 'fake' samples from this node; fake because the distances to - // these samples need not be computed. If enough samples are already made, - // this step does not change the result of the search since this query node - // will never be descended anymore. - queryNode.Stat().NumSamplesMade() += (size_t) std::floor(samplingRatio * - (double) referenceNode.NumDescendants()); - - // Since we are not going to descend down the query tree for this reference - // node, there is no point updating the number of samples made for the child - // nodes of this query node. - return DBL_MAX; - } -} // Rescore(node, node, oldScore) - -/** - * Helper function to insert a point into the list of candidate points. - * - * @param queryIndex Index of point whose neighbors we are inserting into. - * @param neighbor Index of reference point which is being inserted. - * @param distance Distance from query point to reference point. - */ -template -inline void RASearchRules:: -InsertNeighbor( - const size_t queryIndex, - const size_t neighbor, - const double distance) -{ - CandidateList& pqueue = candidates[queryIndex]; - Candidate c = std::make_pair(distance, neighbor); - - if (CandidateCmp()(c, pqueue.top())) - { - pqueue.pop(); - pqueue.push(c); - } -} - -} // namespace neighbor -} // namespace mlpack - -#endif // MLPACK_METHODS_RANN_RA_SEARCH_RULES_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_typedef.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_typedef.hpp deleted file mode 100644 index dc1656071..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_typedef.hpp +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @file ra_typedef.hpp - * @author Parikshit Ram - * - * Simple typedefs describing template instantiations of the RASearch - * class which are commonly used. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_RANN_RA_TYPEDEF_HPP -#define MLPACK_RANN_RA_TYPEDEF_HPP - -// In case someone included this directly. -#include "ra_search.hpp" - -#include - -#include -#include - -namespace mlpack { -namespace neighbor { - -/** - * The KRANN class is the k-rank-approximate-nearest-neighbors method. It - * returns L2 distances for each of the k rank-approximate nearest-neighbors. - * - * The approximation is controlled with two parameters (see allkrann_main.cpp) - * which can be specified at search time. So the tree building is done only once - * while the search can be performed multiple times with different approximation - * levels. - */ -typedef RASearch<> KRANN; - -/** - * The KRAFN class is the k-rank-approximate-farthest-neighbors method. It - * returns L2 distances for each of the k rank-approximate farthest-neighbors. - * - * The approximation is controlled with two parameters (see allkrann_main.cpp) - * which can be specified at search time. So the tree building is done only once - * while the search can be performed multiple times with different approximation - * levels. - */ -typedef RASearch KRAFN; - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/rann/ra_util.hpp b/src/sdk/mlpack/include/mlpack/methods/rann/ra_util.hpp deleted file mode 100644 index a7f3f2f17..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/rann/ra_util.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @file ra_util.hpp - * @author Parikshit Ram - * @author Ryan Curtin - * - * Utilities for rank-approximate neighbor search. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RANN_RA_UTIL_HPP -#define MLPACK_METHODS_RANN_RA_UTIL_HPP - -#include - -namespace mlpack { -namespace neighbor { - -class RAUtil -{ - public: - /** - * Compute the minimum number of samples required to guarantee - * the given rank-approximation and success probability. - * - * @param n Size of the set to be sampled from. - * @param k The number of neighbors required within the rank-approximation. - * @param tau The rank-approximation in percentile of the data. - * @param alpha The success probability desired. - */ - static size_t MinimumSamplesReqd(const size_t n, - const size_t k, - const double tau, - const double alpha); - - /** - * Compute the success probability of obtaining 'k'-neighbors from a - * set of size 'n' within the top 't' neighbors if 'm' samples are made. - * - * @param n Size of the set being sampled from. - * @param k The number of neighbors required within the rank-approximation. - * @param m The number of random samples. - * @param t The desired rank-approximation. - */ - static double SuccessProbability(const size_t n, - const size_t k, - const size_t m, - const size_t t); - - /** - * Pick up desired number of samples (with replacement) from a given range - * of integers so that only the distinct samples are returned from - * the range [0 - specified upper bound) - * - * @param numSamples Number of random samples. - * @param rangeUpperBound The upper bound on the range of integers. - * @param distinctSamples The list of the distinct samples. - */ - static void ObtainDistinctSamples(const size_t numSamples, - const size_t rangeUpperBound, - arma::uvec& distinctSamples); -}; - -} // namespace neighbor -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd.hpp b/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd.hpp deleted file mode 100644 index d329f77e1..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @file regularized_svd.hpp - * @author Siddharth Agrawal - * - * An implementation of Regularized SVD. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_REGULARIZED_SVD_REGULARIZED_SVD_HPP -#define MLPACK_METHODS_REGULARIZED_SVD_REGULARIZED_SVD_HPP - -#include -#include -#include - -#include "regularized_svd_function.hpp" - -namespace mlpack { -namespace svd { - -/** - * Regularized SVD is a matrix factorization technique that seeks to reduce the - * error on the training set, that is on the examples for which the ratings have - * been provided by the users. It is a fairly straightforward technique where - * the user and item matrices are updated with the help of Stochastic Gradient - * Descent(SGD) updates. The updates also penalize the learning of large feature - * values by means of regularization. More details can be found in the following - * links: - * - * http://sifter.org/~simon/journal/20061211.html - * http://www.cs.uic.edu/~liub/KDD-cup-2007/proceedings/Regular-Paterek.pdf - * - * An example of how to use the interface is shown below: - * - * @code - * arma::mat data; // Rating data in the form of coordinate list. - * - * const size_t rank = 20; // Rank used for the decomposition. - * const size_t iterations = 10; // Number of iterations used for optimization. - * - * const double alpha = 0.01 // Learning rate for the SGD optimizer. - * const double lambda = 0.1 // Regularization parameter for the optimization. - * - * // Make a RegularizedSVD object. - * RegularizedSVD<> rSVD(iterations, alpha, lambda); - * - * arma::mat u, v; // User and item matrices. - * - * // Use the Apply() method to get a factorization. - * rSVD.Apply(data, rank, u, v); - * @endcode - */ -template -class RegularizedSVD -{ - public: - /** - * Constructor for Regularized SVD. Obtains the user and item matrices after - * training on the passed data. The constructor initiates an object of class - * RegularizedSVDFunction for optimization. It uses the SGD optimizer by - * default. The optimizer uses a template specialization of Optimize(). - * - * @param iterations Number of optimization iterations. - * @param alpha Learning rate for the SGD optimizer. - * @param lambda Regularization parameter for the optimization. - */ - RegularizedSVD(const size_t iterations = 10, - const double alpha = 0.01, - const double lambda = 0.02); - - /** - * Obtains the user and item matrices using the provided data and rank. - * - * @param data Rating data matrix. - * @param rank Rank parameter to be used for optimization. - * @param u Item matrix obtained on decomposition. - * @param v User matrix obtained on decomposition. - */ - void Apply(const arma::mat& data, - const size_t rank, - arma::mat& u, - arma::mat& v); - - private: - //! Number of optimization iterations. - size_t iterations; - //! Learning rate for the SGD optimizer. - double alpha; - //! Regularization parameter for the optimization. - double lambda; -}; - -} // namespace svd -} // namespace mlpack - -// Include implementation. -#include "regularized_svd_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_function.hpp b/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_function.hpp deleted file mode 100644 index d46a7e2f6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_function.hpp +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @file regularized_svd_function.hpp - * @author Siddharth Agrawal - * - * An implementation of the RegularizedSVDFunction class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_REGULARIZED_SVD_REGULARIZED_FUNCTION_SVD_HPP -#define MLPACK_METHODS_REGULARIZED_SVD_REGULARIZED_FUNCTION_SVD_HPP - -#include -#include -#include -#include - -namespace mlpack { -namespace svd { - -/** - * The data is stored in a matrix of type MatType, so that this class can be - * used with both dense and sparse matrix types. - * - * @tparam MatType The matrix type of the dataset. - */ -template -class RegularizedSVDFunction -{ - public: - /** - * Constructor for RegularizedSVDFunction class. The constructor calculates - * the number of users and items in the passed data. It also randomly - * initializes the parameter values. - * - * @param data Dataset for which SVD is calculated. - * @param rank Rank used for matrix factorization. - * @param lambda Regularization parameter used for optimization. - */ - RegularizedSVDFunction(const MatType& data, - const size_t rank, - const double lambda); - - /** - * Shuffle the points in the dataset. This may be used by optimizers. - */ - void Shuffle(); - - /** - * Evaluates the cost function over all examples in the data. - * - * @param parameters Parameters(user/item matrices) of the decomposition. - */ - double Evaluate(const arma::mat& parameters) const; - - /** - * Evaluates the cost function for one training example. Useful for the SGD - * optimizer abstraction which uses one training example at a time. - * - * @param parameters Parameters(user/item matrices) of the decomposition. - * @param start First index of the training examples to be used. - * @param batchSize Size of batch to evaluate. - */ - double Evaluate(const arma::mat& parameters, - const size_t start, - const size_t batchSize = 1) const; - - /** - * Evaluates the full gradient of the cost function over all the training - * examples. - * - * @param parameters Parameters(user/item matrices) of the decomposition. - * @param gradient Calculated gradient for the parameters. - */ - void Gradient(const arma::mat& parameters, - arma::mat& gradient) const; - - /** - * Evaluates the gradient of the cost function over one training example. - * This function is useful for optimizers like SGD. The type of the gradient - * parameter is a template argument to allow the computation of a sparse - * gradient. - * - * @tparam GradType The type of the gradient out-param. - * @param parameters Parameters(user/item matrices) of the decomposition. - * @param start The first index of the training examples to use. - * @param gradient Calculated gradient for the parameters. - * @param batchSize Size of batch to calculate gradient for. - */ - template - void Gradient(const arma::mat& parameters, - const size_t start, - GradType& gradient, - const size_t batchSize = 1) const; - - //! Return the initial point for the optimization. - const arma::mat& GetInitialPoint() const { return initialPoint; } - - //! Return the dataset passed into the constructor. - const arma::mat& Dataset() const { return data; } - - //! Return the number of training examples. Useful for SGD optimizer. - size_t NumFunctions() const { return data.n_cols; } - - //! Return the number of users in the data. - size_t NumUsers() const { return numUsers; } - - //! Return the number of items in the data. - size_t NumItems() const { return numItems; } - - //! Return the regularization parameters. - double Lambda() const { return lambda; } - - //! Return the rank used for the factorization. - size_t Rank() const { return rank; } - - private: - //! Rating data. This will be an alias until Shuffle() is called. - MatType data; - //! Initial parameter point. - arma::mat initialPoint; - //! Rank used for matrix factorization. - size_t rank; - //! Regularization parameter for the optimization. - double lambda; - //! Number of users in the given dataset. - size_t numUsers; - //! Number of items in the given dataset. - size_t numItems; -}; - -} // namespace svd -} // namespace mlpack - -namespace mlpack { -namespace optimization { - - /** - * Template specialization for the SGD and parallel SGD optimizer. Used - * because the gradient affects only a small number of parameters per example, - * and thus the normal abstraction does not work as fast as we might like it - * to. - */ - template <> - template <> - inline double StandardSGD::Optimize( - mlpack::svd::RegularizedSVDFunction& function, - arma::mat& parameters); - - template <> - template <> - inline double ParallelSGD::Optimize( - mlpack::svd::RegularizedSVDFunction& function, - arma::mat& parameters); - -} // namespace optimization -} // namespace mlpack - -#include "regularized_svd_function_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_function_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_function_impl.hpp deleted file mode 100644 index fd71b10b5..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_function_impl.hpp +++ /dev/null @@ -1,353 +0,0 @@ -/** - * @file regularized_svd_function.cpp - * @author Siddharth Agrawal - * - * An implementation of the RegularizedSVDFunction class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_REGULARIZED_SVD_REGULARIZED_FUNCTION_SVD_IMPL_HPP -#define MLPACK_METHODS_REGULARIZED_SVD_REGULARIZED_FUNCTION_SVD_IMPL_HPP - -#include "regularized_svd_function.hpp" -#include - -namespace mlpack { -namespace svd { - -template -RegularizedSVDFunction::RegularizedSVDFunction(const MatType& data, - const size_t rank, - const double lambda) : - data(math::MakeAlias(const_cast(data), false)), - rank(rank), - lambda(lambda) -{ - // Number of users and items in the data. - numUsers = max(data.row(0)) + 1; - numItems = max(data.row(1)) + 1; - - // Initialize the parameters. - initialPoint.randu(rank, numUsers + numItems); -} - -template -void RegularizedSVDFunction::Shuffle() -{ - data = data.cols(arma::shuffle(arma::linspace(0, data.n_cols - 1, - data.n_cols))); -} - -template -double RegularizedSVDFunction::Evaluate(const arma::mat& parameters) -const -{ - // The cost for the optimization is as follows: - // f(u, v) = sum((rating(i, j) - u(i).t() * v(j))^2) - // The sum is over all the ratings in the rating matrix. - // 'i' points to the user and 'j' points to the item being considered. - // The regularization term is added to the above cost, where the vectors u(i) - // and v(j) are regularized for each rating they contribute to. - - double cost = 0.0; - - for (size_t i = 0; i < data.n_cols; i++) - { - // Indices for accessing the the correct parameter columns. - const size_t user = data(0, i); - const size_t item = data(1, i) + numUsers; - - // Calculate the squared error in the prediction. - const double rating = data(2, i); - double ratingError = rating - arma::dot(parameters.col(user), - parameters.col(item)); - double ratingErrorSquared = ratingError * ratingError; - - // Calculate the regularization penalty corresponding to the parameters. - double userVecNorm = arma::norm(parameters.col(user), 2); - double itemVecNorm = arma::norm(parameters.col(item), 2); - double regularizationError = lambda * (userVecNorm * userVecNorm + - itemVecNorm * itemVecNorm); - - cost += (ratingErrorSquared + regularizationError); - } - - return cost; -} - -template -double RegularizedSVDFunction::Evaluate(const arma::mat& parameters, - const size_t start, - const size_t batchSize) const -{ - // It's possible this loop could be changed so that it's SIMD-vectorized. - double objective = 0.0; - for (size_t i = start; i < start + batchSize; ++i) - { - // Indices for accessing the the correct parameter columns. - const size_t user = data(0, i); - const size_t item = data(1, i) + numUsers; - - // Calculate the squared error in the prediction. - const double rating = data(2, i); - double ratingError = rating - arma::dot(parameters.col(user), - parameters.col(item)); - double ratingErrorSquared = ratingError * ratingError; - - // Calculate the regularization penalty corresponding to the parameters. - double userVecNorm = arma::norm(parameters.col(user), 2); - double itemVecNorm = arma::norm(parameters.col(item), 2); - double regularizationError = lambda * (userVecNorm * userVecNorm + - itemVecNorm * itemVecNorm); - - objective += (ratingErrorSquared + regularizationError); - } - - return objective; -} - -template -void RegularizedSVDFunction::Gradient(const arma::mat& parameters, - arma::mat& gradient) const -{ - // For an example with rating corresponding to user 'i' and item 'j', the - // gradients for the parameters is as follows: - // grad(u(i)) = lambda * u(i) - error * v(j) - // grad(v(j)) = lambda * v(j) - error * u(i) - // 'error' is the prediction error for that example, which is: - // rating(i, j) - u(i).t() * v(j) - // The full gradient is calculated by summing the contributions over all the - // training examples. - - gradient.zeros(rank, numUsers + numItems); - - for (size_t i = 0; i < data.n_cols; i++) - { - // Indices for accessing the the correct parameter columns. - const size_t user = data(0, i); - const size_t item = data(1, i) + numUsers; - - // Prediction error for the example. - const double rating = data(2, i); - double ratingError = rating - arma::dot(parameters.col(user), - parameters.col(item)); - - // Gradient is non-zero only for the parameter columns corresponding to the - // example. - gradient.col(user) += 2 * (lambda * parameters.col(user) - - ratingError * parameters.col(item)); - gradient.col(item) += 2 * (lambda * parameters.col(item) - - ratingError * parameters.col(user)); - } -} - -template -template -void RegularizedSVDFunction::Gradient(const arma::mat& parameters, - const size_t start, - GradType& gradient, - const size_t batchSize) const -{ - gradient.zeros(rank, numUsers + numItems); - - // It's possible this could be SIMD-vectorized for additional speedup. - for (size_t i = start; i < start + batchSize; ++i) - { - const size_t user = data(0, i); - const size_t item = data(1, i) + numUsers; - - // Prediction error for the example. - const double rating = data(2, i); - double ratingError = rating - arma::dot(parameters.col(user), - parameters.col(item)); - - // Gradient is non-zero only for the parameter columns corresponding to the - // example. - gradient.col(user) += 2 * (lambda * parameters.col(user) - - ratingError * parameters.col(item)); - gradient.col(item) += 2 * (lambda * parameters.col(item) - - ratingError * parameters.col(user)); - } -} - -} // namespace svd -} // namespace mlpack - -// Template specialization for the SGD optimizer. -namespace mlpack { -namespace optimization { - -template <> -template <> -double StandardSGD::Optimize( - mlpack::svd::RegularizedSVDFunction& function, - arma::mat& parameters) -{ - // Find the number of functions to use. - const size_t numFunctions = function.NumFunctions(); - - // To keep track of where we are and how things are going. - size_t currentFunction = 0; - double overallObjective = 0; - - // Calculate the first objective function. - for (size_t i = 0; i < numFunctions; i++) - overallObjective += function.Evaluate(parameters, i); - - const arma::mat data = function.Dataset(); - - // Now iterate! - for (size_t i = 1; i != maxIterations; i++, currentFunction++) - { - // Is this iteration the start of a sequence? - if ((currentFunction % numFunctions) == 0) - { - const size_t epoch = i / numFunctions + 1; - Log::Info << "Epoch " << epoch << "; " << "objective " - << overallObjective << "." << std::endl; - - // Reset the counter variables. - overallObjective = 0; - currentFunction = 0; - } - - const size_t numUsers = function.NumUsers(); - - // Indices for accessing the the correct parameter columns. - const size_t user = data(0, currentFunction); - const size_t item = data(1, currentFunction) + numUsers; - - // Prediction error for the example. - const double rating = data(2, currentFunction); - double ratingError = rating - arma::dot(parameters.col(user), - parameters.col(item)); - - double lambda = function.Lambda(); - - // Gradient is non-zero only for the parameter columns corresponding to the - // example. - parameters.col(user) -= stepSize * (lambda * parameters.col(user) - - ratingError * parameters.col(item)); - parameters.col(item) -= stepSize * (lambda * parameters.col(item) - - ratingError * parameters.col(user)); - - // Now add that to the overall objective function. - overallObjective += function.Evaluate(parameters, currentFunction); - } - - return overallObjective; -} - - -template <> -template <> -inline double ParallelSGD::Optimize( - mlpack::svd::RegularizedSVDFunction& function, - arma::mat& iterate) -{ - double overallObjective = DBL_MAX; - double lastObjective; - - // The order in which the functions will be visited. - arma::Col visitationOrder = arma::linspace>(0, - (function.NumFunctions() - 1), function.NumFunctions()); - - const arma::mat data = function.Dataset(); - - // Iterate till the objective is within tolerance or the maximum number of - // allowed iterations is reached. If maxIterations is 0, this will iterate - // till convergence. - for (size_t i = 1; i != maxIterations; ++i) - { - // Calculate the overall objective. - lastObjective = overallObjective; - overallObjective = 0; - - #pragma omp parallel for reduction(+:overallObjective) - for (omp_size_t j = 0; j < (omp_size_t) function.NumFunctions(); ++j) - { - overallObjective += function.Evaluate(iterate, j); - } - - // Output current objective function. - Log::Info << "Parallel SGD: iteration " << i << ", objective " - << overallObjective << "." << std::endl; - - if (std::isnan(overallObjective) || std::isinf(overallObjective)) - { - Log::Warn << "Parallel SGD: converged to " << overallObjective - << "; terminating with failure. Try a smaller step size?" - << std::endl; - return overallObjective; - } - - if (std::abs(lastObjective - overallObjective) < tolerance) - { - Log::Info << "SGD: minimized within tolerance " << tolerance << "; " - << "terminating optimization." << std::endl; - return overallObjective; - } - - // Get the stepsize for this iteration - double stepSize = decayPolicy.StepSize(i); - - if (shuffle) // Determine order of visitation. - std::shuffle(visitationOrder.begin(), visitationOrder.end(), - mlpack::math::randGen); - - #pragma omp parallel - { - // Each processor gets a subset of the instances. - // Each subset is of size threadShareSize. - size_t threadId = 0; - #ifdef HAS_OPENMP - threadId = omp_get_thread_num(); - #endif - - for (size_t j = threadId * threadShareSize; - j < (threadId + 1) * threadShareSize && j < visitationOrder.n_elem; - ++j) - { - const size_t numUsers = function.NumUsers(); - - // Indices for accessing the the correct parameter columns. - const size_t user = data(0, visitationOrder[j]); - const size_t item = data(1, visitationOrder[j]) + numUsers; - - // Prediction error for the example. - const double rating = data(2, visitationOrder[j]); - double ratingError = rating - arma::dot(iterate.col(user), - iterate.col(item)); - - double lambda = function.Lambda(); - - arma::mat userUpdate = stepSize * (lambda * iterate.col(user) - - ratingError * iterate.col(item)); - arma::mat itemUpdate = stepSize * (lambda * iterate.col(item) - - ratingError * iterate.col(user)); - - // Gradient is non-zero only for the parameter columns corresponding to - // the example. - for (size_t i = 0; i < iterate.n_rows; ++i) - { - #pragma omp atomic - iterate(i, user) -= userUpdate(i); - #pragma omp atomic - iterate(i, item) -= itemUpdate(i); - } - } - } - } - Log::Info << "\n Parallel SGD terminated with objective : " - << overallObjective << std::endl; - - return overallObjective; -} - -} // namespace optimization -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_impl.hpp deleted file mode 100644 index 32e4b25ee..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/regularized_svd/regularized_svd_impl.hpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file regularized_svd_impl.hpp - * @author Siddharth Agrawal - * - * An implementation of Regularized SVD. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_REGULARIZED_SVD_REGULARIZED_SVD_IMPL_HPP -#define MLPACK_METHODS_REGULARIZED_SVD_REGULARIZED_SVD_IMPL_HPP - -namespace mlpack { -namespace svd { - -template -RegularizedSVD::RegularizedSVD(const size_t iterations, - const double alpha, - const double lambda) : - iterations(iterations), - alpha(alpha), - lambda(lambda) -{ - // Nothing to do. -} - -template -void RegularizedSVD::Apply(const arma::mat& data, - const size_t rank, - arma::mat& u, - arma::mat& v) -{ - // batchSize is 1 in our implementation of Regularized SVD. - // batchSize other than 1 has not been supported yet. - const int batchSize = 1; - Log::Warn << "The batch size for optimizing RegularizedSVD is 1." - << std::endl; - - // Make the optimizer object using a RegularizedSVDFunction object. - RegularizedSVDFunction rSVDFunc(data, rank, lambda); - mlpack::optimization::StandardSGD optimizer(alpha, batchSize, - iterations * data.n_cols); - - // Get optimized parameters. - arma::mat parameters = rSVDFunc.GetInitialPoint(); - optimizer.Optimize(rSVDFunc, parameters); - - // Constants for extracting user and item matrices. - const size_t numUsers = max(data.row(0)) + 1; - const size_t numItems = max(data.row(1)) + 1; - - // Extract user and item matrices from the optimized parameters. - u = parameters.submat(0, numUsers, rank - 1, numUsers + numItems - 1).t(); - v = parameters.submat(0, 0, rank - 1, numUsers - 1); -} - -} // namespace svd -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/async_learning.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/async_learning.hpp deleted file mode 100644 index c053ea05c..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/async_learning.hpp +++ /dev/null @@ -1,241 +0,0 @@ -/** - * @file async_learning.hpp - * @author Shangtong Zhang - * - * This file is the definition of AsyncLearning class, - * which is wrapper for various asynchronous learning algorithms. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_RL_ASYNC_LEARNING_HPP -#define MLPACK_METHODS_RL_ASYNC_LEARNING_HPP - -#include -#include "worker/one_step_q_learning_worker.hpp" -#include "worker/one_step_sarsa_worker.hpp" -#include "worker/n_step_q_learning_worker.hpp" -#include "training_config.hpp" - -namespace mlpack { -namespace rl { - -/** - * Wrapper of various asynchronous learning algorithms, - * e.g. async one-step Q-learning, async one-step Sarsa, - * async n-step Q-learning and async advantage actor-critic. - * - * For more details, see the following: - * @code - * @inproceedings{mnih2016asynchronous, - * title = {Asynchronous methods for deep reinforcement learning}, - * author = {Mnih, Volodymyr and Badia, Adria Puigdomenech and Mirza, - * Mehdi and Graves, Alex and Lillicrap, Timothy and Harley, - * Tim and Silver, David and Kavukcuoglu, Koray}, - * booktitle = {International Conference on Machine Learning}, - * pages = {1928--1937}, - * year = {2016} - * } - * @endcode - * - * @tparam WorkerType The type of the worker. - * @tparam EnvironmentType The type of reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename WorkerType, - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -class AsyncLearning -{ - public: - /** - * Construct an instance of the given async learning algorithm. - * - * @param config Hyper-parameters for training. - * @param network The network model. - * @param policy The behavior policy. - * @param updater The optimizer. - * @param environment The reinforcement learning task. - */ - AsyncLearning(TrainingConfig config, - NetworkType network, - PolicyType policy, - UpdaterType updater = UpdaterType(), - EnvironmentType environment = EnvironmentType()); - - /** - * Starting async training. - * - * @tparam Measure The type of the measurement. It should be a - * callable object like - * @code - * bool foo(double reward); - * @endcode - * where reward is the total reward of a deterministic test episode, - * and the return value should indicate whether the training - * process is completed. - * @param measure The measurement instance. - */ - template - void Train(Measure& measure); - - //! Get training config. - TrainingConfig& Config() { return config; } - //! Modify training config. - const TrainingConfig& Config() const { return config; } - - //! Get learning network. - NetworkType& Network() { return learningNetwork; } - //! Modify learning network. - const NetworkType& Network() const { return learningNetwork; } - - //! Get behavior policy. - PolicyType& Policy() { return policy; } - //! Modify behavior policy. - const PolicyType& Policy() const { return policy; } - - //! Get optimizer. - UpdaterType& Updater() { return updater; } - //! Modify optimizer. - const UpdaterType& Updater() const { return updater; } - - //! Get the environment. - EnvironmentType& Environment() { return environment; } - //! Modify the environment. - const EnvironmentType& Environment() const { return environment; } - - private: - //! Locally-stored hyper-parameters. - TrainingConfig config; - - //! Locally-stored global learning network. - NetworkType learningNetwork; - - //! Locally-stored policy. - PolicyType policy; - - //! Locally-stored optimizer. - UpdaterType updater; - - //! Locally-stored task. - EnvironmentType environment; -}; - -/** - * Forward declaration of OneStepQLearningWorker. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -class OneStepQLearningWorker; - -/** - * Forward declaration of OneStepSarsaWorker. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -class OneStepSarsaWorker; - -/** - * Forward declaration of NStepQLearningWorker. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -class NStepQLearningWorker; - -/** - * Convenient typedef for async one step q-learning. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -using OneStepQLearning = AsyncLearning, EnvironmentType, NetworkType, - UpdaterType, PolicyType>; - -/** - * Convenient typedef for async one step Sarsa. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -using OneStepSarsa = AsyncLearning, EnvironmentType, NetworkType, - UpdaterType, PolicyType>; - -/** - * Convenient typedef for async n step q-learning. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -using NStepQLearning = AsyncLearning, EnvironmentType, NetworkType, - UpdaterType, PolicyType>; - -} // namespace rl -} // namespace mlpack - -// Include implementation -#include "async_learning_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/async_learning_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/async_learning_impl.hpp deleted file mode 100644 index 40fbdfa35..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/async_learning_impl.hpp +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @file async_learning_impl.hpp - * @author Shangtong Zhang - * - * This file is the implementation of AsyncLearning class, - * which is wrapper for various asynchronous learning algorithms. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_ASYNC_LEARNING_IMPL_HPP -#define MLPACK_METHODS_RL_ASYNC_LEARNING_IMPL_HPP - -#include -#include "queue" - -namespace mlpack { -namespace rl { - -template < - typename WorkerType, - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -AsyncLearning< - WorkerType, - EnvironmentType, - NetworkType, - UpdaterType, - PolicyType ->::AsyncLearning( - TrainingConfig config, - NetworkType network, - PolicyType policy, - UpdaterType updater, - EnvironmentType environment): - config(std::move(config)), - learningNetwork(std::move(network)), - policy(std::move(policy)), - updater(std::move(updater)), - environment(std::move(environment)) -{ /* Nothing to do here. */ }; - -template < - typename WorkerType, - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -template -void AsyncLearning< - WorkerType, - EnvironmentType, - NetworkType, - UpdaterType, - PolicyType ->::Train(Measure& measure) -{ - /** - * OpenMP doesn't support shared class member variables. - * So we need to copy them to local variables. - */ - NetworkType learningNetwork = std::move(this->learningNetwork); - if (learningNetwork.Parameters().is_empty()) - learningNetwork.ResetParameters(); - NetworkType targetNetwork = learningNetwork; - size_t totalSteps = 0; - PolicyType policy = this->policy; - bool stop = false; - - // Set up worker pool, worker 0 will be deterministic for evaluation. - std::vector workers; - for (size_t i = 0; i <= config.NumWorkers(); ++i) - { - workers.push_back(WorkerType(updater, environment, config, !i)); - workers.back().Initialize(learningNetwork); - } - // Set up task queue corresponding to worker pool. - std::queue tasks; - for (size_t i = 0; i <= config.NumWorkers(); ++i) - tasks.push(i); - - /** - * Compute the number of threads for the for-loop. In general, we should use - * OpenMP task rather than for-loop, here we do so to be compatible with some - * compiler. We can switch to OpenMP task once MSVC supports OpenMP 3.0. - */ - size_t numThreads = 0; - #pragma omp parallel reduction(+:numThreads) - numThreads++; - Log::Debug << numThreads << " threads will be used in total." << std::endl; - - #pragma omp parallel for shared(stop, workers, tasks, learningNetwork, \ - targetNetwork, totalSteps, policy) - for (omp_size_t i = 0; i < numThreads; ++i) - { - #pragma omp critical - { - #ifdef HAS_OPENMP - Log::Debug << "Thread " << omp_get_thread_num() << - " started." << std::endl; - #endif - } - size_t task = std::numeric_limits::max(); - while (!stop) - { - // Assign task to current thread from queue. - #pragma omp critical - { - if (task != std::numeric_limits::max()) - tasks.push(task); - - if (!tasks.empty()) - { - task = tasks.front(); - tasks.pop(); - } - }; - - // This may happen when threads are more than workers. - if (task == std::numeric_limits::max()) - continue; - - // Get corresponding worker. - WorkerType& worker = workers[task]; - double episodeReturn; - if (worker.Step(learningNetwork, targetNetwork, totalSteps, - policy, episodeReturn) && !task) - { - stop = measure(episodeReturn); - } - } - } - - // Write back the learning network. - this->learningNetwork = std::move(learningNetwork); -}; - -} // namespace rl -} // namespace mlpack - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/acrobat.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/acrobat.hpp deleted file mode 100644 index 2bc707adb..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/acrobat.hpp +++ /dev/null @@ -1,357 +0,0 @@ -/** - * @file acrobat.hpp - * @author Rohan Raj - * - * This file is an implementation of Acrobat task: - * https://gym.openai.com/envs/Acrobot-v1/ - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_ENVIRONMENT_ACROBAT_HPP -#define MLPACK_METHODS_RL_ENVIRONMENT_ACROBAT_HPP - -#include - -namespace mlpack{ -namespace rl{ - -/** - * Implementation of Acrobat game. Acrobot is a 2-link pendulum with only the - * second joint actuated. Intitially, both links point downwards. The goal is - * to swing the end-effector at a height at least the length of one link above - * the base. Both links can swing freely and can pass by each other, i.e., - * they don't collide when they have the same angle. - */ -class Acrobat -{ - public: - /* - * Implementation of Acrobat State. Each State is a tuple vector - * (theta1, thetha2, angular velocity 1, angular velocity 2). - */ - class State - { - public: - /** - * Construct a state instance. - */ - State(): data(dimension) { /* nothing to do here */ } - - /** - * Construct a state instance from given data. - * - * @param data Data for the theta and angular velocity of two links. - */ - State(const arma::colvec& data) : data(data) - { /* nothing to do here */ } - - //! Modify the state representation. - arma::colvec& Data() { return data; } - - //! Get value of theta (one). - double Theta1() const { return data[0]; } - //! Modify value of theta (one). - double& Theta1() { return data[0]; } - - //! Get value of theta (two). - double Theta2() const { return data[1]; } - //! Modify value of theta (two). - double& Theta2() { return data[1]; } - - //! Get value of Angular velocity (one). - double AngularVelocity1() const { return data[2]; } - //! Modify the angular velocity (one). - double& AngularVelocity1() { return data[2]; } - - //! Get value of Angular velocity (two). - double AngularVelocity2() const { return data[3]; } - //! Modify the angular velocity (two). - double& AngularVelocity2() { return data[3]; } - - //! Encode the state to a column vector. - const arma::colvec& Encode() const { return data; } - - //! Dimension of the encoded state. - static constexpr size_t dimension = 4; - - private: - //! Locally-Stored (theta1, theta2, angular velocity 1, angular velocity2). - arma::colvec data; - }; - - /* - * Implementation of action for Acrobat - */ - enum Action - { - negativeTorque, - zeroTorque, - positiveTorque, - - // Track the size of the action space. - size - }; - - /** - * Construct a Acrobat instance using the given constants. - * - * @param gravity The gravity parameter. - * @param linkLength1 The length of link 1. - * @param linkLength2 The length of link 2. - * @param linkMass1 The mass of link 1. - * @param linkMass2 The mass of link 2. - * @param linkCom1 The position of the center of mass of link 1. - * @param linkCom2 The position of the center of mass of link 2. - * @param linkMoi The moments of inertia for both link. - * @param maxVel1 The max angular velocity of link1. - * @param maxVel2 The max angular velocity of link2. - * @param dt The differential value. - */ - Acrobat(const double gravity = 9.81, - const double linkLength1 = 1.0, - const double linkLength2 = 1.0, - const double linkMass1 = 1.0, - const double linkMass2 = 1.0, - const double linkCom1 = 0.5, - const double linkCom2 = 0.5, - const double linkMoi = 1.0, - const double maxVel1 = 4 * M_PI, - const double maxVel2 = 9 * M_PI, - const double dt = 0.2, - const double doneReward = 0) : - gravity(gravity), - linkLength1(linkLength1), - linkLength2(linkLength2), - linkMass1(linkMass1), - linkMass2(linkMass2), - linkCom1(linkCom1), - linkCom2(linkCom2), - linkMoi(linkMoi), - maxVel1(maxVel1), - maxVel2(maxVel2), - dt(dt), - doneReward(doneReward) - { /* Nothing to do here */ } - - /** - * Dynamics of the Acrobat System. To get reward and next state based on - * current state and current action. Always return -1 reward. - * - * @param state The current State. - * @param action The action taken. - * @param nextState The next state. - * @return reward, it's always -1.0. - */ - double Sample(const State& state, - const Action& action, - State& nextState) const - { - // Make a vector to estimate nextstate. - arma::colvec currentState = {state.Theta1(), state.Theta2(), - state.AngularVelocity1(), state.AngularVelocity2()}; - - arma::colvec currentNextState = Rk4(currentState, Torque(action)); - - nextState.Theta1() = Wrap(currentNextState[0], -M_PI, M_PI); - - nextState.Theta2() = Wrap(currentNextState[1], -M_PI, M_PI); - //! The value of angular velocity is bounded in min and max value. - - nextState.AngularVelocity1() = std::min( - std::max(currentNextState[2], -maxVel1), maxVel1); - nextState.AngularVelocity2() = std::min( - std::max(currentNextState[3], -maxVel2), maxVel2); - /** - * If the acrobat reaches a terminal state, it should be given a positive - * reward. This will ensure that the agent learns the goal of the game. - */ - bool done = IsTerminal(nextState); - if (done) - return doneReward; - return -1; - }; - - /** - * Dynamics of the Acrobat System. To get reward and next state based on - * current state and current action. This function calls the Sample function - * to estimate the next state return reward for taking a particular action. - * - * @param state The current State. - * @param action The action taken. - * @param nextState The next state. - */ - double Sample(const State& state, const Action& action) const - { - State nextState; - return Sample(state, action, nextState); - } - - /** - * This function does random initialization of state space. - */ - State InitialSample() const - { - return State((arma::randu(4) - 0.5) / 5.0); - } - - /** - * This function checks if the acrobat has reached the terminal state. - * - * @param state The current State. - */ - bool IsTerminal(const State& state) const - { - return bool (-std::cos(state.Theta1())-std::cos(state.Theta1() + - state.Theta2()) > 1.0); - } - - /** - * This is the ordinary differential equations required for estimation of - * nextState through RK4 method. - * - * @param state Current State. - * @param torque The torque Applied. - */ - arma::colvec Dsdt(arma::colvec state, const double torque) const - { - const double m1 = linkMass1; - const double m2 = linkMass2; - const double l1 = linkLength1; - const double lc1 = linkCom1; - const double lc2 = linkCom2; - const double I1 = linkMoi; - const double I2 = linkMoi; - const double g = gravity; - const double a = torque; - const double theta1 = state[0]; - const double theta2 = state[1]; - - arma::colvec values(4); - values[0] = state[2]; - values[1] = state[3]; - - const double d1 = m1 * std::pow(lc1, 2) + m2 * (std::pow(l1, 2) + - std::pow(lc2, 2) + 2 * l1 * lc2 * std::cos(theta2)) + I1 + I2; - - const double d2 = m2 * (std::pow(lc2, 2) + l1 * lc2 * std::cos(theta2)) + - I2; - - const double phi2 = m2 * lc2 * g * std::cos(theta1 + theta2 - M_PI / 2.); - - const double phi1 = - m2 * l1 * lc2 * std::pow(values[1], 2) * - std::sin(theta2) - 2 * m2 * l1 * lc2 * values[1] * values[0] * - std::sin(theta2) + (m1 * lc1 + m2 * l1) * g * - std::cos(theta1 - M_PI / 2) + phi2; - - values[3] = (a + d2 / d1 * phi1 - m2 * l1 * lc2 * std::pow(values[0], 2) * - std::sin(theta2) - phi2) / (m2 * std::pow(lc2, 2) + I2 - - std::pow(d2, 2) / d1); - - values[2] = -(d2 * values[3] + phi1) / d1; - - return values; - }; - - /** - * Wrap funtion is required to truncate the angle value from -180 to 180. - * This function will make sure that value will always be between minimum - * to maximum. - * - * @param value Scalar value to wrap. - * @param minimum Minimum range of wrap. - * @param maximum Maximum range of wrap. - */ - double Wrap(double value, - const double minimum, - const double maximum) const - { - const double diff = maximum - minimum; - - if (value > maximum) - { - value = value - diff; - } - else if (value < minimum) - { - value = value + diff; - } - - return value; - }; - - /** - * This function calculates the torque for a particular action. - * 0 : negative torque, 1 : zero torque, 2 : positive torque. - * - * @param Action action taken. - */ - double Torque(const Action& action) const - { - // Add noise to the Torque Torque is action number - 1. {0,1,2} -> {-1,0,1}. - return double(action - 1) + mlpack::math::Random(-0.1, 0.1); - } - - /** - * - * This function calls the RK4 iterative method to estimate the next state - * based on given ordinary differential equation. - * - * @param state The current State. - * @param torque The torque applied. - */ - arma::colvec Rk4(const arma::colvec state, const double torque) const - { - arma::colvec k1 = Dsdt(state, torque); - arma::colvec k2 = Dsdt(state + dt * k1 / 2, torque); - arma::colvec k3 = Dsdt(state + dt * k2 / 2, torque); - arma::colvec k4 = Dsdt(state + dt * k3, torque); - arma::colvec nextState = state + dt * (k1 + 2 * k2 + 2 * k3 + k4) / 6; - - return nextState; - }; - - private: - //! Locally-stored gravity. - double gravity; - - //! Locally-stored length of link 1. - double linkLength1; - - //! Locally-stored length of link 2. - double linkLength2; - - //! Locally-stored mass of link 1. - double linkMass1; - - //! Locally-stored mass of link 2. - double linkMass2; - - //! Locally-stored position of link 1. - double linkCom1; - - //! Locally-stored position of link 2. - double linkCom2; - - //! Locally-stored moment of intertia value. - double linkMoi; - - //! Locally-stored max angular velocity of link1. - double maxVel1; - - //! Locally-stored max angular velocity of link2. - double maxVel2; - - //! Locally-stored dt for RK4 method. - double dt; - - //! Locally-stored done reward. - double doneReward; -}; // class Acrobat - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/cart_pole.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/cart_pole.hpp deleted file mode 100644 index 222c8b419..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/cart_pole.hpp +++ /dev/null @@ -1,247 +0,0 @@ -/** - * @file cart_pole.hpp - * @author Shangtong Zhang - * - * This file is an implementation of Cart Pole task: - * https://gym.openai.com/envs/CartPole-v0 - * - * TODO: provide an option to use dynamics directly from OpenAI gym. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_ENVIRONMENT_CART_POLE_HPP -#define MLPACK_METHODS_RL_ENVIRONMENT_CART_POLE_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * Implementation of Cart Pole task. - */ -class CartPole -{ - public: - /** - * Implementation of the state of Cart Pole. Each state is a tuple vector - * (position, velocity, angle, angular velocity). - */ - class State - { - public: - /** - * Construct a state instance. - */ - State() : data(dimension) - { /* Nothing to do here. */ } - - /** - * Construct a state instance from given data. - * - * @param data Data for the position, velocity, angle and angular velocity. - */ - State(const arma::colvec& data) : data(data) - { /* Nothing to do here */ } - - //! Modify the internal representation of the state. - arma::colvec& Data() { return data; } - - //! Get the position. - double Position() const { return data[0]; } - //! Modify the position. - double& Position() { return data[0]; } - - //! Get the velocity. - double Velocity() const { return data[1]; } - //! Modify the velocity. - double& Velocity() { return data[1]; } - - //! Get the angle. - double Angle() const { return data[2]; } - //! Modify the angle. - double& Angle() { return data[2]; } - - //! Get the angular velocity. - double AngularVelocity() const { return data[3]; } - //! Modify the angular velocity. - double& AngularVelocity() { return data[3]; } - - //! Encode the state to a column vector. - const arma::colvec& Encode() const { return data; } - - //! Dimension of the encoded state. - static constexpr size_t dimension = 4; - - private: - //! Locally-stored (position, velocity, angle, angular velocity). - arma::colvec data; - }; - - /** - * Implementation of action of Cart Pole. - */ - enum Action - { - backward, - forward, - - // Track the size of the action space. - size - }; - - /** - * Construct a Cart Pole instance using the given constants. - * - * @param gravity The gravity constant. - * @param massCart The mass of the cart. - * @param massPole The mass of the pole. - * @param length The length of the pole. - * @param forceMag The magnitude of the applied force. - * @param tau The time interval. - * @param thetaThresholdRadians The maximum angle. - * @param xThreshold The maximum position. - */ - CartPole(const double gravity = 9.8, - const double massCart = 1.0, - const double massPole = 0.1, - const double length = 0.5, - const double forceMag = 10.0, - const double tau = 0.02, - const double thetaThresholdRadians = 12 * 2 * 3.1416 / 360, - const double xThreshold = 2.4, - const double doneReward = 0.0) : - gravity(gravity), - massCart(massCart), - massPole(massPole), - totalMass(massCart + massPole), - length(length), - poleMassLength(massPole * length), - forceMag(forceMag), - tau(tau), - thetaThresholdRadians(thetaThresholdRadians), - xThreshold(xThreshold), - doneReward(doneReward) - { /* Nothing to do here */ } - - /** - * Dynamics of Cart Pole instance. Get reward and next state based on current - * state and current action. - * - * @param state The current state. - * @param action The current action. - * @param nextState The next state. - * @return reward, it's always 1.0. - */ - double Sample(const State& state, - const Action& action, - State& nextState) const - { - // Calculate acceleration. - double force = action ? forceMag : -forceMag; - double cosTheta = std::cos(state.Angle()); - double sinTheta = std::sin(state.Angle()); - double temp = (force + poleMassLength * state.AngularVelocity() * - state.AngularVelocity() * sinTheta) / totalMass; - double thetaAcc = (gravity * sinTheta - cosTheta * temp) / - (length * (4.0 / 3.0 - massPole * cosTheta * cosTheta / totalMass)); - double xAcc = temp - poleMassLength * thetaAcc * cosTheta / totalMass; - - // Update states. - nextState.Position() = state.Position() + tau * state.Velocity(); - nextState.Velocity() = state.Velocity() + tau * xAcc; - nextState.Angle() = state.Angle() + tau * state.AngularVelocity(); - nextState.AngularVelocity() = state.AngularVelocity() + tau * thetaAcc; - - /** - * It is important to note that if the cartpole is falling down, it should - * be penalized. - */ - bool done = IsTerminal(nextState); - if (done) - return doneReward; - /** - * When done is false, it means that the cartpole has fallen down. - * For this case the reward is 1.0. - */ - return 1.0; - } - - /** - * Dynamics of Cart Pole. Get reward based on current state and current - * action. - * - * @param state The current state. - * @param action The current action. - * @return reward, it's always 1.0. - */ - double Sample(const State& state, const Action& action) const - { - State nextState; - return Sample(state, action, nextState); - } - - /** - * Initial state representation is randomly generated within [-0.05, 0.05]. - * - * @return Initial state for each episode. - */ - State InitialSample() const - { - return State((arma::randu(4) - 0.5) / 10.0); - } - - /** - * Whether given state is a terminal state. - * - * @param state The desired state. - * @return true if state is a terminal state, otherwise false. - */ - bool IsTerminal(const State& state) const - { - return std::abs(state.Position()) > xThreshold || - std::abs(state.Angle()) > thetaThresholdRadians; - } - - private: - //! Locally-stored gravity. - double gravity; - - //! Locally-stored mass of the cart. - double massCart; - - //! Locally-stored mass of the pole. - double massPole; - - //! Locally-stored total mass. - double totalMass; - - //! Locally-stored length of the pole. - double length; - - //! Locally-stored moment of pole. - double poleMassLength; - - //! Locally-stored magnitude of the applied force. - double forceMag; - - //! Locally-stored time interval. - double tau; - - //! Locally-stored maximum angle. - double thetaThresholdRadians; - - //! Locally-stored maximum position. - double xThreshold; - - //! Locally-stored done reward. - double doneReward; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/continuous_mountain_car.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/continuous_mountain_car.hpp deleted file mode 100644 index b588f270f..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/continuous_mountain_car.hpp +++ /dev/null @@ -1,213 +0,0 @@ -/** - * @file continuous_mountain_car.hpp - * @author Rohan Raj - * @author Shashank Shekhar - * - * This file is an implementation of Continous Mountain Car task: - * https://gym.openai.com/envs/MountainCarContinuous-v0/ - * - * TODO: provide an option to use dynamics directly from OpenAI gym. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_RL_ENVIRONMENT_CONTINUOUS_MOUNTAIN_CAR_HPP -#define MLPACK_METHODS_RL_ENVIRONMENT_CONTINUOUS_MOUNTAIN_CAR_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * Implementation of Continuous Mountain Car task. - */ -class ContinuousMountainCar -{ - public: - /** - * Implementation of state of Continuous Mountain Car. Each state is a - * (velocity, position) vector. - */ - class State - { - public: - /** - * Construct a state instance. - */ - State() : data(dimension, arma::fill::zeros) - { /* Nothing to do here. */ } - - /** - * Construct a state based on the given data. - * - * @param data Data for the velocity and position. - */ - State(const arma::colvec& data): data(data) - { /* Nothing to do here. */ } - - //! Modify the internal representation of the state. - arma::colvec& Data() { return data; } - - //! Get the velocity. - double Velocity() const { return data[0]; } - //! Modify the velocity. - double& Velocity() { return data[0]; } - - //! Get the position. - double Position() const { return data[1]; } - //! Modify the position. - double& Position() { return data[1]; } - - //! Encode the state to a column vector. - const arma::colvec& Encode() const { return data; } - - //! Dimension of the encoded state. - static constexpr size_t dimension = 2; - - private: - //! Locally-stored velocity and position vector. - arma::colvec data; - }; - - /** - * Implementation of action of Continuous Mountain Car. - * In Continuous mountain car gain, the action represents the - * force to be applied. This value is bounded in range -1.0 to 1.0. - * Unlike the simple mountain car environment, where action space has a - * discrete value, continuous mountain car has continous action space - * value. - */ - struct Action - { - double action[1]; - // Storing degree of freedom - const int size = 1; - }; - - /** - * Construct a Continuous Mountain Car instance using the given constant. - * - * @param positionMin Minimum legal position. - * @param positionMax Maximum legal position. - * @param positionGoal Final target position. - * @param velocityMin Minimum legal velocity. - * @param velocityMax Maximum legal velocity. - * @param power Power generated by car. - */ - ContinuousMountainCar(const double positionMin = -1.2, - const double positionMax = 0.6, - const double positionGoal = 0.45, - const double velocityMin = -0.07, - const double velocityMax = 0.07, - const double power = 0.0015) : - positionMin(positionMin), - positionMax(positionMax), - positionGoal(positionGoal), - velocityMin(velocityMin), - velocityMax(velocityMax), - power(power) - { /* Nothing to do here */ } - - /** - * Dynamics of Continuous Mountain Car. Get reward and next state based - * on current state and current action. - * - * @param state The current state. - * @param action The current action. - * @param nextState The next state. - * @return reward, it's always -1.0. - */ - double Sample(const State& state, - const Action& action, - State& nextState) const - { - // Calculate acceleration. - double force = std::min(std::max(action.action[0], -1.0), 1.0); - - // Update states. - nextState.Velocity() = state.Velocity() + force * power - 0.0025 * - std::cos(3 * state.Position()); - nextState.Velocity() = std::min( - std::max(nextState.Velocity(), velocityMin), velocityMax); - nextState.Position() = state.Position() + nextState.Velocity(); - nextState.Position() = std::min( - std::max(nextState.Position(), positionMin), positionMax); - if (nextState.Position() == positionMin && nextState.Velocity() < 0) - nextState.Velocity() = 0.0; - - // Calculate reward - double reward = 0.0; - // If it is a terminal state, add a reward of 100.0 - if (IsTerminal(nextState)) - reward = 100.0; - reward -= std::pow(action.action[0], 2) * 0.1; - return reward; - } - - /** - * Dynamics of Continuous Mountain Car. Get reward based on current state and current - * action. - * - * @param state The current state. - * @param action The current action. - * @return reward, it's always -1.0. - */ - double Sample(const State& state, const Action& action) const - { - State nextState; - return Sample(state, action, nextState); - } - - /** - * Initial position is randomly generated within [-0.6, -0.4]. - * Initial velocity is 0. - * - * @return Initial state for each episode. - */ - State InitialSample() const - { - State state; - state.Velocity() = 0.0; - state.Position() = math::Random(-0.6, -0.4); - return state; - } - - /** - * Whether given state is a terminal state. - * - * @param state desired state. - * @return true if state is a terminal state, otherwise false. - */ - bool IsTerminal(const State& state) const - { - return bool(state.Position() >= positionGoal); - } - - private: - //! Locally-stored minimum legal position. - double positionMin; - - //! Locally-stored maximum legal position. - double positionMax; - - //! Locally-stored goal position. - double positionGoal; - - //! Locally-stored minimum legal velocity. - double velocityMin; - - //! Locally-stored maximum legal velocity. - double velocityMax; - - //! Locally-stored power. - double power; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/mountain_car.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/mountain_car.hpp deleted file mode 100644 index 7f77a96cd..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/mountain_car.hpp +++ /dev/null @@ -1,209 +0,0 @@ -/** - * @file mountain_car.hpp - * @author Shangtong Zhang - * - * This file is an implementation of Mountain Car task: - * https://gym.openai.com/envs/MountainCar-v0 - * - * TODO: provide an option to use dynamics directly from OpenAI gym. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_RL_ENVIRONMENT_MOUNTAIN_CAR_HPP -#define MLPACK_METHODS_RL_ENVIRONMENT_MOUNTAIN_CAR_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * Implementation of Mountain Car task. - */ -class MountainCar -{ - public: - /** - * Implementation of state of Mountain Car. Each state is a - * (velocity, position) vector. - */ - class State - { - public: - /** - * Construct a state instance. - */ - State(): data(dimension, arma::fill::zeros) - { /* Nothing to do here. */ } - - /** - * Construct a state based on the given data. - * - * @param data Data for the velocityand position. - */ - State(const arma::colvec& data): data(data) - { /* Nothing to do here. */ } - - //! Modify the internal representation of the state. - arma::colvec& Data() { return data; } - - //! Get the velocity. - double Velocity() const { return data[0]; } - //! Modify the velocity. - double& Velocity() { return data[0]; } - - //! Get the position. - double Position() const { return data[1]; } - //! Modify the position. - double& Position() { return data[1]; } - - //! Encode the state to a column vector. - const arma::colvec& Encode() const { return data; } - - //! Dimension of the encoded state. - static constexpr size_t dimension = 2; - - private: - //! Locally-stored velocity and position vector. - arma::colvec data; - }; - - /** - * Implementation of action of Mountain Car. - */ - enum Action - { - backward, - stop, - forward, - - //! Track the size of the action space. - size - }; - - /** - * Construct a Mountain Car instance using the given constant. - * - * @param positionMin Minimum legal position. - * @param positionMax Maximum legal position. - * @param velocityMin Minimum legal velocity. - * @param velocityMax Maximum legal velocity. - */ - MountainCar(const double positionMin = -1.2, - const double positionMax = 0.5, - const double velocityMin = -0.07, - const double velocityMax = 0.07, - const double doneReward = 0) : - positionMin(positionMin), - positionMax(positionMax), - velocityMin(velocityMin), - velocityMax(velocityMax), - doneReward(doneReward) - { /* Nothing to do here */ } - - /** - * Dynamics of Mountain Car. Get reward and next state based on current state - * and current action. - * - * @param state The current state. - * @param action The current action. - * @param nextState The next state. - * @return reward, it's always -1.0. - */ - double Sample(const State& state, - const Action& action, - State& nextState) const - { - // Calculate acceleration. - int direction = action - 1; - nextState.Velocity() = state.Velocity() + 0.001 * direction - 0.0025 * - std::cos(3 * state.Position()); - nextState.Velocity() = std::min( - std::max(nextState.Velocity(), velocityMin), velocityMax); - - // Update states. - nextState.Position() = state.Position() + nextState.Velocity(); - nextState.Position() = std::min( - std::max(nextState.Position(), positionMin), positionMax); - - if (std::abs(nextState.Position() - positionMin) <= 1e-5) - { - nextState.Velocity() = 0.0; - } - bool done = IsTerminal(nextState); - /** - * If done is true , it means that car has reached its goal. - * To make sure that the agent learns this, we will give some - * positive reward to the agent. If the agent doesn't reach the - * terminal state, then we will give a -1.0 reward to penalize - * the agent to take that step. - */ - if (done) - return doneReward; - return -1.0; - } - - /** - * Dynamics of Mountain Car. Get reward based on current state and current - * action. - * - * @param state The current state. - * @param action The current action. - * @return reward, it's always -1.0. - */ - double Sample(const State& state, const Action& action) const - { - State nextState; - return Sample(state, action, nextState); - } - - /** - * Initial position is randomly generated within [-0.6, -0.4]. - * Initial velocity is 0. - * - * @return Initial state for each episode. - */ - State InitialSample() const - { - State state; - state.Velocity() = 0.0; - state.Position() = arma::as_scalar(arma::randu(1)) * 0.2 - 0.6; - return state; - } - - /** - * Whether given state is a terminal state. - * - * @param state desired state. - * @return true if state is a terminal state, otherwise false. - */ - bool IsTerminal(const State& state) const - { - return std::abs(state.Position() - positionMax) <= 1e-5; - } - - private: - //! Locally-stored minimum legal position. - double positionMin; - - //! Locally-stored maximum legal position. - double positionMax; - - //! Locally-stored minimum legal velocity. - double velocityMin; - - //! Locally-stored maximum legal velocity. - double velocityMax; - - //! Locally-stored done reward. - double doneReward; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/pendulum.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/pendulum.hpp deleted file mode 100644 index 878b077c2..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/environment/pendulum.hpp +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @file pendulum.hpp - * @author Shashank Shekhar - * - * This file is an implementation of Pendulum task: - * https://gym.openai.com/envs/Pendulum-v0/ - * - * TODO: provide an option to use dynamics directly from OpenAI gym. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ - -#ifndef MLPACK_METHODS_RL_ENVIRONMENT_PENDULUM_HPP -#define MLPACK_METHODS_RL_ENVIRONMENT_PENDULUM_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * Implementation of Pendulum task. The inverted pendulum swingup problem is a - * classic problem in the control literature. In this version of the problem, - * the pendulum starts in a random position, and the goal is to swing it up so - * it stays upright - */ -class Pendulum -{ - public: - /** - * Implementation of state of Pendulum. Each state is a - * (theta, angular velocity) vector. - */ - class State - { - public: - /** - * Construct a state instance. - */ - State() : data(dimension, arma::fill::zeros) - { /* Nothing to do here. */ } - - /** - * Construct a state based on the given data. - * - * @param data Data for the theta and angular velocity. - */ - State(const arma::colvec& data): data(data) - { /* Nothing to do here. */ } - - //! Modify the internal representation of the state. - arma::colvec& Data() { return data; } - - //! Get the theta. - double Theta() const { return data[0]; } - //! Modify the value of theta. - double& Theta() { return data[0]; } - - //! Get the angular velocity. - double AngularVelocity() const { return data[1]; } - //! Modify the value of angular velocity. - double& AngularVelocity() { return data[1]; } - - //! Encode the state to a column vector. - const arma::colvec& Encode() const { return data; } - - //! Dimension of the encoded state. - static constexpr size_t dimension = 2; - - private: - //! Locally-stored (theta, angular velocity) vector - arma::colvec data; - }; - - /** - * Implementation of action of Pendulum. - * In Pendulum, the action represents the torque to be applied. - * This value is bounded in range -2.0 to 2.0 by default. - */ - struct Action - { - double action[1]; - // Storing degree of freedom - const int size = 1; - }; - - /** - * Construct a Pendulum instance using the given values. - * - * @param maxAngularVelocity Maximum angular velocity. - * @param maxTorque Maximum torque. - * @param dt The differential value. - */ - Pendulum(const double maxAngularVelocity = 8, - const double maxTorque = 2.0, - const double dt = 0.05) : - maxAngularVelocity(maxAngularVelocity), - maxTorque(maxTorque), - dt(dt) - { /* Nothing to do here */ } - - /** - * Dynamics of Pendulum. Get reward and next state based - * on current state and current action. - * - * @param state The current state. - * @param action The current action. - * @param nextState The next state. - * @return reward, The reward for taking the action taken for current state. - */ - double Sample(const State& state, - const Action& action, - State& nextState) const - { - // Get current state. - double theta = state.Theta(); - double angularVelocity = state.AngularVelocity(); - - // Define constants which specify our pendulum. - const double gravity = 10.0; - const double mass = 1.0; - const double length = 1.0; - - // Get action and clip the values between max and min limits. - double torque = std::min( - std::max(action.action[0], -maxTorque), maxTorque); - - // Calculate costs of taking this action in the current state. - double costs = std::pow(AngleNormalize(theta), 2) + 0.1 * - std::pow(angularVelocity, 2) + 0.001 * std::pow(torque, 2); - - // Calculate new state values and assign to the next state. - double newAngularVelocity = angularVelocity + (-3.0 * gravity / (2 * - length) * std::sin(theta + M_PI) + 3.0 / std::pow(mass * length, 2) * - torque) * dt; - nextState.AngularVelocity() = std::min(std::max(newAngularVelocity, - -maxAngularVelocity), maxAngularVelocity); - nextState.Theta() = theta + newAngularVelocity * dt; - - // Return the reward of taking the action in current state. - // The reward is simply the negative of cost incurred for the action. - return -costs; - } - - /** - * Dynamics of Pendulum. Get reward based on current state and current action - * - * @param state The current state. - * @param action The current action. - * @return reward, The reward. - */ - double Sample(const State& state, const Action& action) const - { - State nextState; - return Sample(state, action, nextState); - } - - /** - * Initial theta is randomly generated within [-pi, pi]. - * Initial angular velocity is randomly generated within [-1, 1]. - * - * @return Initial state for each episode. - */ - State InitialSample() const - { - State state; - state.Theta() = math::Random(-M_PI, M_PI); - state.AngularVelocity() = math::Random(-1.0, 1.0); - return state; - } - - /** - * This function calculates the normalized anlge for a particular theta. - * - * @param theta The un-normalized angle. - */ - double AngleNormalize(double theta) const - { - // Scale angle within [-pi, pi). - return double(fmod(theta + M_PI, 2 * M_PI) - M_PI); - } - - private: - //! Locally-stored maximum legal angular velocity. - double maxAngularVelocity; - - //! Locally-stored maximum legal torque. - double maxTorque; - - //! Locally-stored dt. - double dt; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/policy/aggregated_policy.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/policy/aggregated_policy.hpp deleted file mode 100644 index 4755e44ab..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/policy/aggregated_policy.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file aggregated_policy.hpp - * @author Shangtong Zhang - * - * This file is the implementation of AggregatedPolicy class. - * An aggregated policy will randomly select a child policy under a given - * distribution at each time step. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_POLICY_AGGREGATED_POLICY_HPP -#define MLPACK_METHODS_RL_POLICY_AGGREGATED_POLICY_HPP - -#include -#include - -namespace mlpack { -namespace rl { - -/** - * @tparam PolicyType The type of the child policy. - */ -template -class AggregatedPolicy -{ - public: - //! Convenient typedef for action. - using ActionType = typename PolicyType::ActionType; - - /** - * @param policies Child policies. - * @param distribution Probability distribution for each child policy. - * User should make sure its size is same as the number of policies - * and the sum of its element is equal to 1. - */ - AggregatedPolicy(std::vector policies, - const arma::colvec& distribution) : - policies(std::move(policies)), - sampler({distribution}) - { /* Nothing to do here. */ }; - - /** - * Sample an action based on given action values. - * - * @param actionValue Values for each action. - * @param deterministic Always select the action greedily. - * @return Sampled action. - */ - ActionType Sample(const arma::colvec& actionValue, bool deterministic = false) - { - if (deterministic) - return policies.front().Sample(actionValue, true); - size_t selected = arma::as_scalar(sampler.Random()); - return policies[selected].Sample(actionValue, false); - } - - /** - * Exploration probability will anneal at each step. - */ - void Anneal() - { - for (PolicyType& policy : policies) - policy.Anneal(); - } - - private: - //! Locally-stored child policies. - std::vector policies; - - //! Locally-stored sampler under the given distribution. - distribution::DiscreteDistribution sampler; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/policy/greedy_policy.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/policy/greedy_policy.hpp deleted file mode 100644 index 8d00ce46d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/policy/greedy_policy.hpp +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @file greedy_policy.hpp - * @author Shangtong Zhang - * - * This file is an implementation of epsilon greedy policy. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_POLICY_GREEDY_POLICY_HPP -#define MLPACK_METHODS_RL_POLICY_GREEDY_POLICY_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * Implementation for epsilon greedy policy. - * - * In general we will select an action greedily based on the action value, - * however sometimes we will also randomly select an action to encourage - * exploration. - * - * @tparam EnvironmentType The reinforcement learning task. - */ -template -class GreedyPolicy -{ - public: - //! Convenient typedef for action. - using ActionType = typename EnvironmentType::Action; - - /** - * Constructor for epsilon greedy policy class. - * - * @param initialEpsilon The initial probability to explore - * (select a random action). - * @param annealInterval The steps during which the probability to explore - * will anneal. - * @param minEpsilon Epsilon will never be less than this value. - */ - GreedyPolicy(const double initialEpsilon, - const size_t annealInterval, - const double minEpsilon) : - epsilon(initialEpsilon), - minEpsilon(minEpsilon), - delta((initialEpsilon - minEpsilon) / annealInterval) - { /* Nothing to do here. */ } - - /** - * Sample an action based on given action values. - * - * @param actionValue Values for each action. - * @param deterministic Always select the action greedily. - * @return Sampled action. - */ - ActionType Sample(const arma::colvec& actionValue, bool deterministic = false) - { - double exploration = math::Random(); - - // Select the action randomly. - if (!deterministic && exploration < epsilon) - return static_cast(math::RandInt(ActionType::size)); - - // Select the action greedily. - return static_cast( - arma::as_scalar(arma::find(actionValue == actionValue.max(), 1))); - } - - /** - * Exploration probability will anneal at each step. - */ - void Anneal() - { - epsilon -= delta; - epsilon = std::max(minEpsilon, epsilon); - } - - /** - * @return Current possibility to explore. - */ - const double& Epsilon() const { return epsilon; } - - private: - //! Locally-stored probability to explore. - double epsilon; - - //! Locally-stored lower bound for epsilon. - double minEpsilon; - - //! Locally-stored stride for epsilon to anneal. - double delta; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/q_learning.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/q_learning.hpp deleted file mode 100644 index 9332c67e3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/q_learning.hpp +++ /dev/null @@ -1,152 +0,0 @@ -/** - * @file q_learning.hpp - * @author Shangtong Zhang - * - * This file is the definition of QLearning class, - * which implements Q-Learning algorithms. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_Q_LEARNING_HPP -#define MLPACK_METHODS_RL_Q_LEARNING_HPP - -#include - -#include "replay/random_replay.hpp" -#include "training_config.hpp" - -namespace mlpack { -namespace rl { - -/** - * Implementation of various Q-Learning algorithms, such as DQN, double DQN. - * - * For more details, see the following: - * @code - * @article{Mnih2013, - * author = {Volodymyr Mnih and - * Koray Kavukcuoglu and - * David Silver and - * Alex Graves and - * Ioannis Antonoglou and - * Daan Wierstra and - * Martin A. Riedmiller}, - * title = {Playing Atari with Deep Reinforcement Learning}, - * journal = {CoRR}, - * year = {2013}, - * url = {http://arxiv.org/abs/1312.5602} - * } - * @endcode - * - * @tparam EnvironmentType The environment of the reinforcement learning task. - * @tparam NetworkType The network to compute action value. - * @tparam UpdaterType How to apply gradients when training. - * @tparam PolicyType Behavior policy of the agent. - * @tparam ReplayType Experience replay method. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType, - typename ReplayType = RandomReplay -> -class QLearning -{ - public: - //! Convenient typedef for state. - using StateType = typename EnvironmentType::State; - - //! Convenient typedef for action. - using ActionType = typename EnvironmentType::Action; - - /** - * Create the QLearning object with given settings. - * - * If you want to pass in a parameter and discard the original parameter - * object, be sure to use std::move to avoid unnecessary copy. - * - * @param config Hyper-parameters for training. - * @param network The network to compute action value. - * @param policy Behavior policy of the agent. - * @param replayMethod Experience replay method. - * @param updater How to apply gradients when training. - * @param environment Reinforcement learning task. - */ - QLearning(TrainingConfig config, - NetworkType network, - PolicyType policy, - ReplayType replayMethod, - UpdaterType updater = UpdaterType(), - EnvironmentType environment = EnvironmentType()); - - /** - * Execute a step in an episode. - * @return Reward for the step. - */ - double Step(); - - /** - * Execute an episode. - * @return Return of the episode. - */ - double Episode(); - - /** - * @return Total steps from beginning. - */ - const size_t& TotalSteps() const { return totalSteps; } - - //! Modify the training mode / test mode indicator. - bool& Deterministic() { return deterministic; } - //! Get the indicator of training mode / test mode. - const bool& Deterministic() const { return deterministic; } - - private: - /** - * Select the best action based on given action value. - * @param actionValues Action values. - * @return Selected actions. - */ - arma::Col BestAction(const arma::mat& actionValues); - - //! Locally-stored hyper-parameters. - TrainingConfig config; - - //! Locally-stored learning network. - NetworkType learningNetwork; - - //! Locally-stored target network. - NetworkType targetNetwork; - - //! Locally-stored updater. - UpdaterType updater; - - //! Locally-stored behavior policy. - PolicyType policy; - - //! Locally-stored experience method. - ReplayType replayMethod; - - //! Locally-stored reinforcement learning task. - EnvironmentType environment; - - //! Total steps from the beginning of the task. - size_t totalSteps; - - //! Locally-stored current state of the agent. - StateType state; - - //! Locally-stored flag indicating training mode or test mode. - bool deterministic; -}; - -} // namespace rl -} // namespace mlpack - -// Include implementation -#include "q_learning_impl.hpp" -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/q_learning_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/q_learning_impl.hpp deleted file mode 100644 index 8c84ae261..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/q_learning_impl.hpp +++ /dev/null @@ -1,222 +0,0 @@ -/** - * @file q_learning_impl.hpp - * @author Shangtong Zhang - * - * This file is the implementation of QLearning class. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_Q_LEARNING_IMPL_HPP -#define MLPACK_METHODS_RL_Q_LEARNING_IMPL_HPP - -#include "q_learning.hpp" - -namespace mlpack { -namespace rl { - -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType, - typename ReplayType -> -QLearning< - EnvironmentType, - NetworkType, - UpdaterType, - PolicyType, - ReplayType ->::QLearning(TrainingConfig config, - NetworkType network, - PolicyType policy, - ReplayType replayMethod, - UpdaterType updater, - EnvironmentType environment): - config(std::move(config)), - learningNetwork(std::move(network)), - updater(std::move(updater)), - policy(std::move(policy)), - replayMethod(std::move(replayMethod)), - environment(std::move(environment)), - totalSteps(0), - deterministic(false) -{ - if (learningNetwork.Parameters().is_empty()) - learningNetwork.ResetParameters(); - this->updater.Initialize(learningNetwork.Parameters().n_rows, - learningNetwork.Parameters().n_cols); - targetNetwork = learningNetwork; -} - -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType, - typename ReplayType -> -arma::Col QLearning< - EnvironmentType, - NetworkType, - UpdaterType, - PolicyType, - ReplayType ->::BestAction(const arma::mat& actionValues) -{ - arma::Col bestActions(actionValues.n_cols); - arma::rowvec maxActionValues = arma::max(actionValues, 0); - for (size_t i = 0; i < actionValues.n_cols; ++i) - { - bestActions(i) = arma::as_scalar( - arma::find(actionValues.col(i) == maxActionValues[i], 1)); - } - return bestActions; -}; - -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename BehaviorPolicyType, - typename ReplayType -> -double QLearning< - EnvironmentType, - NetworkType, - UpdaterType, - BehaviorPolicyType, - ReplayType ->::Step() -{ - // Get the action value for each action at current state. - arma::colvec actionValue; - learningNetwork.Predict(state.Encode(), actionValue); - - // Select an action according to the behavior policy. - ActionType action = policy.Sample(actionValue, deterministic); - - // Interact with the environment to advance to next state. - StateType nextState; - double reward = environment.Sample(state, action, nextState); - - // Store the transition for replay. - replayMethod.Store(state, action, reward, - nextState, environment.IsTerminal(nextState)); - - // Update current state. - state = nextState; - - if (deterministic || totalSteps < config.ExplorationSteps()) - return reward; - - // Start experience replay. - - // Sample from previous experience. - arma::mat sampledStates; - arma::icolvec sampledActions; - arma::colvec sampledRewards; - arma::mat sampledNextStates; - arma::icolvec isTerminal; - replayMethod.Sample(sampledStates, sampledActions, sampledRewards, - sampledNextStates, isTerminal); - - // Compute action value for next state with target network. - arma::mat nextActionValues; - targetNetwork.Predict(sampledNextStates, nextActionValues); - - arma::Col bestActions; - if (config.DoubleQLearning()) - { - // If use double Q-Learning, use learning network to select the best action. - arma::mat nextActionValues; - learningNetwork.Predict(sampledNextStates, nextActionValues); - bestActions = BestAction(nextActionValues); - } - else - { - bestActions = BestAction(nextActionValues); - } - - // Compute the update target. - arma::mat target; - learningNetwork.Forward(sampledStates, target); - /** - * If the agent is at a terminal state, then we don't need to add the - * discounted reward. At terminal state, the agent wont perform any - * action. - */ - for (size_t i = 0; i < sampledNextStates.n_cols; ++i) - { - if (isTerminal[i]) - target(sampledActions[i], i) = sampledRewards[i]; - else - target(sampledActions[i], i) = sampledRewards[i] + config.Discount() * - nextActionValues(bestActions[i], i); - } - - // Learn form experience. - arma::mat gradients; - learningNetwork.Backward(target, gradients); - updater.Update(learningNetwork.Parameters(), config.StepSize(), gradients); - - return reward; -} - -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename BehaviorPolicyType, - typename ReplayType -> -double QLearning< - EnvironmentType, - NetworkType, - UpdaterType, - BehaviorPolicyType, - ReplayType ->::Episode() -{ - // Get the initial state from environment. - state = environment.InitialSample(); - - // Track the steps in this episode. - size_t steps = 0; - - // Track the return of this episode. - double totalReturn = 0.0; - - // Running until get to the terminal state. - while (!environment.IsTerminal(state)) - { - if (config.StepLimit() && steps >= config.StepLimit()) - break; - - totalReturn += Step(); - steps++; - - if (deterministic) - continue; - - totalSteps++; - - // Update target network - if (totalSteps % config.TargetNetworkSyncInterval() == 0) - targetNetwork = learningNetwork; - - if (totalSteps > config.ExplorationSteps()) - policy.Anneal(); - } - - return totalReturn; -} - -} // namespace rl -} // namespace mlpack - -#endif - diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/replay/random_replay.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/replay/random_replay.hpp deleted file mode 100644 index 163c3de25..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/replay/random_replay.hpp +++ /dev/null @@ -1,170 +0,0 @@ -/** - * @file random_replay.hpp - * @author Shangtong Zhang - * - * This file is an implementation of random experience replay. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_REPLAY_RANDOM_REPLAY_HPP -#define MLPACK_METHODS_RL_REPLAY_RANDOM_REPLAY_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * Implementation of random experience replay. - * - * At each time step, interactions between the agent and the - * environment will be saved to a memory buffer. When necessary, - * we can simply sample previous experiences from the buffer to - * train the agent. Typically this would be a random sample and - * the memory will be a First-In-First-Out buffer. - * - * For more information, see the following. - * - * @code - * @phdthesis{lin1993reinforcement, - * title = {Reinforcement learning for robots using neural networks}, - * author = {Lin, Long-Ji}, - * year = {1993}, - * school = {Fujitsu Laboratories Ltd} - * } - * @endcode - * - * @tparam EnvironmentType Desired task. - */ -template -class RandomReplay -{ - public: - //! Convenient typedef for action. - using ActionType = typename EnvironmentType::Action; - - //! Convenient typedef for state. - using StateType = typename EnvironmentType::State; - - /** - * Construct an instance of random experience replay class. - * - * @param batchSize Number of examples returned at each sample. - * @param capacity Total memory size in terms of number of examples. - * @param dimension The dimension of an encoded state. - */ - RandomReplay(const size_t batchSize, - const size_t capacity, - const size_t dimension = StateType::dimension) : - batchSize(batchSize), - capacity(capacity), - position(0), - states(dimension, capacity), - actions(capacity), - rewards(capacity), - nextStates(dimension, capacity), - isTerminal(capacity), - full(false) - { /* Nothing to do here. */ } - - /** - * Store the given experience. - * - * @param state Given state. - * @param action Given action. - * @param reward Given reward. - * @param nextState Given next state. - * @param isEnd Whether next state is terminal state. - */ - void Store(const StateType& state, - ActionType action, - double reward, - const StateType& nextState, - bool isEnd) - { - states.col(position) = state.Encode(); - actions(position) = action; - rewards(position) = reward; - nextStates.col(position) = nextState.Encode(); - isTerminal(position) = isEnd; - position++; - if (position == capacity) - { - full = true; - position = 0; - } - } - - /** - * Sample some experiences. - * - * @param sampledStates Sampled encoded states. - * @param sampledActions Sampled actions. - * @param sampledRewards Sampled rewards. - * @param sampledNextStates Sampled encoded next states. - * @param isTerminal Indicate whether corresponding next state is terminal - * state. - */ - void Sample(arma::mat& sampledStates, - arma::icolvec& sampledActions, - arma::colvec& sampledRewards, - arma::mat& sampledNextStates, - arma::icolvec& isTerminal) - { - size_t upperBound = full ? capacity : position; - arma::uvec sampledIndices = arma::randi( - batchSize, arma::distr_param(0, upperBound - 1)); - - sampledStates = states.cols(sampledIndices); - sampledActions = actions.elem(sampledIndices); - sampledRewards = rewards.elem(sampledIndices); - sampledNextStates = nextStates.cols(sampledIndices); - isTerminal = this->isTerminal.elem(sampledIndices); - } - - /** - * Get the number of transitions in the memory. - * - * @return Actual used memory size - */ - const size_t& Size() - { - return full ? capacity : position; - } - - private: - //! Locally-stored number of examples of each sample. - size_t batchSize; - - //! Locally-stored total memory limit. - size_t capacity; - - //! Indicate the position to store new transition. - size_t position; - - //! Locally-stored encoded previous states. - arma::mat states; - - //! Locally-stored previous actions. - arma::icolvec actions; - - //! Locally-stored previous rewards. - arma::colvec rewards; - - //! Locally-stored encoded previous next states. - arma::mat nextStates; - - //! Locally-stored termination information of previous experience. - arma::icolvec isTerminal; - - //! Locally-stored indicator that whether the memory is full or not - bool full; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/training_config.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/training_config.hpp deleted file mode 100644 index df4ece07e..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/training_config.hpp +++ /dev/null @@ -1,163 +0,0 @@ -/** - * @file training_config.hpp - * @author Shangtong Zhang - * - * This file is the implementation of TrainingConfig class, - * which contains hyper-parameters for training RL agent. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_TRAINING_CONFIG_HPP -#define MLPACK_METHODS_RL_TRAINING_CONFIG_HPP - -namespace mlpack { -namespace rl { - -class TrainingConfig -{ - public: - TrainingConfig() : - numWorkers(1), - updateInterval(1), - stepLimit(0), - explorationSteps(1), - gradientLimit(40), - doubleQLearning(false) - { /* Nothing to do here. */ } - - TrainingConfig( - size_t numWorkers, - size_t updateInterval, - size_t targetNetworkSyncInterval, - size_t stepLimit, - size_t explorationSteps, - double stepSize, - double discount, - double gradientLimit, - bool doubleQLearning) : - numWorkers(numWorkers), - updateInterval(updateInterval), - targetNetworkSyncInterval(targetNetworkSyncInterval), - stepLimit(stepLimit), - explorationSteps(explorationSteps), - stepSize(stepSize), - discount(discount), - gradientLimit(gradientLimit), - doubleQLearning(doubleQLearning) - { /* Nothing to do here. */ } - - //! Get the amount of workers. - size_t NumWorkers() const { return numWorkers; } - //! Modify the amount of workers. - size_t& NumWorkers() { return numWorkers; } - - //! Get the update interval. - size_t UpdateInterval() const { return updateInterval; } - //! Modify the update interval. - size_t& UpdateInterval() { return updateInterval; } - - //! Get the interval for syncing target network. - size_t TargetNetworkSyncInterval() const - { return targetNetworkSyncInterval; } - //! Modify the interval for syncing target network. - size_t& TargetNetworkSyncInterval() { return targetNetworkSyncInterval; } - - //! Get the maximum steps of each episode. - size_t StepLimit() const { return stepLimit; } - /** - * Modify the maximum steps of each episode. - * Setting it to 0 means no limit. - */ - size_t& StepLimit() { return stepLimit; } - - //! Get the exploration steps. - size_t ExplorationSteps() const { return explorationSteps; } - //! Modify the exploration steps. - size_t& ExplorationSteps() { return explorationSteps; } - - //! Get the step size of the optimizer. - double StepSize() const { return stepSize; } - //! Modify the step size of the optimizer. - double& StepSize() { return stepSize; } - - //! Get the discount rate for future reward. - double Discount() const { return discount; } - //! Modify the discount rate for future reward. - double& Discount() { return discount; } - - //! Get the limit of update gradient. - double GradientLimit() const { return gradientLimit; } - //! Modify the limit of update gradient. - double& GradientLimit() { return gradientLimit; } - - //! Get the indicator of double q-learning. - bool DoubleQLearning() const { return doubleQLearning; } - //! Modify the indicator of double q-learning. - bool& DoubleQLearning() { return doubleQLearning; } - - private: - /** - * Locally-stored number of workers. - * This is valid only for async RL agent. - */ - size_t numWorkers; - - /** - * Locally-stored update interval. - * Update interval is similar to batch size, - * however the update is done one by one. - * This is valid only for async RL agent. - */ - size_t updateInterval; - - /** - * Locally-stored interval for syncing target network. - * This is valid for both async RL agent and q-learning agent. - */ - size_t targetNetworkSyncInterval; - - /** - * Locally-stored step limit of each episode. - * This is valid for both async RL agent and q-learning agent. - */ - size_t stepLimit; - - /** - * Locally-stored exploration steps before learning. - * The agent won't start learn until those steps have passed. - * This is valid only for q-learning agent. - */ - size_t explorationSteps; - - /** - * Locally-stored step size of optimizer. - * This is valid for both async RL agent and q-learning agent. - */ - double stepSize; - - /** - * Locally-stored discount rate for future reward. - * This is valid for both async RL agent and q-learning agent. - */ - double discount; - - /** - * Locally-stored gradient limit. - * This is valid only for async RL agent. - */ - double gradientLimit; - - /** - * Locally-stored indicator for double q-learning. - * This is valid only for q-learning agent. - */ - bool doubleQLearning; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/n_step_q_learning_worker.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/n_step_q_learning_worker.hpp deleted file mode 100644 index 3aa5041c3..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/n_step_q_learning_worker.hpp +++ /dev/null @@ -1,239 +0,0 @@ -/** - * @file n_step_q_learning_worker.hpp - * @author Shangtong Zhang - * - * This file is the definition of NStepQLearningWorker class, - * which implements an episode for async n step Q-Learning algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_WORKER_N_STEP_Q_LEARNING_WORKER_HPP -#define MLPACK_METHODS_RL_WORKER_N_STEP_Q_LEARNING_WORKER_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * N-step Q-Learning worker. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -class NStepQLearningWorker -{ - public: - using StateType = typename EnvironmentType::State; - using ActionType = typename EnvironmentType::Action; - using TransitionType = std::tuple; - - /** - * Construct N-step Q-Learning worker with the given parameters and - * environment. - * - * @param updater The optimizer. - * @param environment The reinforcement learning task. - * @param config Hyper-parameters. - * @param deterministic Whether it should be deterministic. - */ - NStepQLearningWorker( - const UpdaterType& updater, - const EnvironmentType& environment, - const TrainingConfig& config, - bool deterministic): - updater(updater), - environment(environment), - config(config), - deterministic(deterministic), - pending(config.UpdateInterval()) - { Reset(); } - - /** - * Initialize the worker. - * @param learningNetwork The shared network. - */ - void Initialize(NetworkType& learningNetwork) - { - updater.Initialize(learningNetwork.Parameters().n_rows, - learningNetwork.Parameters().n_cols); - // Build local network. - network = learningNetwork; - } - - /** - * The agent will execute one step. - * - * @param learningNetwork The shared learning network. - * @param targetNetwork The shared target network. - * @param totalSteps The shared counter for total steps. - * @param policy The shared behavior policy. - * @param totalReward This will be the episode return if the episode ends - * after this step. Otherwise this is invalid. - * @return Indicate whether current episode ends after this step. - */ - bool Step(NetworkType& learningNetwork, - NetworkType& targetNetwork, - size_t& totalSteps, - PolicyType& policy, - double& totalReward) - { - // Interact with the environment. - arma::colvec actionValue; - network.Predict(state.Encode(), actionValue); - ActionType action = policy.Sample(actionValue, deterministic); - StateType nextState; - double reward = environment.Sample(state, action, nextState); - bool terminal = environment.IsTerminal(nextState); - - episodeReturn += reward; - steps++; - - terminal = terminal || steps >= config.StepLimit(); - if (deterministic) - { - if (terminal) - { - totalReward = episodeReturn; - Reset(); - // Sync with latest learning network. - network = learningNetwork; - return true; - } - state = nextState; - return false; - } - - #pragma omp atomic - totalSteps++; - - pending[pendingIndex] = std::make_tuple(state, action, reward, nextState); - pendingIndex++; - - if (terminal || pendingIndex >= config.UpdateInterval()) - { - // Initialize the gradient storage. - arma::mat totalGradients(learningNetwork.Parameters().n_rows, - learningNetwork.Parameters().n_cols, arma::fill::zeros); - - // Bootstrap from the value of next state. - arma::colvec actionValue; - double target = 0; - if (!terminal) - { - #pragma omp critical - { targetNetwork.Predict(nextState.Encode(), actionValue); }; - target = actionValue.max(); - } - - // Update in reverse order. - for (int i = pending.size() - 1; i >= 0; --i) - { - TransitionType &transition = pending[i]; - target = config.Discount() * target + std::get<2>(transition); - - // Compute the training target for current state. - network.Forward(std::get<0>(transition).Encode(), actionValue); - actionValue[std::get<1>(transition)] = target; - - // Compute gradient. - arma::mat gradients; - network.Backward(actionValue, gradients); - - // Accumulate gradients. - totalGradients += gradients; - } - - // Clamp the accumulated gradients. - totalGradients.transform( - [&](double gradient) - { return std::min(std::max(gradient, -config.GradientLimit()), - config.GradientLimit()); }); - - // Perform async update of the global network. - updater.Update(learningNetwork.Parameters(), - config.StepSize(), totalGradients); - - // Sync the local network with the global network. - network = learningNetwork; - - pendingIndex = 0; - } - - // Update global target network. - if (totalSteps % config.TargetNetworkSyncInterval() == 0) - { - #pragma omp critical - { targetNetwork = learningNetwork; } - } - - policy.Anneal(); - - if (terminal) - { - totalReward = episodeReturn; - Reset(); - return true; - } - state = nextState; - return false; - } - - private: - /** - * Reset the worker for a new episode. - */ - void Reset() - { - steps = 0; - episodeReturn = 0; - pendingIndex = 0; - state = environment.InitialSample(); - } - - //! Locally-stored optimizer. - UpdaterType updater; - - //! Locally-stored task. - EnvironmentType environment; - - //! Locally-stored hyper-parameters. - TrainingConfig config; - - //! Whether this episode is deterministic or not. - bool deterministic; - - //! Total steps in current episode. - size_t steps; - - //! Total reward in current episode. - double episodeReturn; - - //! Buffer for delayed update. - std::vector pending; - - //! Current position of the buffer. - size_t pendingIndex; - - //! Local network of the worker. - NetworkType network; - - //! Current state of the agent. - StateType state; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/one_step_q_learning_worker.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/one_step_q_learning_worker.hpp deleted file mode 100644 index 198398ced..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/one_step_q_learning_worker.hpp +++ /dev/null @@ -1,239 +0,0 @@ -/** - * @file one_step_q_learning_worker.hpp - * @author Shangtong Zhang - * - * This file is the definition of OneStepQLearningWorker class, - * which implements an episode for async one step Q-Learning algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_WORKER_ONE_STEP_Q_LEARNING_WORKER_HPP -#define MLPACK_METHODS_RL_WORKER_ONE_STEP_Q_LEARNING_WORKER_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * One step Q-Learning worker. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. * - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -class OneStepQLearningWorker -{ - public: - using StateType = typename EnvironmentType::State; - using ActionType = typename EnvironmentType::Action; - using TransitionType = std::tuple; - - /** - * Construct one step Q-Learning worker with the given parameters and - * environment. - * - * @param updater The optimizer. - * @param environment The reinforcement learning task. - * @param config Hyper-parameters. - * @param deterministic Whether it should be deterministic. - */ - OneStepQLearningWorker( - const UpdaterType& updater, - const EnvironmentType& environment, - const TrainingConfig& config, - bool deterministic): - updater(updater), - environment(environment), - config(config), - deterministic(deterministic), - pending(config.UpdateInterval()) - { Reset(); } - - /** - * Initialize the worker. - * @param learningNetwork The shared network. - */ - void Initialize(NetworkType& learningNetwork) - { - updater.Initialize(learningNetwork.Parameters().n_rows, - learningNetwork.Parameters().n_cols); - // Build local network. - network = learningNetwork; - } - - /** - * The agent will execute one step. - * - * @param learningNetwork The shared learning network. - * @param targetNetwork The shared target network. - * @param totalSteps The shared counter for total steps. - * @param policy The shared behavior policy. - * @param totalReward This will be the episode return if the episode ends - * after this step. Otherwise this is invalid. - * @return Indicate whether current episode ends after this step. - */ - bool Step(NetworkType& learningNetwork, - NetworkType& targetNetwork, - size_t& totalSteps, - PolicyType& policy, - double& totalReward) - { - // Interact with the environment. - arma::colvec actionValue; - network.Predict(state.Encode(), actionValue); - ActionType action = policy.Sample(actionValue, deterministic); - StateType nextState; - double reward = environment.Sample(state, action, nextState); - bool terminal = environment.IsTerminal(nextState); - - episodeReturn += reward; - steps++; - - terminal = terminal || steps >= config.StepLimit(); - if (deterministic) - { - if (terminal) - { - totalReward = episodeReturn; - Reset(); - // Sync with latest learning network. - network = learningNetwork; - return true; - } - state = nextState; - return false; - } - - #pragma omp atomic - totalSteps++; - - pending[pendingIndex] = std::make_tuple(state, action, reward, nextState); - pendingIndex++; - - if (terminal || pendingIndex >= config.UpdateInterval()) - { - // Initialize the gradient storage. - arma::mat totalGradients(learningNetwork.Parameters().n_rows, - learningNetwork.Parameters().n_cols, arma::fill::zeros); - for (size_t i = 0; i < pending.size(); ++i) - { - TransitionType &transition = pending[i]; - - // Compute the target state-action value. - arma::colvec actionValue; - #pragma omp critical - { - targetNetwork.Predict( - std::get<3>(transition).Encode(), actionValue); - }; - double targetActionValue = actionValue.max(); - if (terminal && i == pending.size() - 1) - targetActionValue = 0; - targetActionValue = std::get<2>(transition) + - config.Discount() * targetActionValue; - - // Compute the training target for current state. - network.Forward(std::get<0>(transition).Encode(), actionValue); - actionValue[std::get<1>(transition)] = targetActionValue; - - // Compute gradient. - arma::mat gradients; - network.Backward(actionValue, gradients); - - // Accumulate gradients. - totalGradients += gradients; - } - - // Clamp the accumulated gradients. - totalGradients.transform( - [&](double gradient) - { return std::min(std::max(gradient, -config.GradientLimit()), - config.GradientLimit()); }); - - // Perform async update of the global network. - updater.Update(learningNetwork.Parameters(), - config.StepSize(), totalGradients); - - // Sync the local network with the global network. - network = learningNetwork; - - pendingIndex = 0; - } - - // Update global target network. - if (totalSteps % config.TargetNetworkSyncInterval() == 0) - { - #pragma omp critical - { targetNetwork = learningNetwork; } - } - - policy.Anneal(); - - if (terminal) - { - totalReward = episodeReturn; - Reset(); - return true; - } - state = nextState; - return false; - } - - private: - /** - * Reset the worker for a new episode. - */ - void Reset() - { - steps = 0; - episodeReturn = 0; - pendingIndex = 0; - state = environment.InitialSample(); - } - - //! Locally-stored optimizer. - UpdaterType updater; - - //! Locally-stored task. - EnvironmentType environment; - - //! Locally-stored hyper-parameters. - TrainingConfig config; - - //! Whether this episode is deterministic or not. - bool deterministic; - - //! Total steps in current episode. - size_t steps; - - //! Total reward in current episode. - double episodeReturn; - - //! Buffer for delayed update. - std::vector pending; - - //! Current position of the buffer. - size_t pendingIndex; - - //! Local network of the worker. - NetworkType network; - - //! Current state of the agent. - StateType state; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/one_step_sarsa_worker.hpp b/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/one_step_sarsa_worker.hpp deleted file mode 100644 index 3734da95d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/reinforcement_learning/worker/one_step_sarsa_worker.hpp +++ /dev/null @@ -1,253 +0,0 @@ -/** - * @file one_step_sarsa_worker.hpp - * @author Shangtong Zhang - * - * This file is the definition of OneStepSarsaWorker class, - * which implements an episode for async one step Sarsa algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_RL_WORKER_ONE_STEP_SARSA_WORKER_HPP -#define MLPACK_METHODS_RL_WORKER_ONE_STEP_SARSA_WORKER_HPP - -#include - -namespace mlpack { -namespace rl { - -/** - * One step Sarsa worker. - * - * @tparam EnvironmentType The type of the reinforcement learning task. - * @tparam NetworkType The type of the network model. - * @tparam UpdaterType The type of the optimizer. - * @tparam PolicyType The type of the behavior policy. - */ -template < - typename EnvironmentType, - typename NetworkType, - typename UpdaterType, - typename PolicyType -> -class OneStepSarsaWorker -{ - public: - using StateType = typename EnvironmentType::State; - using ActionType = typename EnvironmentType::Action; - using TransitionType = std::tuple; - - /** - * Construct one step sarsa worker with the given parameters and - * environment. - * - * @param updater The optimizer. - * @param environment The reinforcement learning task. - * @param config Hyper-parameters. - * @param deterministic Whether it should be deterministic. - */ - OneStepSarsaWorker( - const UpdaterType& updater, - const EnvironmentType& environment, - const TrainingConfig& config, - bool deterministic): - updater(updater), - environment(environment), - config(config), - deterministic(deterministic), - pending(config.UpdateInterval()) - { Reset(); } - - /** - * Initialize the worker. - * @param learningNetwork The shared network. - */ - void Initialize(NetworkType& learningNetwork) - { - updater.Initialize(learningNetwork.Parameters().n_rows, - learningNetwork.Parameters().n_cols); - // Build local network. - network = learningNetwork; - } - - /** - * The agent will execute one step. - * - * @param learningNetwork The shared learning network. - * @param targetNetwork The shared target network. - * @param totalSteps The shared counter for total steps. - * @param policy The shared behavior policy. - * @param totalReward This will be the episode return if the episode ends - * after this step. Otherwise this is invalid. - * @return Indicate whether current episode ends after this step. - */ - bool Step(NetworkType& learningNetwork, - NetworkType& targetNetwork, - size_t& totalSteps, - PolicyType& policy, - double& totalReward) - { - // Interact with the environment. - if (action == ActionType::size) - { - // Invalid action means we are at the beginning of an episode. - arma::colvec actionValue; - network.Predict(state.Encode(), actionValue); - action = policy.Sample(actionValue, deterministic); - } - StateType nextState; - double reward = environment.Sample(state, action, nextState); - bool terminal = environment.IsTerminal(nextState); - arma::colvec actionValue; - network.Predict(nextState.Encode(), actionValue); - ActionType nextAction = policy.Sample(actionValue, deterministic); - - episodeReturn += reward; - steps++; - - terminal = terminal || steps >= config.StepLimit(); - if (deterministic) - { - if (terminal) - { - totalReward = episodeReturn; - Reset(); - // Sync with latest learning network. - network = learningNetwork; - return true; - } - state = nextState; - action = nextAction; - return false; - } - - #pragma omp atomic - totalSteps++; - - pending[pendingIndex++] = - std::make_tuple(state, action, reward, nextState, nextAction); - - if (terminal || pendingIndex >= config.UpdateInterval()) - { - // Initialize the gradient storage. - arma::mat totalGradients(learningNetwork.Parameters().n_rows, - learningNetwork.Parameters().n_cols, arma::fill::zeros); - for (size_t i = 0; i < pending.size(); ++i) - { - TransitionType &transition = pending[i]; - - // Compute the target state-action value. - arma::colvec actionValue; - #pragma omp critical - { - targetNetwork.Predict( - std::get<3>(transition).Encode(), actionValue); - }; - double targetActionValue = 0; - if (!(terminal && i == pending.size() - 1)) - targetActionValue = actionValue[std::get<4>(transition)]; - targetActionValue = std::get<2>(transition) + - config.Discount() * targetActionValue; - - // Compute the training target for current state. - network.Forward(std::get<0>(transition).Encode(), actionValue); - actionValue[std::get<1>(transition)] = targetActionValue; - - // Compute gradient. - arma::mat gradients; - network.Backward(actionValue, gradients); - - // Accumulate gradients. - totalGradients += gradients; - } - - // Clamp the accumulated gradients. - totalGradients.transform( - [&](double gradient) - { return std::min(std::max(gradient, -config.GradientLimit()), - config.GradientLimit()); }); - - // Perform async update of the global network. - updater.Update(learningNetwork.Parameters(), - config.StepSize(), totalGradients); - - // Sync the local network with the global network. - network = learningNetwork; - - pendingIndex = 0; - } - - // Update global target network. - if (totalSteps % config.TargetNetworkSyncInterval() == 0) - { - #pragma omp critical - { targetNetwork = learningNetwork; } - } - - policy.Anneal(); - - if (terminal) - { - totalReward = episodeReturn; - Reset(); - return true; - } - state = nextState; - action = nextAction; - return false; - } - - private: - /** - * Reset the worker for a new episode. - */ - void Reset() - { - steps = 0; - episodeReturn = 0; - pendingIndex = 0; - state = environment.InitialSample(); - action = ActionType::size; - } - - //! Locally-stored optimizer. - UpdaterType updater; - - //! Locally-stored task. - EnvironmentType environment; - - //! Locally-stored hyper-parameters. - TrainingConfig config; - - //! Whether this episode is deterministic or not. - bool deterministic; - - //! Total steps in current episode. - size_t steps; - - //! Total reward in current episode. - double episodeReturn; - - //! Buffer for delayed update. - std::vector pending; - - //! Current position of the buffer. - size_t pendingIndex; - - //! Local network of the worker. - NetworkType network; - - //! Current state of the agent. - StateType state; - - //! Current action of the agent. - ActionType action; -}; - -} // namespace rl -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression.hpp b/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression.hpp deleted file mode 100644 index 56c7b1643..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression.hpp +++ /dev/null @@ -1,226 +0,0 @@ -/** - * @file softmax_regression.hpp - * @author Siddharth Agrawal - * - * An implementation of softmax regression. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_HPP -#define MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_HPP - -#include -#include - -#include "softmax_regression_function.hpp" - -namespace mlpack { -namespace regression { - -/** - * Softmax Regression is a classifier which can be used for classification when - * the data available can take two or more class values. It is a generalization - * of Logistic Regression (which is used only for binary classification). The - * model has a different set of parameters for each class, but can be easily - * converted into a vectorized implementation as has been done in this module. - * The model can be used for direct classification of feature data or in - * conjunction with unsupervised learning methods. More technical details about - * the model can be found on the following webpage: - * - * http://ufldl.stanford.edu/wiki/index.php/Softmax_Regression - * - * An example on how to use the interface is shown below: - * - * @code - * arma::mat train_data; // Training data matrix. - * arma::vec labels; // Labels associated with the data. - * const size_t inputSize = 784; // Size of input feature vector. - * const size_t numClasses = 10; // Number of classes. - * - * // Train the model using default options. - * SoftmaxRegression<> regressor1(train_data, labels, inputSize, numClasses); - * - * const size_t numBasis = 5; // Parameter required for L-BFGS algorithm. - * const size_t numIterations = 100; // Maximum number of iterations. - * - * // Use an instantiated optimizer for the training. - * SoftmaxRegressionFunction srf(train_data, labels, inputSize, numClasses); - * L_BFGS optimizer(srf, numBasis, numIterations); - * SoftmaxRegression regressor2(optimizer); - * - * arma::mat test_data; // Test data matrix. - * arma::vec predictions1, predictions2; // Vectors to store predictions in. - * - * // Obtain predictions from both the learned models. - * regressor1.Classify(test_data, predictions1); - * regressor2.Classify(test_data, predictions2); - * @endcode - */ -class SoftmaxRegression -{ - public: - /** - * Initialize the SoftmaxRegression without performing training. Default - * value of lambda is 0.0001. Be sure to use Train() before calling - * Classify() or ComputeAccuracy(), otherwise the results may be meaningless. - * - * @param inputSize Size of the input feature vector. - * @param numClasses Number of classes for classification. - * @param fitIntercept add intercept term or not. - */ - SoftmaxRegression(const size_t inputSize = 0, - const size_t numClasses = 0, - const bool fitIntercept = false); - - /** - * Construct the SoftmaxRegression class with the provided data and labels. - * This will train the model. Optionally, the parameter 'lambda' can be - * passed, which controls the amount of L2-regularization in the objective - * function. By default, the model takes a small value. - * - * @tparam OptimizerType Desired optimizer type. - * @param data Input training features. Each column associate with one sample - * @param labels Labels associated with the feature data. - * @param inputSize Size of the input feature vector. - * @param numClasses Number of classes for classification. - * @param optimizer Desired optimizer. - * @param lambda L2-regularization constant. - * @param fitIntercept add intercept term or not. - */ - template - SoftmaxRegression(const arma::mat& data, - const arma::Row& labels, - const size_t numClasses, - const double lambda = 0.0001, - const bool fitIntercept = false, - OptimizerType optimizer = OptimizerType()); - - /** - * Classify the given points, returning the predicted labels for each point. - * The function calculates the probabilities for every class, given a data - * point. It then chooses the class which has the highest probability among - * all. - * - * @param dataset Set of points to classify. - * @param labels Predicted labels for each point. - */ - void Classify(const arma::mat& dataset, arma::Row& labels) const; - - /** - * Classify the given point. The predicted class label is returned. - * The function calculates the probabilites for every class, given the point. - * It then chooses the class which has the highest probability among all. - * - * @param point Point to be classified. - * @return Predicted class label of the point. - */ - template - size_t Classify(const VecType& point) const; - - /** - * Classify the given points, returning class probabilities and predicted - * class label for each point. - * The function calculates the probabilities for every class, given a data - * point. It then chooses the class which has the highest probability among - * all. - * - * @param dataset Matrix of data points to be classified. - * @param labels Predicted labels for each point. - * @param probabilities Class probabilities for each point. - */ - void Classify(const arma::mat& dataset, - arma::Row& labels, - arma::mat& probabilites) const; - - /** - * Classify the given points, returning class probabilities for each point. - * - * @param dataset Matrix of data points to be classified. - * @param probabilities Class probabilities for each point. - */ - void Classify(const arma::mat& dataset, - arma::mat& probabilities) const; - - /** - * Computes accuracy of the learned model given the feature data and the - * labels associated with each data point. Predictions are made using the - * provided data and are compared with the actual labels. - * - * @param testData Matrix of data points using which predictions are made. - * @param labels Vector of labels associated with the data. - */ - double ComputeAccuracy(const arma::mat& testData, - const arma::Row& labels) const; - - /** - * Train the softmax regression with the given training data. - * - * @tparam OptimizerType Desired optimizer type. - * @param data Input data with each column as one example. - * @param labels Labels associated with the feature data. - * @param numClasses Number of classes for classification. - * @param optimizer Desired optimizer. - * @return Objective value of the final point. - */ - template - double Train(const arma::mat& data, - const arma::Row& labels, - const size_t numClasses, - OptimizerType optimizer = OptimizerType()); - - //! Sets the number of classes. - size_t& NumClasses() { return numClasses; } - //! Gets the number of classes. - size_t NumClasses() const { return numClasses; } - - //! Sets the regularization parameter. - double& Lambda() { return lambda; } - //! Gets the regularization parameter. - double Lambda() const { return lambda; } - - //! Gets the intercept term flag. We can't change this after training. - bool FitIntercept() const { return fitIntercept; } - - //! Get the model parameters. - arma::mat& Parameters() { return parameters; } - //! Get the model parameters. - const arma::mat& Parameters() const { return parameters; } - - //! Gets the features size of the training data - size_t FeatureSize() const - { return fitIntercept ? parameters.n_cols - 1 : - parameters.n_cols; } - - /** - * Serialize the SoftmaxRegression model. - */ - template - void serialize(Archive& ar, const unsigned int /* version */) - { - ar & BOOST_SERIALIZATION_NVP(parameters); - ar & BOOST_SERIALIZATION_NVP(numClasses); - ar & BOOST_SERIALIZATION_NVP(lambda); - ar & BOOST_SERIALIZATION_NVP(fitIntercept); - } - - private: - //! Parameters after optimization. - arma::mat parameters; - //! Number of classes. - size_t numClasses; - //! L2-regularization constant. - double lambda; - //! Intercept term flag. - bool fitIntercept; -}; - -} // namespace regression -} // namespace mlpack - -// Include implementation. -#include "softmax_regression_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression_function.hpp b/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression_function.hpp deleted file mode 100644 index ed091609d..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression_function.hpp +++ /dev/null @@ -1,205 +0,0 @@ -/** - * @file softmax_regression_function.hpp - * @author Siddharth Agrawal - * - * The function to be optimized for softmax regression. Any mlpack optimizer - * can be used. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_FUNCTION_HPP -#define MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_FUNCTION_HPP - -#include - -namespace mlpack { -namespace regression { - -class SoftmaxRegressionFunction -{ - public: - /** - * Construct the Softmax Regression objective function with the given - * parameters. - * - * @param data Input training data, each column associate with one sample - * @param labels Labels associated with the feature data. - * @param inputSize Size of the input feature vector. - * @param numClasses Number of classes for classification. - * @param lambda L2-regularization constant. - * @param fitIntercept Intercept term flag. - */ - SoftmaxRegressionFunction(const arma::mat& data, - const arma::Row& labels, - const size_t numClasses, - const double lambda = 0.0001, - const bool fitIntercept = false); - - //! Initializes the parameters of the model to suitable values. - const arma::mat InitializeWeights(); - - /** - * Shuffle the dataset. - */ - void Shuffle(); - - /** - * Initialize Softmax Regression weights (trainable parameters) with the given - * parameters. - * - * @param featureSize The number of features in the training set. - * @param numClasses Number of classes for classification. - * @param fitIntercept If true, an intercept is fitted. - * @return Initialized model weights. - */ - static const arma::mat InitializeWeights(const size_t featureSize, - const size_t numClasses, - const bool fitIntercept = false); - - /** - * Initialize Softmax Regression weights (trainable parameters) with the given - * parameters. - * - * @param weights This will be filled with the initialized model weights. - * @param featureSize The number of features in the training set. - * @param numClasses Number of classes for classification. - * @param fitIntercept Intercept term flag. - */ - static void InitializeWeights(arma::mat &weights, - const size_t featureSize, - const size_t numClasses, - const bool fitIntercept = false); - - /** - * Constructs the ground truth label matrix with the passed labels. - * - * @param labels Labels associated with the training data. - * @param groundTruth Pointer to arma::mat which stores the computed matrix. - */ - void GetGroundTruthMatrix(const arma::Row& labels, - arma::sp_mat& groundTruth); - - /** - * Evaluate the probabilities matrix with the passed parameters. - * probabilities(i, j) = - * exp(\theta_i * data_j) / sum_k(exp(\theta_k * data_j)). - * It represents the probability of data_j belongs to class i. - * - * @param parameters Current values of the model parameters. - * @param probabilities Pointer to arma::mat which stores the probabilities. - * @param start Index of point to start at. - * @param batchSize Number of points to calculate probabilities for. - */ - void GetProbabilitiesMatrix(const arma::mat& parameters, - arma::mat& probabilities, - const size_t start, - const size_t batchSize) const; - - /** - * Evaluates the objective function of the softmax regression model using the - * given parameters. The cost function has terms for the log likelihood error - * and the regularization cost. The objective function takes a low value when - * the model generalizes well for the given training data, while having small - * parameter values. - * - * @param parameters Current values of the model parameters. - */ - double Evaluate(const arma::mat& parameters) const; - - /** - * Evaluate the objective function of the softmax regression model for a - * subset of the data points using the given parameters. The cost function has - * terms for the log likelihood error and the regularization cost. The - * objective function takes a low value when the model generalizes well for - * the given training data, while having small parameter values. - * - * @param parameters Current values of the model parameters. - * @param start First index of the data points to use. - * @param batchSize Number of data points to evaluate objective for. - */ - double Evaluate(const arma::mat& parameters, - const size_t start, - const size_t batchSize = 1) const; - - /** - * Evaluates the gradient values of the objective function given the current - * set of parameters. The function calculates the probabilities for each class - * given the parameters, and computes the gradients based on the difference - * from the ground truth. - * - * @param parameters Current values of the model parameters. - * @param gradient Matrix where gradient values will be stored. - */ - void Gradient(const arma::mat& parameters, arma::mat& gradient) const; - - /** - * Evaluate the gradient of the objective function given the current set of - * parameters, on a subset of the data. The function calculates the - * probabilities for each class given the parameters, and computes the - * gradients based on the difference from the ground truth. - * - * @param parameters Current values of the model parameters. - * @param start First index of the data points to use. - * @param gradient Matrix to store gradient into. - * @param batchSize Number of data points to evaluate gradient for. - */ - void Gradient(const arma::mat& parameters, - const size_t start, - arma::mat& gradient, - const size_t batchSize = 1) const; - - /** - * Evaluates the gradient values of the objective function given the current - * set of parameters for a single feature indexed by j. - * - * @param parameters Current values of the model parameters. - * @param j The index of the feature with respect to which the partial - * gradient is to be computed. - * @param gradient Out param for the gradient value. - */ - void PartialGradient(const arma::mat& parameters, - size_t j, - arma::sp_mat& gradient) const; - - //! Return the initial point for the optimization. - const arma::mat& GetInitialPoint() const { return initialPoint; } - - //! Gets the number of classes. - size_t NumClasses() const { return numClasses; } - - //! Gets the features size of the training data. - size_t NumFeatures() const - { - return initialPoint.n_cols; - } - - //! Sets the regularization parameter. - double& Lambda() { return lambda; } - //! Gets the regularization parameter. - double Lambda() const { return lambda; } - - //! Gets the intercept flag. - bool FitIntercept() const { return fitIntercept; } - - private: - //! Training data matrix. This is an alias until the data is shuffled. - arma::mat data; - //! Label matrix for the provided data. - arma::sp_mat groundTruth; - //! Initial parameter point. - arma::mat initialPoint; - //! Number of classes. - size_t numClasses; - //! L2-regularization constant. - double lambda; - //! Intercept term flag. - bool fitIntercept; -}; - -} // namespace regression -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression_impl.hpp deleted file mode 100644 index 8caceb391..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/softmax_regression/softmax_regression_impl.hpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @file softmax_regression_impl.hpp - * @author Siddharth Agrawal - * - * Implementation of softmax regression. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_IMPL_HPP -#define MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_IMPL_HPP - -// In case it hasn't been included yet. -#include "softmax_regression.hpp" - -namespace mlpack { -namespace regression { - -template -SoftmaxRegression::SoftmaxRegression( - const arma::mat& data, - const arma::Row& labels, - const size_t numClasses, - const double lambda, - const bool fitIntercept, - OptimizerType optimizer) : - numClasses(numClasses), - lambda(lambda), - fitIntercept(fitIntercept) -{ - Train(data, labels, numClasses, optimizer); -} - -template -size_t SoftmaxRegression::Classify(const VecType& point) const -{ - arma::Row label(1); - Classify(point, label); - return size_t(label(0)); -} - -template -double SoftmaxRegression::Train(const arma::mat& data, - const arma::Row& labels, - const size_t numClasses, - OptimizerType optimizer) -{ - SoftmaxRegressionFunction regressor(data, labels, numClasses, - lambda, fitIntercept); - if (parameters.is_empty()) - parameters = regressor.GetInitialPoint(); - - // Train the model. - Timer::Start("softmax_regression_optimization"); - const double out = optimizer.Optimize(regressor, parameters); - Timer::Stop("softmax_regression_optimization"); - - Log::Info << "SoftmaxRegression::SoftmaxRegression(): final objective of " - << "trained model is " << out << "." << std::endl; - - return out; -} - -} // namespace regression -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/maximal_inputs.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/maximal_inputs.hpp deleted file mode 100644 index 2ee324210..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/maximal_inputs.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @file maximal_inputs.hpp - * @author Tham Ngap Wei - * - * A function to find the maximal inputs of an autoencoder. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_NN_MAXIMAL_INPUTS_HPP -#define MLPACK_METHODS_NN_MAXIMAL_INPUTS_HPP - -#include - -namespace mlpack { -namespace nn { - -/** - * Given a parameters matrix from an autoencoder, maximize the hidden units of - * the parameters, storing the maximal inputs in the given output matrix. - * Details can be found on the 'Visualizing a Trained Autoencoder' page of the - * Stanford UFLDL tutorial: - * - * http://deeplearning.stanford.edu/wiki/index.php/Main_Page - * - * This function is based on the implementation (display_network.m) from the - * "Exercise: Sparse Autoencoder" page of the UFLDL tutorial: - * - * http://deeplearning.stanford.edu/wiki/index.php/Exercise:Sparse_Autoencoder - * - * Example usage of this function can be seen below. Note that this function - * can work with the ColumnsToBlocks class in order to reshape the maximal - * inputs for visualization, as in the UFLDL tutorial. The code below - * demonstrates this. - * - * @code - * arma::mat data; // Data matrix. - * const size_t vSize = 64; // Size of visible layer, depends on the data. - * const size_t hSize = 25; // Size of hidden layer, depends on requirements. - * - * const size_t numBasis = 5; // Parameter required for L-BFGS algorithm. - * const size_t numIterations = 100; // Maximum number of iterations. - * - * // Use an instantiated optimizer for the training. - * SparseAutoencoder encoder(data, vSize, hSize); - * - * arma::mat maximalInput; // Store the features learned by sparse autoencoder - * mlpack::nn::MaximalInputs(encoder.Parameters(), maximalInput); - * - * arma::mat outputs; - * const bool scale = true; - * - * ColumnsToBlocks ctb(5,5); - * arma::mat output; - * ctb.Transform(maximalInput, output); - * // Save the output as PGM, for visualization. - * output.save(fileName, arma::pgm_binary); - * @endcode - * - * @pre Layout of parameters - * - * The layout of the parameters matrix should be same as following - * @code - * // vSize 1 - * // | | | - * // hSize| w1 |b1| - * // |________|__| - * // | | | - * // hSize| w2' | | - * // |________|__| - * // 1| b2' | | - * @endcode - * - * Also, the square root of vSize must be an integer (i.e. vSize must be a - * perfect square). - * - * @param parameters The parameters of the autoencoder. - * @param output Matrix to store the maximal inputs in. - */ -void MaximalInputs(const arma::mat& parameters, arma::mat& output); - -/** - * Normalize each column of the input matrix by its maximum value, if that - * maximum value is not zero. - * - * @param input The input data to normalize. - * @param output A matrix to store the input data in after normalization. - */ -void NormalizeColByMax(const arma::mat& input, arma::mat& output); - -} // namespace nn -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder.hpp deleted file mode 100644 index 3999d6be0..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder.hpp +++ /dev/null @@ -1,191 +0,0 @@ -/** - * @file sparse_autoencoder.hpp - * @author Siddharth Agrawal - * - * An implementation of sparse autoencoders. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_AUTOENCODER_SPARSE_AUTOENCODER_HPP -#define MLPACK_METHODS_SPARSE_AUTOENCODER_SPARSE_AUTOENCODER_HPP - -#include -#include - -#include "sparse_autoencoder_function.hpp" - -namespace mlpack { -namespace nn { - -/** - * A sparse autoencoder is a neural network whose aim to learn compressed - * representations of the data, typically for dimensionality reduction, with a - * constraint on the activity of the neurons in the network. Sparse autoencoders - * can be stacked together to learn a hierarchy of features, which provide a - * better representation of the data for classification. This is a method used - * in the recently developed field of deep learning. More technical details - * about the model can be found on the following webpage: - * - * http://deeplearning.stanford.edu/wiki/index.php/UFLDL_Tutorial - * - * An example of how to use the interface is shown below: - * - * @code - * arma::mat data; // Data matrix. - * const size_t vSize = 64; // Size of visible layer, depends on the data. - * const size_t hSize = 25; // Size of hidden layer, depends on requirements. - * - * // Train the model using default options. - * SparseAutoencoder encoder1(data, vSize, hSize); - * - * const size_t numBasis = 5; // Parameter required for L-BFGS algorithm. - * const size_t numIterations = 100; // Maximum number of iterations. - * - * // Use an instantiated optimizer for the training. - * SparseAutoencoderFunction saf(data, vSize, hSize); - * L_BFGS optimizer(saf, numBasis, numIterations); - * SparseAutoencoder encoder2(optimizer); - * - * arma::mat features1, features2; // Matrices for storing new representations. - * - * // Get new representations from the trained models. - * encoder1.GetNewFeatures(data, features1); - * encoder2.GetNewFeatures(data, features2); - * @endcode - * - * This implementation allows the use of arbitrary mlpack optimizers via the - * OptimizerType template parameter. - * - */ -class SparseAutoencoder -{ - public: - /** - * Construct the sparse autoencoder model with the given training data. This - * will train the model. The parameters 'lambda', 'beta' and 'rho' can be set - * optionally. Changing these parameters will have an effect on regularization - * and sparsity of the model. - * - * @tparam OptimizerType The optimizer to use. - * @param data Input data with each column as one example. - * @param visibleSize Size of input vector expected at the visible layer. - * @param hiddenSize Size of input vector expected at the hidden layer. - * @param lambda L2-regularization parameter. - * @param beta KL divergence parameter. - * @param rho Sparsity parameter. - */ - template - SparseAutoencoder(const arma::mat& data, - const size_t visibleSize, - const size_t hiddenSize, - const double lambda = 0.0001, - const double beta = 3, - const double rho = 0.01, - OptimizerType optimizer = OptimizerType()); - - /** - * Transforms the provided data into the representation learned by the sparse - * autoencoder. The function basically performs a feedforward computation - * using the learned weights, and returns the hidden layer activations. - * - * @param data Matrix of the provided data. - * @param features The hidden layer representation of the provided data. - */ - void GetNewFeatures(arma::mat& data, arma::mat& features); - - /** - * Returns the elementwise sigmoid of the passed matrix, where the sigmoid - * function of a real number 'x' is [1 / (1 + exp(-x))]. - * - * @param x Matrix of real values for which we require the sigmoid activation. - */ - void Sigmoid(const arma::mat& x, arma::mat& output) const - { - output = (1.0 / (1 + arma::exp(-x))); - } - - //! Sets size of the visible layer. - void VisibleSize(const size_t visible) - { - this->visibleSize = visible; - } - - //! Gets size of the visible layer. - size_t VisibleSize() const - { - return visibleSize; - } - - //! Sets size of the hidden layer. - void HiddenSize(const size_t hidden) - { - this->hiddenSize = hidden; - } - - //! Gets the size of the hidden layer. - size_t HiddenSize() const - { - return hiddenSize; - } - - //! Sets the L2-regularization parameter. - void Lambda(const double l) - { - this->lambda = l; - } - - //! Gets the L2-regularization parameter. - double Lambda() const - { - return lambda; - } - - //! Sets the KL divergence parameter. - void Beta(const double b) - { - this->beta = b; - } - - //! Gets the KL divergence parameter. - double Beta() const - { - return beta; - } - - //! Sets the sparsity parameter. - void Rho(const double r) - { - this->rho = r; - } - - //! Gets the sparsity parameter. - double Rho() const - { - return rho; - } - - private: - //! Parameters after optimization. - arma::mat parameters; - //! Size of the visible layer. - size_t visibleSize; - //! Size of the hidden layer. - size_t hiddenSize; - //! L2-regularization parameter. - double lambda; - //! KL divergence parameter. - double beta; - //! Sparsity parameter. - double rho; -}; - -} // namespace nn -} // namespace mlpack - -// Include implementation. -#include "sparse_autoencoder_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder_function.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder_function.hpp deleted file mode 100644 index d05c16dd6..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder_function.hpp +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @file sparse_autoencoder_function.hpp - * @author Siddharth Agrawal - * - * The function to be optimized for sparse autoencoders. Any mlpack optimizer - * can be used. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_AUTOENCODER_SPARSE_AUTOENCODER_FUNCTION_HPP -#define MLPACK_METHODS_SPARSE_AUTOENCODER_SPARSE_AUTOENCODER_FUNCTION_HPP - -#include - -namespace mlpack { -namespace nn { - -/** - * This is a class for the sparse autoencoder objective function. It can be used - * to create learning models like self-taught learning, stacked autoencoders, - * conditional random fields (CRFs), and so forth. - */ -class SparseAutoencoderFunction -{ - public: - /** - * Construct the sparse autoencoder objective function with the given - * parameters. - * - * @param data The data matrix. - * @param visibleSize Size of input vector expected at the visible layer. - * @param hiddenSize Size of input vector expected at the hidden layer. - * @param lambda L2-regularization parameter. - * @param beta KL divergence parameter. - * @param rho Sparsity parameter. - */ - SparseAutoencoderFunction(const arma::mat& data, - const size_t visibleSize, - const size_t hiddenSize, - const double lambda = 0.0001, - const double beta = 3, - const double rho = 0.01); - - //! Initializes the parameters of the model to suitable values. - const arma::mat InitializeWeights(); - - /** - * Evaluates the objective function of the sparse autoencoder model using the - * given parameters. The cost function has terms for the reconstruction - * error, regularization cost and the sparsity cost. The objective function - * takes a low value when the model is able to reconstruct the data well - * using weights which are low in value and when the average activations of - * neurons in the hidden layers agrees well with the sparsity parameter 'rho'. - * - * @param parameters Current values of the model parameters. - */ - double Evaluate(const arma::mat& parameters) const; - - /** - * Evaluates the gradient values of the objective function given the current - * set of parameters. The function performs a feedforward pass and computes - * the error in reconstructing the data points. It then uses the - * backpropagation algorithm to compute the gradient values. - * - * @param parameters Current values of the model parameters. - * @param gradient Matrix where gradient values will be stored. - */ - void Gradient(const arma::mat& parameters, arma::mat& gradient) const; - - /** - * Returns the elementwise sigmoid of the passed matrix, where the sigmoid - * function of a real number 'x' is [1 / (1 + exp(-x))]. - * - * @param x Matrix of real values for which we require the sigmoid activation. - */ - void Sigmoid(const arma::mat& x, arma::mat& output) const - { - output = (1.0 / (1 + arma::exp(-x))); - } - - //! Return the initial point for the optimization. - const arma::mat& GetInitialPoint() const { return initialPoint; } - - //! Sets size of the visible layer. - void VisibleSize(const size_t visible) - { - this->visibleSize = visible; - } - - //! Gets size of the visible layer. - size_t VisibleSize() const - { - return visibleSize; - } - - //! Sets size of the hidden layer. - void HiddenSize(const size_t hidden) - { - this->hiddenSize = hidden; - } - - //! Gets the size of the hidden layer. - size_t HiddenSize() const - { - return hiddenSize; - } - - //! Sets the L2-regularization parameter. - void Lambda(const double l) - { - this->lambda = l; - } - - //! Gets the L2-regularization parameter. - double Lambda() const - { - return lambda; - } - - //! Sets the KL divergence parameter. - void Beta(const double b) - { - this->beta = b; - } - - //! Gets the KL divergence parameter. - double Beta() const - { - return beta; - } - - //! Sets the sparsity parameter. - void Rho(const double r) - { - this->rho = r; - } - - //! Gets the sparsity parameter. - double Rho() const - { - return rho; - } - - private: - //! The matrix of data points. - const arma::mat& data; - //! Initial parameter vector. - arma::mat initialPoint; - //! Size of the visible layer. - size_t visibleSize; - //! Size of the hidden layer. - size_t hiddenSize; - //! L2-regularization parameter. - double lambda; - //! KL divergence parameter. - double beta; - //! Sparsity parameter. - double rho; -}; - -} // namespace nn -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder_impl.hpp deleted file mode 100644 index ac4316283..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_autoencoder/sparse_autoencoder_impl.hpp +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @file sparse_autoencoder_impl.hpp - * @author Siddharth Agrawal - * - * Implementation of sparse autoencoders. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_AUTOENCODER_SPARSE_AUTOENCODER_IMPL_HPP -#define MLPACK_METHODS_SPARSE_AUTOENCODER_SPARSE_AUTOENCODER_IMPL_HPP - -// In case it hasn't been included yet. -#include "sparse_autoencoder.hpp" - -namespace mlpack { -namespace nn { - -template -SparseAutoencoder::SparseAutoencoder(const arma::mat& data, - const size_t visibleSize, - const size_t hiddenSize, - double lambda, - double beta, - double rho, - OptimizerType optimizer) : - visibleSize(visibleSize), - hiddenSize(hiddenSize), - lambda(lambda), - beta(beta), - rho(rho) -{ - SparseAutoencoderFunction encoderFunction(data, visibleSize, hiddenSize, - lambda, beta, rho); - - parameters = encoderFunction.GetInitialPoint(); - - // Train the model. - Timer::Start("sparse_autoencoder_optimization"); - const double out = optimizer.Optimize(encoderFunction, parameters); - Timer::Stop("sparse_autoencoder_optimization"); - - Log::Info << "SparseAutoencoder::SparseAutoencoder(): final objective of " - << "trained model is " << out << "." << std::endl; -} - -} // namespace nn -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/data_dependent_random_initializer.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_coding/data_dependent_random_initializer.hpp deleted file mode 100644 index dbe01ecae..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/data_dependent_random_initializer.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @file data_dependent_random_initializer.hpp - * @author Nishant Mehta - * - * A sensible heuristic for initializing dictionaries for sparse coding. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_CODING_DATA_DEPENDENT_RANDOM_INITIALIZER_HPP -#define MLPACK_METHODS_SPARSE_CODING_DATA_DEPENDENT_RANDOM_INITIALIZER_HPP - -#include -#include - -namespace mlpack { -namespace sparse_coding { - -/** - * A data-dependent random dictionary initializer for SparseCoding. This - * creates random dictionary atoms by adding three random observations from the - * data together, and then normalizing the atom. - */ -class DataDependentRandomInitializer -{ - public: - /** - * Initialize the dictionary by adding together three random observations from - * the data, and then normalizing the atom. This implementation is simple - * enough to be included with the definition. - * - * @param data Dataset to initialize the dictionary with. - * @param atoms Number of atoms in dictionary. - * @param dictionary Dictionary to initialize. - */ - static void Initialize(const arma::mat& data, - const size_t atoms, - arma::mat& dictionary) - { - // Set the size of the dictionary. - dictionary.set_size(data.n_rows, atoms); - - // Create each atom. - for (size_t i = 0; i < atoms; ++i) - { - // Add three atoms together. - dictionary.col(i) = (data.col(math::RandInt(data.n_cols)) + - data.col(math::RandInt(data.n_cols)) + - data.col(math::RandInt(data.n_cols))); - - // Now normalize the atom. - dictionary.col(i) /= norm(dictionary.col(i), 2); - } - } -}; - -} // namespace sparse_coding -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/nothing_initializer.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_coding/nothing_initializer.hpp deleted file mode 100644 index 972bf3cff..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/nothing_initializer.hpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @file nothing_initializer.hpp - * @author Ryan Curtin - * - * An initializer for SparseCoding which does precisely nothing. It is useful - * for when you have an already defined dictionary and you plan on setting it - * with SparseCoding::Dictionary(). - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_CODING_NOTHING_INITIALIZER_HPP -#define MLPACK_METHODS_SPARSE_CODING_NOTHING_INITIALIZER_HPP - -#include - -namespace mlpack { -namespace sparse_coding { - -/** - * A DictionaryInitializer for SparseCoding which does not initialize anything; - * it is useful for when the dictionary is already known and will be set with - * SparseCoding::Dictionary(). - */ -class NothingInitializer -{ - public: - /** - * This function does not initialize the dictionary. This will cause problems - * for SparseCoding if the dictionary is not set manually before running the - * method. - */ - static void Initialize(const arma::mat& /* data */, - const size_t /* atoms */, - arma::mat& /* dictionary */) - { - // Do nothing! - } -}; - -} // namespace sparse_coding -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/random_initializer.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_coding/random_initializer.hpp deleted file mode 100644 index ce92064b7..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/random_initializer.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file random_initializer.hpp - * @author Nishant Mehta - * - * A very simple random dictionary initializer for SparseCoding; it is probably - * not a very good choice. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_CODING_RANDOM_INITIALIZER_HPP -#define MLPACK_METHODS_SPARSE_CODING_RANDOM_INITIALIZER_HPP - -#include - -namespace mlpack { -namespace sparse_coding { - -/** - * A DictionaryInitializer for use with the SparseCoding class. This provides a - * random, normally distributed dictionary, such that each atom has a norm of 1. - */ -class RandomInitializer -{ - public: - /** - * Initialize the dictionary randomly from a normal distribution, such that - * each atom has a norm of 1. This is simple enough to be included with the - * definition. - * - * @param data Dataset to use for initialization. - * @param atoms Number of atoms (columns) in the dictionary. - * @param dictionary Dictionary to initialize. - */ - static void Initialize(const arma::mat& data, - const size_t atoms, - arma::mat& dictionary) - { - // Create random dictionary. - dictionary.randn(data.n_rows, atoms); - - // Normalize each atom. - for (size_t j = 0; j < atoms; ++j) - dictionary.col(j) /= norm(dictionary.col(j), 2); - } -}; - -} // namespace sparse_coding -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/sparse_coding.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_coding/sparse_coding.hpp deleted file mode 100644 index 644f73c5b..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/sparse_coding.hpp +++ /dev/null @@ -1,285 +0,0 @@ -/** - * @file sparse_coding.hpp - * @author Nishant Mehta - * - * Definition of the SparseCoding class, which performs L1 (LASSO) or - * L1+L2 (Elastic Net)-regularized sparse coding with dictionary learning - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_HPP -#define MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_HPP - -#include -#include - -// Include our three simple dictionary initializers. -#include "nothing_initializer.hpp" -#include "data_dependent_random_initializer.hpp" -#include "random_initializer.hpp" - -namespace mlpack { -namespace sparse_coding { - -/** - * An implementation of Sparse Coding with Dictionary Learning that achieves - * sparsity via an l1-norm regularizer on the codes (LASSO) or an (l1+l2)-norm - * regularizer on the codes (the Elastic Net). - * - * Let d be the number of dimensions in the original space, m the number of - * training points, and k the number of atoms in the dictionary (the dimension - * of the learned feature space). The training data X is a d-by-m matrix where - * each column is a point and each row is a dimension. The dictionary D is a - * d-by-k matrix, and the sparse codes matrix Z is a k-by-m matrix. - * This program seeks to minimize the objective: - * - * \f[ - * \min_{D,Z} 0.5 ||X - D Z||_{F}^2\ + \lambda_1 \sum_{i=1}^m ||Z_i||_1 - * + 0.5 \lambda_2 \sum_{i=1}^m ||Z_i||_2^2 - * \f] - * - * subject to \f$ ||D_j||_2 <= 1 \f$ for \f$ 1 <= j <= k \f$ - * where typically \f$ lambda_1 > 0 \f$ and \f$ lambda_2 = 0 \f$. - * - * This problem is solved by an algorithm that alternates between a dictionary - * learning step and a sparse coding step. The dictionary learning step updates - * the dictionary D using a Newton method based on the Lagrange dual (see the - * paper below for details). The sparse coding step involves solving a large - * number of sparse linear regression problems; this can be done efficiently - * using LARS, an algorithm that can solve the LASSO or the Elastic Net (papers - * below). - * - * Here are those papers: - * - * @code - * @incollection{lee2007efficient, - * title = {Efficient sparse coding algorithms}, - * author = {Honglak Lee and Alexis Battle and Rajat Raina and Andrew Y. Ng}, - * booktitle = {Advances in Neural Information Processing Systems 19}, - * editor = {B. Sch\"{o}lkopf and J. Platt and T. Hoffman}, - * publisher = {MIT Press}, - * address = {Cambridge, MA}, - * pages = {801--808}, - * year = {2007} - * } - * @endcode - * - * @code - * @article{efron2004least, - * title={Least angle regression}, - * author={Efron, B. and Hastie, T. and Johnstone, I. and Tibshirani, R.}, - * journal={The Annals of statistics}, - * volume={32}, - * number={2}, - * pages={407--499}, - * year={2004}, - * publisher={Institute of Mathematical Statistics} - * } - * @endcode - * - * @code - * @article{zou2005regularization, - * title={Regularization and variable selection via the elastic net}, - * author={Zou, H. and Hastie, T.}, - * journal={Journal of the Royal Statistical Society Series B}, - * volume={67}, - * number={2}, - * pages={301--320}, - * year={2005}, - * publisher={Royal Statistical Society} - * } - * @endcode - * - * Note that the implementation here does not use the feature-sign search - * algorithm from Honglak Lee's paper, but instead the LARS algorithm suggested - * in that paper. - * - * When Train() is called, the dictionary is initialized using the - * DictionaryInitializationPolicy class. Possible choices include the - * RandomInitializer, which provides an entirely random dictionary, the - * DataDependentRandomInitializer, which provides a random dictionary based - * loosely on characteristics of the dataset, and the NothingInitializer, which - * does not initialize the dictionary -- instead, the user should set the - * dictionary using the Dictionary() mutator method. - * - * Once a dictionary is trained with Train(), another matrix may be encoded with - * the Encode() function. - * - * @tparam DictionaryInitializationPolicy The class to use to initialize the - * dictionary; must have 'void Initialize(const arma::mat& data, arma::mat& - * dictionary)' function. - */ -class SparseCoding -{ - public: - /** - * Set the parameters to SparseCoding. lambda2 defaults to 0. This - * constructor will train the model. If that is not desired, call the other - * constructor that does not take a data matrix. This constructor will also - * initialize the dictionary using the given DictionaryInitializer before - * training. - * - * If you want to initialize the dictionary to a custom matrix, consider - * either writing your own DictionaryInitializer class (with void - * Initialize(const arma::mat& data, arma::mat& dictionary) function), or call - * the constructor that does not take a data matrix, then call Dictionary() to - * set the dictionary matrix to a matrix of your choosing, and then call - * Train() with NothingInitializer (i.e. Train(data)). - * - * @param data Data matrix. - * @param atoms Number of atoms in dictionary. - * @param lambda1 Regularization parameter for l1-norm penalty. - * @param lambda2 Regularization parameter for l2-norm penalty. - * @param maxIterations Maximum number of iterations to run algorithm. If 0, - * the algorithm will run until convergence (or forever). - * @param objTolerance Tolerance for objective function. When an iteration of - * the algorithm produces an improvement smaller than this, the algorithm - * will terminate. - * @param newtonTolerance Tolerance for the Newton's method dictionary - * optimization step. - */ - template - SparseCoding(const arma::mat& data, - const size_t atoms, - const double lambda1, - const double lambda2 = 0, - const size_t maxIterations = 0, - const double objTolerance = 0.01, - const double newtonTolerance = 1e-6, - const DictionaryInitializer& initializer = - DictionaryInitializer()); - - /** - * Set the parameters to SparseCoding. lambda2 defaults to 0. This - * constructor will not train the model, and a subsequent call to Train() will - * be required before the model can encode points with Encode(). - * - * @param atoms Number of atoms in dictionary. - * @param lambda1 Regularization parameter for l1-norm penalty. - * @param lambda2 Regularization parameter for l2-norm penalty. - * @param maxIterations Maximum number of iterations to run algorithm. If 0, - * the algorithm will run until convergence (or forever). - * @param objTolerance Tolerance for objective function. When an iteration of - * the algorithm produces an improvement smaller than this, the algorithm - * will terminate. - * @param newtonTolerance Tolerance for the Newton's method dictionary - * optimization step. - */ - SparseCoding(const size_t atoms = 0, - const double lambda1 = 0, - const double lambda2 = 0, - const size_t maxIterations = 0, - const double objTolerance = 0.01, - const double newtonTolerance = 1e-6); - - /** - * Train the sparse coding model on the given dataset. - */ - template - void Train(const arma::mat& data, - const DictionaryInitializer& initializer = - DictionaryInitializer()); - - /** - * Sparse code each point in the given dataset via LARS, using the current - * dictionary and store the encoded data in the codes matrix. - * - * @param data Input data matrix to be encoded. - * @param codes Output codes matrix. - */ - void Encode(const arma::mat& data, arma::mat& codes); - - /** - * Learn dictionary via Newton method based on Lagrange dual. - * - * @param data Data matrix. - * @param codes Matrix of codes. - * @param adjacencies Indices of entries (unrolled column by column) of - * the coding matrix Z that are non-zero (the adjacency matrix for the - * bipartite graph of points and atoms). - * @return the norm of the gradient of the Lagrange dual with respect to - * the dual variables - */ - double OptimizeDictionary(const arma::mat& data, - const arma::mat& codes, - const arma::uvec& adjacencies); - - /** - * Project each atom of the dictionary back onto the unit ball, if necessary. - */ - void ProjectDictionary(); - - /** - * Compute the objective function. - */ - double Objective(const arma::mat& data, const arma::mat& codes) const; - - //! Access the dictionary. - const arma::mat& Dictionary() const { return dictionary; } - //! Modify the dictionary. - arma::mat& Dictionary() { return dictionary; } - - //! Access the number of atoms. - size_t Atoms() const { return atoms; } - //! Modify the number of atoms. - size_t& Atoms() { return atoms; } - - //! Access the L1 regularization term. - double Lambda1() const { return lambda1; } - //! Modify the L1 regularization term. - double& Lambda1() { return lambda1; } - - //! Access the L2 regularization term. - double Lambda2() const { return lambda2; } - //! Modify the L2 regularization term. - double& Lambda2() { return lambda2; } - - //! Get the maximum number of iterations. - size_t MaxIterations() const { return maxIterations; } - //! Modify the maximum number of iterations. - size_t& MaxIterations() { return maxIterations; } - - //! Get the objective tolerance. - double ObjTolerance() const { return objTolerance; } - //! Modify the objective tolerance. - double& ObjTolerance() { return objTolerance; } - - //! Get the tolerance for Newton's method (dictionary optimization step). - double NewtonTolerance() const { return newtonTolerance; } - //! Modify the tolerance for Newton's method (dictionary optimization step). - double& NewtonTolerance() { return newtonTolerance; } - - //! Serialize the sparse coding model. - template - void serialize(Archive& ar, const unsigned int /* version */); - - private: - //! Number of atoms. - size_t atoms; - - //! Dictionary (columns are atoms). - arma::mat dictionary; - - //! l1 regularization term. - double lambda1; - //! l2 regularization term. - double lambda2; - - //! Maximum number of iterations during training. - size_t maxIterations; - //! Tolerance for main objective. - double objTolerance; - //! Tolerance for Newton's method (dictionary training). - double newtonTolerance; -}; - -} // namespace sparse_coding -} // namespace mlpack - -// Include implementation. -#include "sparse_coding_impl.hpp" - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/sparse_coding_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_coding/sparse_coding_impl.hpp deleted file mode 100644 index 6dc617e02..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_coding/sparse_coding_impl.hpp +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @file sparse_coding_impl.hpp - * @author Nishant Mehta - * - * Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or - * l1+l2 (Elastic Net) regularization. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP -#define MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP - -// In case it hasn't already been included. -#include "sparse_coding.hpp" - -namespace mlpack { -namespace sparse_coding { - -template -SparseCoding::SparseCoding( - const arma::mat& data, - const size_t atoms, - const double lambda1, - const double lambda2, - const size_t maxIterations, - const double objTolerance, - const double newtonTolerance, - const DictionaryInitializer& initializer) : - atoms(atoms), - lambda1(lambda1), - lambda2(lambda2), - maxIterations(maxIterations), - objTolerance(objTolerance), - newtonTolerance(newtonTolerance) -{ - Train(data, initializer); -} - -template -void SparseCoding::Train( - const arma::mat& data, - const DictionaryInitializer& initializer) -{ - // Now, train. - Timer::Start("sparse_coding"); - - // Initialize the dictionary. - initializer.Initialize(data, atoms, dictionary); - - double lastObjVal = DBL_MAX; - - // Take the initial coding step, which has to happen before entering the main - // optimization loop. - Log::Info << "Initial coding step." << std::endl; - - arma::mat codes(atoms, data.n_cols); - Encode(data, codes); - arma::uvec adjacencies = find(codes); - - Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem)) - / ((double) (atoms * data.n_cols)) << "%." << std::endl; - Log::Info << " Objective value: " << Objective(data, codes) << "." - << std::endl; - - for (size_t t = 1; t != maxIterations; ++t) - { - // Print current iteration, and maximum number of iterations (if it isn't - // 0). - Log::Info << "Iteration " << t; - if (maxIterations != 0) - Log::Info << " of " << maxIterations; - Log::Info << "." << std::endl; - - // First step: optimize the dictionary. - Log::Info << "Performing dictionary step... " << std::endl; - OptimizeDictionary(data, codes, adjacencies); - Log::Info << " Objective value: " << Objective(data, codes) << "." - << std::endl; - - // Second step: perform the coding. - Log::Info << "Performing coding step..." << std::endl; - Encode(data, codes); - // Get the indices of all the nonzero elements in the codes. - adjacencies = find(codes); - Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem)) - / ((double) (atoms * data.n_cols)) << "%." << std::endl; - - // Find the new objective value and improvement so we can check for - // convergence. - double curObjVal = Objective(data, codes); - double improvement = lastObjVal - curObjVal; - Log::Info << " Objective value: " << curObjVal << " (improvement " - << std::scientific << improvement << ")." << std::endl; - - // Have we converged? - if (improvement < objTolerance) - { - Log::Info << "Converged within tolerance " << objTolerance << ".\n"; - break; - } - - lastObjVal = curObjVal; - } - - Timer::Stop("sparse_coding"); -} - -template -void SparseCoding::serialize(Archive& ar, const unsigned int /* version */) -{ - ar & BOOST_SERIALIZATION_NVP(atoms); - ar & BOOST_SERIALIZATION_NVP(dictionary); - ar & BOOST_SERIALIZATION_NVP(lambda1); - ar & BOOST_SERIALIZATION_NVP(lambda2); - ar & BOOST_SERIALIZATION_NVP(maxIterations); - ar & BOOST_SERIALIZATION_NVP(objTolerance); - ar & BOOST_SERIALIZATION_NVP(newtonTolerance); -} - -} // namespace sparse_coding -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_svm/sparse_svm_function.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_svm/sparse_svm_function.hpp deleted file mode 100644 index e70b16133..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_svm/sparse_svm_function.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @file sparse_svm_function.hpp - * @author Shikhar Bhardwaj - * - * Implementation of the hinge loss function for training a sparse SVM with the - * parallel SGD algorithm. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_SVM_SPARSE_SVM_FUNCTION_HPP -#define MLPACK_METHODS_SPARSE_SVM_SPARSE_SVM_FUNCTION_HPP - -#include - -class SparseSVMFunction -{ - public: - //! Nothing to do for the default constructor. - SparseSVMFunction() {} - - //! Member initialization constructor. - SparseSVMFunction(const arma::sp_mat& dataset, const arma::vec& labels); - - /** - * Shuffle the dataset. - */ - void Shuffle(); - - /** - * Evaluate the hinge loss function on the specified datapoints. - * - * @param parameters The parameters of the SVM. - * @param startId First index of the datapoints to use for function - * evaluation. - * @param batchSize Size of batch to process. - * @return The value of the loss function at the given parameters. - */ - double Evaluate(const arma::mat& parameters, - const size_t startId, - const size_t batchSize = 1); - - /** - * Evaluate the gradient the gradient of the hinge loss function, following - * the SparseFunctionType requirements on the Gradient function. - * - * @param parameters The parameters of the SVM. - * @param id Index of the datapoint to use for the gradient evaluation. - * @param gradient Sparse matrix to output the gradient into. - */ - template - void Gradient(const arma::mat& parameters, size_t id, GradType& gradient); - - //! Return the initial point for the optimization. - const arma::mat& InitialPoint() const { return initialPoint; } - //! Modify the initial point for the optimization. - arma::mat& InitialPoint() { return initialPoint; } - - //! Get the dataset. - const arma::sp_mat& Dataset() const { return dataset; } - //! Modify the dataset. - arma::sp_mat& Dataset() { return dataset; } - - //! Get the labels. - const arma::vec& Labels() const { return labels; } - //! Modify the labels. - arma::vec& Labels() { return labels; } - - //! Return the number of functions. - size_t NumFunctions(); - - private: - //! The initial point, from which to start the optimization. - arma::mat initialPoint; - - //! The datapoints for training. - arma::sp_mat dataset; - - //! The labels, y_i. - arma::vec labels; -}; - -// Include implementation -#include "sparse_svm_function_impl.hpp" - -#endif // MLPACK_METHODS_SPARSE_SVM_SPARSE_SVM_FUNCTION_HPP diff --git a/src/sdk/mlpack/include/mlpack/methods/sparse_svm/sparse_svm_function_impl.hpp b/src/sdk/mlpack/include/mlpack/methods/sparse_svm/sparse_svm_function_impl.hpp deleted file mode 100644 index 44f7e88f4..000000000 --- a/src/sdk/mlpack/include/mlpack/methods/sparse_svm/sparse_svm_function_impl.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file sparse_svm_function_impl.hpp - * @author Shikhar Bhardwaj - * - * Implementation of the hinge loss function for training a sparse SVM with the - * parallel SGD algorithm - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_METHODS_SPARSE_SVM_SPARSE_SVM_FUNCTION_IMPL_HPP -#define MLPACK_METHODS_SPARSE_SVM_SPARSE_SVM_FUNCTION_IMPL_HPP - -// In case it hasn't been included yet. -#include "sparse_svm_function.hpp" - -SparseSVMFunction::SparseSVMFunction( - const arma::sp_mat& dataset, const arma::vec& labels) : - dataset(dataset), - labels(math::MakeAlias(const_cast(labels), false)) -{ /* Nothing to do */ } - -void SparseSVMFunction::Shuffle() -{ - arma::sp_mat newDataset; - arma::vec newLabels; - - // Shuffle the data. - math::ShuffleData(dataset, labels, newDataset, newLabels); - - math::ClearAlias(newLabels); - - dataset = std::move(newDataset); - labels = std::move(newLabels); -} - -double SparseSVMFunction::Evaluate(const arma::mat& parameters, - const size_t firstId, - const size_t batchSize) -{ - // The hinge loss function. - const size_t lastId = firstId + batchSize - 1; - return arma::accu(arma::max(0.0, 1 - labels.subvec(firstId, lastId) % - dataset.cols(firstId, lastId) * - arma::repmat(parameters, 1, batchSize).t())); -} - -template -void SparseSVMFunction::Gradient( - const arma::mat& parameters, - const size_t firstId, - GradType& gradient, - const size_t batchSize) -{ - // Evaluate the gradient of the hinge loss function. - const size_t lastId = firstId + batchSize - 1; - arma::vec dots = 1 - labels.subvec(firstId, lastId) % - dataset.cols(firstId, lastId) * - arma::repmat(parameters, 1, batchSize).t(); - gradient = GradType(parameters.n_rows, 1); - for (size_t i = 0; i < batchSize; ++i) - { - if (dots[i] >= 0) - { - // Is this correct? - gradient += -1 * GradType(dataset.col(id) * labels(id)); - } - } -} - -size_t SparseSVMFunction::NumFunctions() -{ - // The number of points in the dataset is the number of functions, as this - // is a data dependent function. - return dataset.n_cols; -} - -#endif // MLPACK_METHODS_SPARSE_SVM_SPARSE_SVM_FUNCTION_IMPL_HPP diff --git a/src/sdk/mlpack/include/mlpack/mlpack_export.hpp b/src/sdk/mlpack/include/mlpack/mlpack_export.hpp deleted file mode 100644 index 3eaffc155..000000000 --- a/src/sdk/mlpack/include/mlpack/mlpack_export.hpp +++ /dev/null @@ -1,42 +0,0 @@ - -#ifndef MLPACK_EXPORT_H -#define MLPACK_EXPORT_H - -#ifdef MLPACK_STATIC_DEFINE -# define MLPACK_EXPORT -# define MLPACK_NO_EXPORT -#else -# ifndef MLPACK_EXPORT -# ifdef mlpack_EXPORTS - /* We are building this library */ -# define MLPACK_EXPORT -# else - /* We are using this library */ -# define MLPACK_EXPORT -# endif -# endif - -# ifndef MLPACK_NO_EXPORT -# define MLPACK_NO_EXPORT -# endif -#endif - -#ifndef MLPACK_DEPRECATED -# define MLPACK_DEPRECATED __attribute__ ((__deprecated__)) -#endif - -#ifndef MLPACK_DEPRECATED_EXPORT -# define MLPACK_DEPRECATED_EXPORT MLPACK_EXPORT MLPACK_DEPRECATED -#endif - -#ifndef MLPACK_DEPRECATED_NO_EXPORT -# define MLPACK_DEPRECATED_NO_EXPORT MLPACK_NO_EXPORT MLPACK_DEPRECATED -#endif - -#if 0 /* DEFINE_NO_DEPRECATED */ -# ifndef MLPACK_NO_DEPRECATED -# define MLPACK_NO_DEPRECATED -# endif -#endif - -#endif diff --git a/src/sdk/mlpack/include/mlpack/prereqs.hpp b/src/sdk/mlpack/include/mlpack/prereqs.hpp deleted file mode 100644 index a8e0a7080..000000000 --- a/src/sdk/mlpack/include/mlpack/prereqs.hpp +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @file prereqs.hpp - * - * The core includes that mlpack expects; standard C++ includes and Armadillo. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_PREREQS_HPP -#define MLPACK_PREREQS_HPP - -// Defining _USE_MATH_DEFINES should set M_PI. -#define _USE_MATH_DEFINES -#include - -// First, check if Armadillo was included before, warning if so. -#ifdef ARMA_INCLUDES -#pragma message "Armadillo was included before mlpack; this can sometimes cause\ - problems. It should only be necessary to include and not \ -." -#endif - -// Next, standard includes. -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// But if it's not defined, we'll do it. -#ifndef M_PI - #define M_PI 3.141592653589793238462643383279 -#endif - -// Give ourselves a nice way to force functions to be inline if we need. -#define force_inline -#if defined(__GNUG__) && !defined(DEBUG) - #undef force_inline - #define force_inline __attribute__((always_inline)) -#elif defined(_MSC_VER) && !defined(DEBUG) - #undef force_inline - #define force_inline __forceinline -#endif - -// Backport this functionality from C++14, if it doesn't exist. -#if __cplusplus <= 201103L -#if !defined(_MSC_VER) || _MSC_VER <= 1800 -namespace std { - -template -using enable_if_t = typename enable_if::type; - -} -#endif -#endif - -// Increase the number of template arguments for the boost list class. -#undef BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS -#undef BOOST_MPL_LIMIT_LIST_SIZE -#define BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS -#define BOOST_MPL_LIMIT_LIST_SIZE 50 - -// We'll need the necessary boost::serialization features, as well as what we -// use with mlpack. In Boost 1.59 and newer, the BOOST_PFTO code is no longer -// defined, but we still need to define it (as nothing) so that the mlpack -// serialization shim compiles. -#include -// We are not including boost/serialization/vector.hpp here. It is included in -// mlpack/core/boost_backport/boost_backport_serialization.hpp because of -// different behaviors of vector serialization in different versions of boost. -// #include -#include -// boost_backport.hpp handles the version and backporting of serialization (and -// other) features. -#include "mlpack/core/boost_backport/boost_backport_serialization.hpp" -// Boost 1.59 and newer don't use BOOST_PFTO, but our shims do. We can resolve -// any issue by setting BOOST_PFTO to nothing. -#ifndef BOOST_PFTO - #define BOOST_PFTO -#endif -#include -#include - -// If we have Boost 1.58 or older and are using C++14, the compilation is likely -// to fail due to boost::visitor issues. We will pre-emptively fail. -#if __cplusplus > 201103L && BOOST_VERSION < 105900 -#error Use of C++14 mode with Boost < 1.59 is known to cause compilation \ -problems. Instead specify the C++11 standard (-std=c++11 with gcc or clang), \ -or upgrade Boost to 1.59 or newer. -#endif - -// On Visual Studio, disable C4519 (default arguments for function templates) -// since it's by default an error, which doesn't even make any sense because -// it's part of the C++11 standard. -#ifdef _MSC_VER - #pragma warning(disable : 4519) - #define ARMA_USE_CXX11 -#endif - -// Now include Armadillo through the special mlpack extensions. -#include -#include - -// Ensure that the user isn't doing something stupid with their Armadillo -// defines. -#include - -// All code should have access to logging. -#include -#include - -// This can be removed with Visual Studio supports an OpenMP version with -// unsigned loop variables. -#ifdef _WIN32 - #define omp_size_t intmax_t -#else - #define omp_size_t size_t -#endif - -// We need to be able to mark functions deprecated. -#include - -#endif diff --git a/src/sdk/mlpack/include/mlpack/tests/custom_layer.hpp b/src/sdk/mlpack/include/mlpack/tests/custom_layer.hpp deleted file mode 100644 index da4bb422a..000000000 --- a/src/sdk/mlpack/include/mlpack/tests/custom_layer.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @file custom_layer.hpp - * @author Projyal Dev - * - * A simple custom layer mimicing SigmoidLayer for testing if custom - * layers work. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_TESTS_CUSTOM_LAYER_HPP -#define MLPACK_TESTS_CUSTOM_LAYER_HPP - -#include -#include - - -namespace mlpack { -namespace ann { - /** - * Standard Sigmoid layer. - */ - template < - class ActivationFunction = LogisticFunction, - typename InputDataType = arma::mat, - typename OutputDataType = arma::mat - > - using CustomLayer = BaseLayer< - ActivationFunction, InputDataType, OutputDataType>; - -} // namespace ann -} // namespace mlpack - -#endif // MLPACK_TESTS_CUSTOM_LAYER_HPP diff --git a/src/sdk/mlpack/include/mlpack/tests/main_tests/hmm_test_utils.hpp b/src/sdk/mlpack/include/mlpack/tests/main_tests/hmm_test_utils.hpp deleted file mode 100644 index cf9d06fcc..000000000 --- a/src/sdk/mlpack/include/mlpack/tests/main_tests/hmm_test_utils.hpp +++ /dev/null @@ -1,163 +0,0 @@ -/** - * @file hmm_test_utils.hpp - * @author Daivik Nema - * - * Structs for initializing and training HMMs (either of Discrete, Gaussian or - * GMM HMMs). These structs are passed as template parameters to the - * PerformAction function of an HMMModel object. These structs have been adapted - * from the structs in mlpack/methods/hmm/hmm_train_main.cpp. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_TESTS_MAIN_TESTS_HMM_TEST_UTILS_HPP -#define MLPACK_TESTS_MAIN_TESTS_HMM_TEST_UTILS_HPP - -#include -#include - -struct InitHMMModel -{ - template - static void Apply(HMMType& hmm, vector* trainSeq) - { - const size_t states = 2; - - // Create the initialized-to-zero model. - Create(hmm, *trainSeq, states); - - // Initializing the emission distribution depends on the distribution. - // Therefore we have to use the helper functions. - RandomInitialize(hmm.Emission()); - } - - //! Helper function to create discrete HMM. - static void Create(HMM& hmm, - vector& trainSeq, - size_t states, - double tolerance = 1e-05) - { - // Maximum observation is necessary so we know how to train the discrete - // distribution. - arma::Col maxEmissions(trainSeq[0].n_rows); - maxEmissions.zeros(); - for (vector::iterator it = trainSeq.begin(); it != trainSeq.end(); - ++it) - { - arma::Col maxSeqs = - arma::conv_to>::from(arma::max(*it, 1)) + 1; - maxEmissions = arma::max(maxEmissions, maxSeqs); - } - - hmm = HMM(size_t(states), - DiscreteDistribution(maxEmissions), tolerance); - } - - static void Create(HMM& hmm, - vector& trainSeq, - size_t states, - double tolerance = 1e-05) - { - // Find dimension of the data. - const size_t dimensionality = trainSeq[0].n_rows; - - // Verify dimensionality of data. - for (size_t i = 0; i < trainSeq.size(); ++i) - { - if (trainSeq[i].n_rows != dimensionality) - { - Log::Fatal << "Observation sequence " << i << " dimensionality (" - << trainSeq[i].n_rows << " is incorrect (should be " - << dimensionality << ")!" << endl; - } - } - - // Get the model and initialize it. - hmm = HMM(size_t(states), - GaussianDistribution(dimensionality), tolerance); - } - - static void Create(HMM& hmm, - vector& trainSeq, - size_t states, - double tolerance = 1e-05) - { - // Find dimension of the data. - const size_t dimensionality = trainSeq[0].n_rows; - const int gaussians = 2; - - if (gaussians == 0) - { - Log::Fatal << "Number of gaussians for each GMM must be specified " - << "when type = 'gmm'!" << endl; - } - - if (gaussians < 0) - { - Log::Fatal << "Invalid number of gaussians (" << gaussians << "); must " - << "be greater than or equal to 1." << endl; - } - - // Create HMM object. - hmm = HMM(size_t(states), GMM(size_t(gaussians), dimensionality), - tolerance); - } - - //! Helper function for discrete emission distributions. - static void RandomInitialize(vector& e) - { - for (size_t i = 0; i < e.size(); ++i) - { - e[i].Probabilities().randu(); - e[i].Probabilities() /= arma::accu(e[i].Probabilities()); - } - } - - static void RandomInitialize(vector& e) - { - for (size_t i = 0; i < e.size(); ++i) - { - const size_t dimensionality = e[i].Mean().n_rows; - e[i].Mean().randu(); - // Generate random covariance. - arma::mat r = arma::randu(dimensionality, dimensionality); - e[i].Covariance(r * r.t()); - } - } - - static void RandomInitialize(vector& e) - { - for (size_t i = 0; i < e.size(); ++i) - { - // Random weights. - e[i].Weights().randu(); - e[i].Weights() /= arma::accu(e[i].Weights()); - - // Random means and covariances. - for (int g = 0; g < 2; ++g) - { - const size_t dimensionality = e[i].Component(g).Mean().n_rows; - e[i].Component(g).Mean().randu(); - - // Generate random covariance. - arma::mat r = arma::randu(dimensionality, - dimensionality); - e[i].Component(g).Covariance(r * r.t()); - } - } - } -}; - -struct TrainHMMModel -{ - template - static void Apply(HMMType& hmm, vector* trainSeq) - { - // For now, perform unsupervised (Baum-Welch) training. - hmm.Train(*trainSeq); - } -}; - -#endif diff --git a/src/sdk/mlpack/include/mlpack/tests/main_tests/test_helper.hpp b/src/sdk/mlpack/include/mlpack/tests/main_tests/test_helper.hpp deleted file mode 100644 index 12cb72c71..000000000 --- a/src/sdk/mlpack/include/mlpack/tests/main_tests/test_helper.hpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @file test_helper.hpp - * @author Eugene Freyman - * - * Helper functions for testing. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_TESTS_MAIN_TESTS_TEST_HELPER_HPP -#define MLPACK_TESTS_MAIN_TESTS_TEST_HELPER_HPP - -#include - -namespace mlpack { -namespace util { - -/** - * Utility function that is used in binding tests for setting a parameter and - * marking it as passed; it uses copy semantics for lvalues and move semantics - * for rvalues. - * - * @param name Name of parameter to set. - * @param value Value to set parameter to. - */ -template -void SetInputParam(const std::string& name, T&& value) -{ - CLI::GetParam::type>(name) = - std::forward(value); - CLI::SetPassed(name); -} - -} // namespace util -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/tests/mock_categorical_data.hpp b/src/sdk/mlpack/include/mlpack/tests/mock_categorical_data.hpp deleted file mode 100644 index dc9b15a21..000000000 --- a/src/sdk/mlpack/include/mlpack/tests/mock_categorical_data.hpp +++ /dev/null @@ -1,116 +0,0 @@ -/** - * @file mock_categorical_data.hpp - * - * Generate categorical dataset for tests. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_TESTS_MOCK_CATEGORICAL_DATA_HPP -#define MLPACK_TESTS_MOCK_CATEGORICAL_DATA_HPP - -#include -#include - -/** - * Create a mock categorical dataset for testing. - */ -inline void MockCategoricalData(arma::mat& d, - arma::Row& l, - mlpack::data::DatasetInfo& datasetInfo) -{ - // We'll build a spiral dataset plus two noisy categorical features. We need - // to build the distributions for the categorical features (they'll be - // discrete distributions). - mlpack::distribution::DiscreteDistribution c1[5]; - // The distribution will be automatically normalized. - for (size_t i = 0; i < 5; ++i) - { - std::vector probs; - probs.push_back(arma::vec(4, arma::fill::randu)); - c1[i] = mlpack::distribution::DiscreteDistribution(probs); - } - - mlpack::distribution::DiscreteDistribution c2[5]; - for (size_t i = 0; i < 5; ++i) - { - std::vector probs; - probs.push_back(arma::vec(2, arma::fill::randu)); - c2[i] = mlpack::distribution::DiscreteDistribution(probs); - } - - arma::mat spiralDataset(4, 4000); - arma::Row labels(4000); - for (size_t i = 0; i < 4000; ++i) - { - // One circle every 2000 samples. Plus some noise. - const double magnitude = 2.0 + (double(i) / 200.0) + - 0.5 * mlpack::math::Random(); - const double angle = (i % 200) * (2 * M_PI) + mlpack::math::Random(); - - const double x = magnitude * cos(angle); - const double y = magnitude * sin(angle); - - spiralDataset(0, i) = x; - spiralDataset(1, i) = y; - - // Set categorical features c1 and c2. - if (i < 800) - { - spiralDataset(2, i) = c1[1].Random()[0]; - spiralDataset(3, i) = c2[1].Random()[0]; - labels[i] = 1; - } - else if (i < 1600) - { - spiralDataset(2, i) = c1[3].Random()[0]; - spiralDataset(3, i) = c2[3].Random()[0]; - labels[i] = 3; - } - else if (i < 2400) - { - spiralDataset(2, i) = c1[2].Random()[0]; - spiralDataset(3, i) = c2[2].Random()[0]; - labels[i] = 2; - } - else if (i < 3200) - { - spiralDataset(2, i) = c1[0].Random()[0]; - spiralDataset(3, i) = c2[0].Random()[0]; - labels[i] = 0; - } - else - { - spiralDataset(2, i) = c1[4].Random()[0]; - spiralDataset(3, i) = c2[4].Random()[0]; - labels[i] = 4; - } - } - - // Now create the dataset info. - datasetInfo = mlpack::data::DatasetInfo(4); - datasetInfo.Type(2) = mlpack::data::Datatype::categorical; - datasetInfo.Type(3) = mlpack::data::Datatype::categorical; - // Set mappings. - datasetInfo.MapString("0", 2); - datasetInfo.MapString("1", 2); - datasetInfo.MapString("2", 2); - datasetInfo.MapString("3", 2); - datasetInfo.MapString("0", 3); - datasetInfo.MapString("1", 3); - - // Now shuffle the dataset. - arma::uvec indices = arma::shuffle(arma::linspace(0, 3999, - 4000)); - d = arma::mat(4, 4000); - l = arma::Row(4000); - for (size_t i = 0; i < 4000; ++i) - { - d.col(i) = spiralDataset.col(indices[i]); - l[i] = labels[indices[i]]; - } -} - -#endif diff --git a/src/sdk/mlpack/include/mlpack/tests/serialization.hpp b/src/sdk/mlpack/include/mlpack/tests/serialization.hpp deleted file mode 100644 index 73699bf6e..000000000 --- a/src/sdk/mlpack/include/mlpack/tests/serialization.hpp +++ /dev/null @@ -1,325 +0,0 @@ -/** - * @file serialization.hpp - * @author Ryan Curtin - * - * Miscellaneous utility functions for serialization tests. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_TESTS_SERIALIZATION_HPP -#define MLPACK_TESTS_SERIALIZATION_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "test_tools.hpp" - -namespace mlpack { - -// Test function for loading and saving Armadillo objects. -template -void TestArmadilloSerialization(arma::Cube& x) -{ - // First save it. - // Use type_info name to get unique file name for serialization test files. - std::string fileName = FilterFileName(typeid(IArchiveType).name()); - std::ofstream ofs(fileName, std::ios::binary); - bool success = true; - - { - OArchiveType o(ofs); - - try - { - o << BOOST_SERIALIZATION_NVP(x); - } - catch (boost::archive::archive_exception& e) - { - success = false; - } - } - - BOOST_REQUIRE_EQUAL(success, true); - ofs.close(); - - // Now load it. - arma::Cube orig(x); - success = true; - std::ifstream ifs(fileName, std::ios::binary); - - { - IArchiveType i(ifs); - - try - { - i >> BOOST_SERIALIZATION_NVP(x); - } - catch (boost::archive::archive_exception& e) - { - success = false; - } - } - ifs.close(); - - remove(fileName.c_str()); - - BOOST_REQUIRE_EQUAL(success, true); - - BOOST_REQUIRE_EQUAL(x.n_rows, orig.n_rows); - BOOST_REQUIRE_EQUAL(x.n_cols, orig.n_cols); - BOOST_REQUIRE_EQUAL(x.n_elem_slice, orig.n_elem_slice); - BOOST_REQUIRE_EQUAL(x.n_slices, orig.n_slices); - BOOST_REQUIRE_EQUAL(x.n_elem, orig.n_elem); - - for (size_t slice = 0; slice != x.n_slices; ++slice) - { - const auto& origSlice = orig.slice(slice); - const auto& xSlice = x.slice(slice); - for (size_t i = 0; i < x.n_cols; ++i) - { - for (size_t j = 0; j < x.n_rows; ++j) - { - if (double(origSlice(j, i)) == 0.0) - BOOST_REQUIRE_SMALL(double(xSlice(j, i)), 1e-8); - else - BOOST_REQUIRE_CLOSE(double(origSlice(j, i)), double(xSlice(j, i)), - 1e-8); - } - } - } -} - -// Test all serialization strategies. -template -void TestAllArmadilloSerialization(arma::Cube& x) -{ - TestArmadilloSerialization(x); - TestArmadilloSerialization(x); - TestArmadilloSerialization(x); -} - -// Test function for loading and saving Armadillo objects. -template -void TestArmadilloSerialization(MatType& x) -{ - // First save it. - std::string fileName = FilterFileName(typeid(IArchiveType).name()); - std::ofstream ofs(fileName, std::ios::binary); - bool success = true; - - { - OArchiveType o(ofs); - - try - { - o << BOOST_SERIALIZATION_NVP(x); - } - catch (boost::archive::archive_exception& e) - { - success = false; - } - } - - BOOST_REQUIRE_EQUAL(success, true); - ofs.close(); - - // Now load it. - MatType orig(x); - success = true; - std::ifstream ifs(fileName, std::ios::binary); - - { - IArchiveType i(ifs); - - try - { - i >> BOOST_SERIALIZATION_NVP(x); - } - catch (boost::archive::archive_exception& e) - { - success = false; - } - } - ifs.close(); - - remove(fileName.c_str()); - - BOOST_REQUIRE_EQUAL(success, true); - - BOOST_REQUIRE_EQUAL(x.n_rows, orig.n_rows); - BOOST_REQUIRE_EQUAL(x.n_cols, orig.n_cols); - BOOST_REQUIRE_EQUAL(x.n_elem, orig.n_elem); - - for (size_t i = 0; i < x.n_cols; ++i) - for (size_t j = 0; j < x.n_rows; ++j) - if (double(orig(j, i)) == 0.0) - BOOST_REQUIRE_SMALL(double(x(j, i)), 1e-8); - else - BOOST_REQUIRE_CLOSE(double(orig(j, i)), double(x(j, i)), 1e-8); -} - -// Test all serialization strategies. -template -void TestAllArmadilloSerialization(MatType& x) -{ - TestArmadilloSerialization(x); - TestArmadilloSerialization(x); - TestArmadilloSerialization(x); -} - -// Save and load an mlpack object. -// The re-loaded copy is placed in 'newT'. -template -void SerializeObject(T& t, T& newT) -{ - std::string fileName = FilterFileName(typeid(T).name()); - std::ofstream ofs(fileName, std::ios::binary); - bool success = true; - - { - OArchiveType o(ofs); - - try - { - o << BOOST_SERIALIZATION_NVP(t); - } - catch (boost::archive::archive_exception& e) - { - std::cerr << e.what() << std::endl; - success = false; - } - } - ofs.close(); - - BOOST_REQUIRE_EQUAL(success, true); - - std::ifstream ifs(fileName, std::ios::binary); - - { - IArchiveType i(ifs); - - try - { - i >> BOOST_SERIALIZATION_NVP(newT); - } - catch (boost::archive::archive_exception& e) - { - std::cout << e.what() << "\n"; - success = false; - } - } - ifs.close(); - - remove(fileName.c_str()); - - BOOST_REQUIRE_EQUAL(success, true); -} - -// Test mlpack serialization with all three archive types. -template -void SerializeObjectAll(T& t, T& xmlT, T& textT, T& binaryT) -{ - SerializeObject(t, xmlT); - SerializeObject(t, textT); - SerializeObject(t, binaryT); -} - -// Save and load a non-default-constructible mlpack object. -template -void SerializePointerObject(T* t, T*& newT) -{ - std::string fileName = FilterFileName(typeid(T).name()); - std::ofstream ofs(fileName, std::ios::binary); - bool success = true; - - { - OArchiveType o(ofs); - try - { - o << BOOST_SERIALIZATION_NVP(t); - } - catch (boost::archive::archive_exception& e) - { - std::cout << e.what() << "\n"; - success = false; - } - } - ofs.close(); - - BOOST_REQUIRE_EQUAL(success, true); - - std::ifstream ifs(fileName, std::ios::binary); - - { - IArchiveType i(ifs); - - try - { - i >> BOOST_SERIALIZATION_NVP(newT); - } - catch (std::exception& e) - { - std::cout << e.what() << "\n"; - success = false; - } - } - ifs.close(); - - remove(fileName.c_str()); - - BOOST_REQUIRE_EQUAL(success, true); -} - -template -void SerializePointerObjectAll(T* t, T*& xmlT, T*& textT, T*& binaryT) -{ - SerializePointerObject(t, textT); - SerializePointerObject(t, binaryT); - SerializePointerObject(t, xmlT); -} - -// Utility function to check the equality of two Armadillo matrices. -void CheckMatrices(const arma::mat& x, - const arma::mat& xmlX, - const arma::mat& textX, - const arma::mat& binaryX); - -void CheckMatrices(const arma::Mat& x, - const arma::Mat& xmlX, - const arma::Mat& textX, - const arma::Mat& binaryX); - -void CheckMatrices(const arma::cube& x, - const arma::cube& xmlX, - const arma::cube& textX, - const arma::cube& binaryX); - -} // namespace mlpack - -#endif diff --git a/src/sdk/mlpack/include/mlpack/tests/test_function_tools.hpp b/src/sdk/mlpack/include/mlpack/tests/test_function_tools.hpp deleted file mode 100644 index 7d69c7ba6..000000000 --- a/src/sdk/mlpack/include/mlpack/tests/test_function_tools.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @file test_function_tools.hpp - * @author Marcus Edel - * - * This file provides some useful test function methods. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_TESTS_TEST_FUNCTION_TOOLS_HPP -#define MLPACK_TESTS_TEST_FUNCTION_TOOLS_HPP - -#include - -#include - -using namespace mlpack; -using namespace mlpack::distribution; -using namespace mlpack::regression; - -/** - * Create the data for the a logistic regression test. - * - * @param data Matrix object to store the data into. - * @param testData Matrix object to store the test data into. - * @param shuffledData Matrix object to store the shuffled data into. - * @param responses Matrix object to store the overall responses into. - * @param testResponses Matrix object to store the test responses into. - * @param shuffledResponses Matrix object to store the shuffled responses into. - */ -inline void LogisticRegressionTestData(arma::mat& data, - arma::mat& testData, - arma::mat& shuffledData, - arma::Row& responses, - arma::Row& testResponses, - arma::Row& shuffledResponses) -{ - // Generate a two-Gaussian dataset. - GaussianDistribution g1(arma::vec("1.0 1.0 1.0"), arma::eye(3, 3)); - GaussianDistribution g2(arma::vec("9.0 9.0 9.0"), arma::eye(3, 3)); - - data = arma::mat(3, 1000); - responses = arma::Row(1000); - for (size_t i = 0; i < 500; ++i) - { - data.col(i) = g1.Random(); - responses[i] = 0; - } - for (size_t i = 500; i < 1000; ++i) - { - data.col(i) = g2.Random(); - responses[i] = 1; - } - - // Shuffle the dataset. - arma::uvec indices = arma::shuffle(arma::linspace(0, - data.n_cols - 1, data.n_cols)); - shuffledData = arma::mat(3, 1000); - shuffledResponses = arma::Row(1000); - for (size_t i = 0; i < data.n_cols; ++i) - { - shuffledData.col(i) = data.col(indices[i]); - shuffledResponses[i] = responses[indices[i]]; - } - - // Create a test set. - testData = arma::mat(3, 1000); - testResponses = arma::Row(1000); - for (size_t i = 0; i < 500; ++i) - { - testData.col(i) = g1.Random(); - testResponses[i] = 0; - } - for (size_t i = 500; i < 1000; ++i) - { - testData.col(i) = g2.Random(); - testResponses[i] = 1; - } -} - -#endif diff --git a/src/sdk/mlpack/include/mlpack/tests/test_tools.hpp b/src/sdk/mlpack/include/mlpack/tests/test_tools.hpp deleted file mode 100644 index 8d6bae563..000000000 --- a/src/sdk/mlpack/include/mlpack/tests/test_tools.hpp +++ /dev/null @@ -1,175 +0,0 @@ -/** - * @file test_tools.hpp - * @author Ryan Curtin - * - * This file includes some useful macros for tests. - * - * mlpack is free software; you may redistribute it and/or modify it under the - * terms of the 3-clause BSD license. You should have received a copy of the - * 3-clause BSD license along with mlpack. If not, see - * http://www.opensource.org/licenses/BSD-3-Clause for more information. - */ -#ifndef MLPACK_TESTS_TEST_TOOLS_HPP -#define MLPACK_TESTS_TEST_TOOLS_HPP - -#include -#include - -// Require the approximation L to be within a relative error of E respect to the -// actual value R. -#define REQUIRE_RELATIVE_ERR(L, R, E) \ - BOOST_REQUIRE_LE(std::abs((R) - (L)), (E) * std::abs(R)) - -// Check the values of two matrices. -inline void CheckMatrices(const arma::mat& a, - const arma::mat& b, - double tolerance = 1e-5) -{ - BOOST_REQUIRE_EQUAL(a.n_rows, b.n_rows); - BOOST_REQUIRE_EQUAL(a.n_cols, b.n_cols); - - for (size_t i = 0; i < a.n_elem; ++i) - { - if (std::abs(a[i]) < tolerance / 2) - BOOST_REQUIRE_SMALL(b[i], tolerance / 2); - else - BOOST_REQUIRE_CLOSE(a[i], b[i], tolerance); - } -} - -// Check the values of two unsigned matrices. -inline void CheckMatrices(const arma::Mat& a, - const arma::Mat& b) -{ - BOOST_REQUIRE_EQUAL(a.n_rows, b.n_rows); - BOOST_REQUIRE_EQUAL(a.n_cols, b.n_cols); - - for (size_t i = 0; i < a.n_elem; ++i) - BOOST_REQUIRE_EQUAL(a[i], b[i]); -} - -// Check the values of two cubes. -inline void CheckMatrices(const arma::cube& a, - const arma::cube& b, - double tolerance = 1e-5) -{ - BOOST_REQUIRE_EQUAL(a.n_rows, b.n_rows); - BOOST_REQUIRE_EQUAL(a.n_cols, b.n_cols); - BOOST_REQUIRE_EQUAL(a.n_slices, b.n_slices); - - for (size_t i = 0; i < a.n_elem; ++i) - { - if (std::abs(a[i]) < tolerance / 2) - BOOST_REQUIRE_SMALL(b[i], tolerance / 2); - else - BOOST_REQUIRE_CLOSE(a[i], b[i], tolerance); - } -} - -// Check if two matrices are different. -inline void CheckMatricesNotEqual(const arma::mat& a, - const arma::mat& b, - double tolerance = 1e-5) -{ - bool areDifferent = false; - - // Only check the elements if the dimensions are equal. - if (a.n_rows == b.n_rows && a.n_cols == b.n_cols) - { - for (size_t i = 0; i < a.n_elem; ++i) - { - if (std::abs(a[i]) < tolerance / 2 && - b[i] > tolerance / 2) - { - areDifferent = true; - break; - } - else if (std::abs(a[i] - b[i]) > tolerance) - { - areDifferent = true; - break; - } - } - } - else - areDifferent = true; - - if (!areDifferent) - BOOST_ERROR("The matrices are equal."); -} - -// Check if two unsigned matrices are different. -inline void CheckMatricesNotEqual(const arma::Mat& a, - const arma::Mat& b) -{ - bool areDifferent = false; - - // Only check the elements if the dimensions are equal. - if (a.n_rows == b.n_rows && a.n_cols == b.n_cols) - { - for (size_t i = 0; i < a.n_elem; ++i) - { - if (a[i] != b[i]) - { - areDifferent = true; - break; - } - } - } - else - areDifferent = true; - - if (!areDifferent) - BOOST_ERROR("The matrices are equal."); -} - -// Check if two cubes are different. -inline void CheckMatricesNotEqual(const arma::cube& a, - const arma::cube& b, - double tolerance = 1e-5) -{ - bool areDifferent = false; - - // Only check the elements if the dimensions are equal. - if (a.n_rows == b.n_rows && a.n_cols == b.n_cols && - a.n_slices == b.n_slices) - { - for (size_t i = 0; i < a.n_elem; ++i) - { - if (std::abs(a[i]) < tolerance / 2 && - b[i] > tolerance / 2) - { - areDifferent = true; - break; - } - else if (std::abs(a[i] - b[i]) > tolerance) - { - areDifferent = true; - break; - } - } - } - else - areDifferent = true; - - if (!areDifferent) - BOOST_ERROR("The matrices are equal."); -} - - -// Filter typeinfo string to generate unique filenames for serialization tests. -inline std::string FilterFileName(const std::string& inputString) -{ - // Take the last valid 32 characters for the filename. - std::string fileName; - for (auto it = inputString.rbegin(); it != inputString.rend() && - fileName.size() != 32; ++it) - { - if (std::isalnum(*it)) - fileName.push_back(*it); - } - - return fileName; -} - -#endif diff --git a/src/sdk/mlpack/lib/libboost_program_options.a b/src/sdk/mlpack/lib/libboost_program_options.a deleted file mode 100644 index 8f1241902..000000000 Binary files a/src/sdk/mlpack/lib/libboost_program_options.a and /dev/null differ diff --git a/src/sdk/mlpack/lib/libboost_serialization.a b/src/sdk/mlpack/lib/libboost_serialization.a deleted file mode 100644 index 89b5137a0..000000000 Binary files a/src/sdk/mlpack/lib/libboost_serialization.a and /dev/null differ diff --git a/src/sdk/mlpack/lib/libboost_unit_test_framework.a b/src/sdk/mlpack/lib/libboost_unit_test_framework.a deleted file mode 100644 index 747a7add5..000000000 Binary files a/src/sdk/mlpack/lib/libboost_unit_test_framework.a and /dev/null differ diff --git a/src/sdk/mlpack/lib/libboost_wserialization.a b/src/sdk/mlpack/lib/libboost_wserialization.a deleted file mode 100644 index 9477c4582..000000000 Binary files a/src/sdk/mlpack/lib/libboost_wserialization.a and /dev/null differ diff --git a/src/sdk/mlpack/lib/libmlpack.a b/src/sdk/mlpack/lib/libmlpack.a deleted file mode 100644 index 00956cb22..000000000 Binary files a/src/sdk/mlpack/lib/libmlpack.a and /dev/null differ diff --git a/tools/devcmd.cmd b/tools/devcmd.cmd index 63ce9adbc..887a43df9 100644 --- a/tools/devcmd.cmd +++ b/tools/devcmd.cmd @@ -1 +1,3 @@ -@"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\Tools\VsDevCmd.bat" \ No newline at end of file +rem @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\Tools\VsDevCmd.bat" + +@"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Auxiliary\Build\vcvars64.bat" \ No newline at end of file