首页 > 代码库 > 使用 JavaScript 编写优化算法 (1)
使用 JavaScript 编写优化算法 (1)
之前一直用Python来写优化算法,为了增强 JS 的熟练程度,开始将原有的代码改写成 JS。采用的工具包括 node.js + Grunt + nodeunit + github + npm + travis-ci。
最初的版本采用过程式的方式实现,没有采用面向对象或事件驱动的模式。
#!/usr/bin/env node --harmony// Random Search"use strict";var util = require("util");function objective_function(v) { return v.map(function(x) { return x*x; }).reduce(function(a, b) { return a+b; });}function random_vector(min_max) { return min_max.map(function(x) { return x[0] + (x[1] - x[0]) * Math.random(); });}function search(search_space, max_iteration) { var best = {}; for (var iteration = 0; iteration < max_iteration; iteration++) { var candidate = { ‘vector‘: random_vector(search_space) }; candidate[‘cost‘] = objective_function(candidate[‘vector‘]); //console.log(candidate); if (iteration === 0 || candidate[‘cost‘] < best[‘cost‘]) { best = candidate; } console.log(‘ > iteration=‘ + (iteration+1) + ‘, best=‘ + best[‘cost‘]); } return best;}function generate_array(element, repeat) { return new Array(repeat+1).join(1).split(‘‘).map(function(){return element;});}function run () { var problem_size = 2; var search_space = generate_array([-5, 5], problem_size); var max_iteration = 100; var best = search(search_space, max_iteration); console.log("Done. Best Solution: " + util.inspect(best));}exports.objective_function = objective_function;exports.random_vector = random_vector;exports.generate_array = generate_array;exports.search = search;exports.run = run;
调用方式很简单。
var rs = require(‘clever_algorithms_js‘).random_search;rs.run();
单元测试:
var random_search = require(‘../../lib/stochastic/random_search‘);exports[‘objective‘] = function (test) { test.equal(random_search.objective_function([1, 2]), 5); test.done();};exports[‘random_vector‘] = function (test) { var rv = random_search.random_vector([[1, 2], [2, 3]]); test.equal(rv.length, 2); test.ok(1 <= rv[0] && rv[0] <= 2); test.ok(2 <= rv[1] && rv[1] <= 3); test.done();};exports[‘generate_array‘] = function (test) { var a = random_search.generate_array([-5, 5], 2); test.equal(a.length, 2); test.deepEqual(a, [[-5,5], [-5,5]]); test.done();};exports[‘search‘] = function (test) { var problem_size = 2, search_space = random_search.generate_array([-5, 5], problem_size), max_iter = 100; var best = random_search.search(search_space, max_iter); test.notEqual(best, {}); test.ok(-5 <= best[‘cost‘] && best[‘cost‘] <= 5); test.done();};
[1] https://www.npmjs.org/package/clever_algorithms_js
[2] https://github.com/fox000002/clever_algorithms_js
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。