Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 6x 6x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 18x 12x 12x 12x 12x 18x 12x 12x 18x 40x 40x 12x 12x 12x 12x 12x 12x 12x 12x 12x 40x 40x 40x 40x 40x 40x 40x 12x 12x 12x 12x 12x 12x 28x 28x 12x 12x 12x 12x 24x 24x 24x 24x 24x 24x 24x 56x 24x 24x 24x 56x 24x 24x 24x 24x 24x 80x 80x 28x 80x 52x 52x 80x 24x 24x 12x 12x 12x 24x 12x 12x 12x 12x 12x 18x 24x 24x 24x 24x 12x 18x 3x 3x 3x 3x 3x | /**
* @license Apache-2.0
*
* Copyright (c) 2026 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var randint = require( '@stdlib/random/base/discrete-uniform' ).factory;
var randu = require( '@stdlib/random/base/mt19937' ).factory;
var dcopy = require( '@stdlib/blas/base/dcopy' ).ndarray;
var Float64Array = require( '@stdlib/array/float64' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var format = require( '@stdlib/string/format' );
var dsquaredEuclidean = require( '@stdlib/stats/strided/distances/dsquared-euclidean' ).ndarray;
var dcosine = require( '@stdlib/stats/strided/distances/dcosine-distance' ).ndarray;
var dcityblock = require( '@stdlib/stats/strided/distances/dcityblock' ).ndarray;
var dcorrelation = require( '@stdlib/stats/strided/distances/dcorrelation' ).ndarray;
// MAIN //
/**
* Initializes centroids by performing the k-means++ initialization procedure on double-precision floating-point data points using alternative indexing semantics.
*
* ## Method
*
* The k-means++ algorithm for choosing initial centroids is as follows:
*
* 1. Select a data point uniformly at random from a data set \\( X \\). This data point is first centroid and denoted \\( c_0 \\).
*
* 2. Compute the distance from each data point to \\( c_0 \\). Denote the distance between \\( c_j \\) and data point \\( m \\) as \\( d(x_m, c_j) \\).
*
* 3. Select the next centroid, \\( c_1 \\), at random from \\( X \\) with probability
*
* ```tex
* \frac{d^2(x_m, c_0)}{\sum_{j=0}^{n-1} d^2(x_j, c_0)}
* ```
*
* where \\( n \\) is the number of data points.
*
* 4. To choose centroid \\( j \\),
*
* a. Compute the distances from each data point to each centroid and assign each data point to its closest centroid.
*
* b. For \\( i = 0,\ldots,n-1 \\) and \\( p = 0,\ldots,j-2 \\), select centroid \\( j \\) at random from \\( X \\) with probability
*
* ```tex
* \frac{d^2(x_i, c_p)}{\sum_{\{h; x_h \exits C_p\}} d^2(x_h, c_p)}
* ```
*
* where \\( C_p \\) is the set of all data points closest to centroid \\( c_p \\) and \\( x_i \\) belongs to \\( c_p \\).
*
* Stated more plainly, select each subsequent centroid with a probability proportional to the distance from the centroid to the closest centroid already chosen.
*
* 5. Repeat step `4` until \\( k \\) centroids have been chosen.
*
* ## References
*
* - Arthur, David, and Sergei Vassilvitskii. 2007. "K-means++: The Advantages of Careful Seeding." In _Proceedings of the Eighteenth Annual Acm-Siam Symposium on Discrete Algorithms_, 1027–35. SODA '07. Philadelphia, PA, USA: Society for Industrial and Applied Mathematics. <http://dl.acm.org/citation.cfm?id=1283383.1283494>.
*
* @param {PositiveInteger} k - number of clusters
* @param {PositiveInteger} M - number of data points
* @param {PositiveInteger} N - number of features
* @param {Float64Array} out - input array
* @param {integer} so1 - first stride length of `out`
* @param {integer} so2 - second stride length of `out`
* @param {NonNegativeInteger} oo - starting index of `out`
* @param {Float64Array} X - input array
* @param {integer} sx1 - first stride length of `X`
* @param {integer} sx2 - second stride length of `X`
* @param {NonNegativeInteger} ox - starting index of `X`
* @param {string} metric - distance metric
* @param {PositiveInteger} trials - number of potential centroids per iteration (>= 1)
* @param {*} seed - PRNG seed
* @throws {TypeError} tenth argument must be a valid trials (>=1)
* @returns {Float64Array} centroids
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var k = 3;
* var M = 5;
* var N = 2;
*
* var out = new Float64Array( k*N );
*
* // Specify data points:
* var xbuf = new Float64Array([
* 0.0, 0.0,
* 1.0, 1.0,
* 1.0, -1.0,
* -1.0, -1.0,
* -1.0, 1.0
* ]);
*
* var v = dkmeansInitPlusPlus( k, M, N, out, 2, 1, 0, xbuf, 2, 1, 0, 'sqeuclidean', 3, 44 );
* // returns <Float64Array>[0,0,1,-1,1,1]
*/
function dkmeansInitPlusPlus( k, M, N, out, so1, so2, oo, X, sx1, sx2, ox, metric, trials, seed ) { // eslint-disable-line max-len, max-params
var centroids; // array of indices
var dhash;
var randi;
var probs;
var rand;
var csum;
var bsum;
var dist;
var xidx;
var cidx;
var oidx;
var d2;
var bc;
var d;
var c;
var i;
var j;
var t;
var r;
if ( trials < 1 ) {
throw new TypeError( format( 'invalid argument. Thirteenth argument must be a valid trials (>=1). Value: `%s`.', trials ) );
}
if ( k < 1 || M < 1 || N < 1) {
return NaN;
}
// Create seeded PRNGs:
rand = randu({
'seed': seed
});
randi = randint({
'seed': rand()
});
rand = rand.normalized;
// 1. Select a data point at random for the first centroid...
c = randi( 0, M-1 );
if ( k === 1 ) {
// For the trivial case of one centroid, we are done which means we can skip to setting the output centroid data...
return dcopy( N, X, sx2, ox + ( sx1*c ), out, so2, oo );
}
centroids = [ c ];
if ( metric === 'sqeuclidean' ) {
dist = dsquaredEuclidean;
} else if ( metric === 'cosine' ) {
dist = dcosine;
} else if ( metric === 'cityblock' ) {
dist = dcityblock;
} else {
dist = dcorrelation;
}
dhash = new Float64Array( M );
for ( i = 0; i < M; i++ ) {
dhash[ i ] = PINF; // squared distance
}
// Create a scratch array for storing cumulative probabilities:
probs = new Float64Array( M );
// 2-5. For each data point, compute the distances to each centroid, find the closest centroid, and, based on the distance to the closest centroid, assign a probability to the data point to be chosen as centroid `c_j`...
for ( i = 1; i < k; i++ ) {
csum = 0.0;
xidx = ox;
cidx = ox + ( sx1*centroids[ i-1 ] );
for ( j = 0; j < M; j++ ) {
d2 = dist( N, X, sx2, xidx, X, sx2, cidx );
if ( d2 < dhash[ j ] ) {
dhash[ j ] = d2;
csum += d2;
} else {
csum += dhash[ j ];
}
xidx += sx1;
}
if ( csum === 0.0 ) {
centroids.push( randi( 0, M-1 ) );
continue;
}
// Compute the cumulative probabilities...
probs[ 0 ] = dhash[ 0 ] / csum;
for ( j = 1; j < M; j++ ) {
probs[ j ] = probs[ j-1 ] + ( dhash[ j ] / csum );
}
// Based Arthur's and Vassilvitskii's paper "kmeans++: The Advantages of Careful Seeding" (see conclusion), randomly select candidate centroids and pick the candidate which minimizes the total squared distance...
bsum = PINF; // best sum
bc = -1; // best candidate
for ( t = 0; t < trials; t++ ) {
// Use rejection sampling to handle edge case where the total cumulative probability does not equal unity due to accumulated floating-point errors and is less than `r` (*very* rarely should this require more than one iteration)...
c = -1;
// Note: the following should never choose an already chosen centroid (why? because a centroid's minimum squared distance is `0`, which means it will either correspond to a cumulative probability of `0` or will correspond to a cumulative probability equal to the previous cumulative probability, thus leading to the equivalent of a no-op iteration)
while ( c === -1 ) {
r = rand(); // Note: `r` exists on the interval `[0,1)`
for ( j = 0; j < M; j++ ) {
if ( r < probs[ j ] ) {
c = j;
break;
}
}
}
// Compute the sum of squared distances were we to include the candidate centroid...
csum = 0.0;
cidx = ox + ( sx1 * c );
for ( j = 0; j < M; j++ ) {
d = dist( N, X, sx2, ox + ( sx1*j ), X, sx2, cidx );
if ( d < dhash[ j ] ) {
csum += d;
} else {
csum += dhash[ j ];
}
}
// Determine if the candidate is the best candidate we have seen thus far...
if ( csum < bsum ) {
bsum = csum;
bc = c;
}
}
// Push the "best" candidate to our list of centroids:
centroids.push( bc );
}
// 6. Set centroid data...
oidx = oo;
for ( i = 0; i < k; i++ ) {
// Note: the following is likely to be an "out-of-order" copy...
dcopy( N, X, sx2, ox + ( sx1*centroids[i] ), out, so2, oidx );
oidx += so1;
}
return out;
}
// EXPORTS //
module.exports = dkmeansInitPlusPlus;
|