楼主: ReneeBK
993 2

【JavaScript】kmeans using JavaScript [推广有奖]

  • 1关注
  • 62粉丝

VIP

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49407 个
通用积分
51.8704
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57815 点
帖子
4006
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

相似文件 换一批

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
kmeans

K-means clustering in JavaScript

K-means clustering aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean.

Installation

npm install ml-kmeans

API Documentation

本帖隐藏的内容

kmeans-master.zip (1.18 MB)




二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Javascript script kmeans scrip means

本帖被以下文库推荐

沙发
ReneeBK 发表于 2017-4-16 04:19:06 |只看作者 |坛友微信交流群
  1. 'use strict';

  2. const utils = require('./utils');
  3. const init = require('./initialization');
  4. const KMeansResult = require('./KMeansResult');
  5. const squaredDistance = require('ml-distance-euclidean').squared;

  6. const defaultOptions = {
  7.     maxIterations: 100,
  8.     tolerance: 1e-6,
  9.     withIterations: false,
  10.     initialization: 'mostDistant',
  11.     distanceFunction: squaredDistance
  12. };

  13. /**
  14. * Each step operation for kmeans
  15. * @ignore
  16. * @param {Array<Array<number>>} centers - K centers in format [x,y,z,...]
  17. * @param {Array<Array<number>>} data - Points [x,y,z,...] to cluster
  18. * @param {Array<number>} clusterID - Cluster identifier for each data dot
  19. * @param {number} K - Number of clusters
  20. * @param {object} [options] - Option object
  21. * @param {number} iterations - Current number of iterations
  22. * @return {KMeansResult}
  23. */
  24. function step(centers, data, clusterID, K, options, iterations) {
  25.     clusterID = utils.updateClusterID(data, centers, clusterID, options.distanceFunction);
  26.     var newCenters = utils.updateCenters(data, clusterID, K);
  27.     var converged = utils.converged(newCenters, centers, options.distanceFunction, options.tolerance);
  28.     return new KMeansResult(clusterID, newCenters, converged, iterations, options.distanceFunction);
  29. }

  30. /**
  31. * Generator version for the algorithm
  32. * @ignore
  33. * @param {Array<Array<number>>} centers - K centers in format [x,y,z,...]
  34. * @param {Array<Array<number>>} data - Points [x,y,z,...] to cluster
  35. * @param {Array<number>} clusterID - Cluster identifier for each data dot
  36. * @param {number} K - Number of clusters
  37. * @param {object} [options] - Option object
  38. */
  39. function* kmeansGenerator(centers, data, clusterID, K, options) {
  40.     var converged = false;
  41.     var stepNumber = 0;
  42.     var stepResult;
  43.     while (!converged && (stepNumber < options.maxIterations)) {
  44.         stepResult = step(centers, data, clusterID, K, options, ++stepNumber);
  45.         yield stepResult.computeInformation(data);
  46.         converged = stepResult.converged;
  47.         centers = stepResult.centroids;
  48.     }
  49. }

  50. /**
  51. * K-means algorithm
  52. * @param {Array<Array<number>>} data - Points in the format to cluster [x,y,z,...]
  53. * @param {number} K - Number of clusters
  54. * @param {object} [options] - Option object
  55. * @param {number} [options.maxIterations = 100] - Maximum of iterations allowed
  56. * @param {number} [options.tolerance = 1e-6] - Error tolerance
  57. * @param {boolean} [options.withIterations = false] - Store clusters and centroids for each iteration
  58. * @param {function} [options.distanceFunction = squaredDistance] - Distance function to use between the points
  59. * @param {string|Array<Array<number>>} [options.initialization = 'moreDistant'] - K centers in format [x,y,z,...] or a method for initialize the data:
  60. *  * `'random'` will choose K random different values.
  61. *  * `'mostDistant'` will choose the more distant points to a first random pick
  62. * @return {KMeansResult} - Cluster identifier for each data dot and centroids with the following fields:
  63. *  * `'clusters'`: Array of indexes for the clusters.
  64. *  * `'centroids'`: Array with the resulting centroids.
  65. *  * `'iterations'`: Number of iterations that took to converge
  66. */
  67. function kmeans(data, K, options) {
  68.     options = Object.assign({}, defaultOptions, options);

  69.     if (K <= 0 || K > data.length || !Number.isInteger(K)) {
  70.         throw new Error('K should be a positive integer smaller than the number of points');
  71.     }

  72.     var centers;
  73.     if (Array.isArray(options.initialization)) {
  74.         if (options.initialization.length !== K) {
  75.             throw new Error('The initial centers should have the same length as K');
  76.         } else {
  77.             centers = options.initialization;
  78.         }
  79.     } else {
  80.         switch (options.initialization) {
  81.             case 'random':
  82.                 centers = init.random(data, K);
  83.                 break;
  84.             case 'mostDistant':
  85.                 centers = init.mostDistant(data, K, utils.calculateDistanceMatrix(data, options.distanceFunction));
  86.                 break;
  87.             default:
  88.                 throw new Error('Unknown initialization method: "' + options.initialization + '"');
  89.         }
  90.     }

  91.     // infinite loop until convergence
  92.     if (options.maxIterations === 0) {
  93.         options.maxIterations = Number.MAX_VALUE;
  94.     }

  95.     var clusterID = new Array(data.length);
  96.     if (options.withIterations) {
  97.         return kmeansGenerator(centers, data, clusterID, K, options);
  98.     } else {
  99.         var converged = false;
  100.         var stepNumber = 0;
  101.         var stepResult;
  102.         while (!converged && (stepNumber < options.maxIterations)) {
  103.             stepResult = step(centers, data, clusterID, K, options, ++stepNumber);
  104.             converged = stepResult.converged;
  105.             centers = stepResult.centroids;
  106.         }
  107.         return stepResult.computeInformation(data);
  108.     }
  109. }

  110. module.exports = kmeans;
复制代码

使用道具

藤椅
ReneeBK 发表于 2017-4-16 04:20:13 |只看作者 |坛友微信交流群
  1. Example

  2. const kmeans = require('ml-kmeans');

  3. let data = [[1, 1, 1], [1, 2, 1], [-1, -1, -1], [-1, -1, -1.5]];
  4. let centers = [[1, 2, 1], [-1, -1, -1]];

  5. let ans = kmeans(data, 2, {initialization: centers});
  6. console.log(ans);
  7. /*
  8. KMeansResult {
  9.   clusters: [ 0, 0, 1, 1 ],
  10.   centroids:
  11.    [ { centroid: [ 1, 1.5, 1 ], error: 0.25, size: 2 },
  12.      { centroid: [ -1, -1, -1.25 ], error: 0.0625, size: 2 } ],
  13.   converged: true,
  14.   iterations: 1
  15. }
  16. */
复制代码

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-5-1 01:13