Ensmallen使用小结

发布时间 2023-03-29 17:40:07作者: 师怀

Ensmallen 使用小结

Ensmallen 介绍

Ensmallen 是一个用于数值优化的库,在你有一个代价函数需要求解最小值时,可以用 ensmallen 来实现,其包含了一些现在常用的全局和局部优化器。ensmallen 是一个用于非线性数值优化的高质量 c++库。官网

下面是一段示例代码

// autoDiffent.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <armadillo>
#include <ensmallen.hpp>
using namespace ens;
using namespace arma;
using namespace std;

class ArbitraryFunctionType1
{
public:
	// This should return f(x).
	double Evaluate(const arma::mat& x) {
		double x0 = x.row(0)[0];
		double y;
		if (x0 < -1) {
			y = pow(x0 + 2, 2) - 1;
		}
		else {
			y = std::sqrt(std::pow(x0, 3) - pow(x0, 2) - x0 + 1);
		}
		//return std::abs(2 * std::pow(arma::norm(x), 2.0) - 10);
		return y;
	};
};

int main()
{
	arma::mat x("-5");
	std::cout << "Optimal x: " << x << std::endl;
	ens::SA<> optimizer;
	ArbitraryFunctionType1 F;
	optimizer.Optimize(F, x);

	std::cout << "after x: " << x << std::endl;

	system("Pause");
	return 0;
}

一些点

  1. 新的 ensmallen 库要求支持 C++11 ,vs2013 不支持、2017 可以。