File: class.c

package info (click to toggle)
r-cran-class 7.3-18-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 232 kB
  • sloc: ansic: 379; makefile: 2
file content (446 lines) | stat: -rw-r--r-- 11,493 bytes parent folder | download | duplicates (3)
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
 *  class/src/class.c by W. N. Venables and B. D. Ripley  Copyright (C) 1994-2018
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 or 3 of the License
 *  (at your option).
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  A copy of the GNU General Public License is available at
 *  http://www.r-project.org/Licenses/
 *
 */

#include <stdlib.h> // currently in R.h
#include <R.h>
#include <math.h>
#include <float.h>

#define EPS 1e-4		/* relative test of equality of distances */

#define RANDIN  GetRNGstate()
#define RANDOUT PutRNGstate()
#define UNIF unif_rand()

void
VR_knn1(Sint *pntr, Sint *pnte, Sint *p, double *train, Sint *class,
	double *test, Sint *res, Sint *votes, Sint *nc, double *dists)
{
    int   npat, index, i, j, k, ntr = *pntr, nte = *pnte, nind=0, ntie, *ind;
    double dm, dist, tmp;

    RANDIN;
    ind = Calloc(ntr, int);
    for (npat = 0; npat < nte; npat++) {
	dm = DOUBLE_XMAX;
	for (j = 0; j < ntr; j++) {
	    dist = 0.0;
	    for (k = 0; k < *p; k++) {
		tmp = test[npat + k * nte] - train[j + k * ntr];
		dist += tmp * tmp;
	    }
	    if (dist <= dm * (1 + EPS)) {
		if (dist < dm * (1 - EPS))
		    nind = 0;
		else
		    nind++;
		dm = dist;
		ind[nind] = j;
	    }
	}
	for (i = 1; i <= *nc; i++)
	    votes[i] = 0;
/* nind is the number of tied minima, minus one */
	if (nind == 0)
	    index = class[ind[0]];
	else {
	    for (i = 0; i <= nind; i++)
		votes[class[ind[i]]]++;
	    j = votes[1];
/*
     This uses 'reservoir sampling' to choose amongst ties at random
     on a single pass.

 */
	    index = 1;
	    ntie = 1;
	    for (i = 2; i <= *nc; i++)
		if (votes[i] > j) {
		    ntie = 1;
		    index = i;
		    j = votes[i];
		} else if (votes[i] == j) {
		    if (++ntie * UNIF < 1.0)
			index = i;
		}
	}
	res[npat] = index;
	dists[npat] = dm;
    }
    RANDOUT;
    Free(ind);
}


#define MAX_TIES 1000
/* Not worth doing this dynamically -- limits k + # ties + fence, in fact */


void
VR_knn(Sint *kin, Sint *lin, Sint *pntr, Sint *pnte, Sint *p,
       double *train, Sint *class, double *test, Sint *res, double *pr,
       Sint *votes, Sint *nc, Sint *cv, Sint *use_all)
{
    int   i, index, j, k, k1, kinit = *kin, kn, l = *lin, mm, npat, ntie,
          ntr = *pntr, nte = *pnte, extras;
    int   pos[MAX_TIES], nclass[MAX_TIES];
    int   j1, j2, needed, t;
    double dist, tmp, nndist[MAX_TIES];

    RANDIN;
/*
    Use a 'fence' in the (k+1)st position to avoid special cases.
    Simple insertion sort will suffice since k will be small.
 */

    for (npat = 0; npat < nte; npat++) {
	kn = kinit;
	for (k = 0; k < kn; k++)
	    nndist[k] = 0.99 * DOUBLE_XMAX;
	for (j = 0; j < ntr; j++) {
	    if ((*cv > 0) && (j == npat))
		continue;
	    dist = 0.0;
	    for (k = 0; k < *p; k++) {
		tmp = test[npat + k * nte] - train[j + k * ntr];
		dist += tmp * tmp;
	    }
/* Use 'fuzz' since distance computed could depend on order of coordinates */
	    if (dist <= nndist[kinit - 1] * (1 + EPS))
		for (k = 0; k <= kn; k++)
		    if (dist < nndist[k]) {
			for (k1 = kn; k1 > k; k1--) {
			    nndist[k1] = nndist[k1 - 1];
			    pos[k1] = pos[k1 - 1];
			}
			nndist[k] = dist;
			pos[k] = j;
/* Keep an extra distance if the largest current one ties with current kth */
			if (nndist[kn] <= nndist[kinit - 1])
			    if (++kn == MAX_TIES - 1)
				error("too many ties in knn");
			break;
		    }
	    nndist[kn] = 0.99 * DOUBLE_XMAX;
	}

	for (j = 0; j <= *nc; j++)
	    votes[j] = 0;
	if (*use_all) {
	    for (j = 0; j < kinit; j++)
		votes[class[pos[j]]]++;
	    extras = 0;
	    for (j = kinit; j < kn; j++) {
		if (nndist[j] > nndist[kinit - 1] * (1 + EPS))
		    break;
		extras++;
		votes[class[pos[j]]]++;
	    }
	} else { /* break ties at random */
	    extras = 0;
	    for (j = 0; j < kinit; j++) {
		if (nndist[j] >= nndist[kinit - 1] * (1 - EPS))
		    break;
		votes[class[pos[j]]]++;
	    }
	    j1 = j;
	    if (j1 == kinit - 1) { /* no ties for largest */
		votes[class[pos[j1]]]++;
	    } else {
/* Use reservoir sampling to choose amongst the tied distances */
		j1 = j;
		needed = kinit - j1;
		for (j = 0; j < needed; j++)
		    nclass[j] = class[pos[j1 + j]];
		t = needed;
		for (j = j1 + needed; j < kn; j++) {
		    if (nndist[j] > nndist[kinit - 1] * (1 + EPS))
			break;
		    if (++t * UNIF < needed) {
			j2 = j1 + (int) (UNIF * needed);
			nclass[j2] = class[pos[j]];
		    }
		}
		for (j = 0; j < needed; j++)
		    votes[nclass[j]]++;
	    }
	}

/* Use reservoir sampling to choose amongst the tied votes */
	ntie = 1;
	if (l > 0)
	    mm = l - 1 + extras;
	else
	    mm = 0;
	index = 0;
	for (i = 1; i <= *nc; i++)
	    if (votes[i] > mm) {
		ntie = 1;
		index = i;
		mm = votes[i];
	    } else if (votes[i] == mm && votes[i] >= l) {
		if (++ntie * UNIF < 1.0)
		    index = i;
	    }
	res[npat] = index;
	pr[npat] = (double) mm / (kinit + extras);
    }
    RANDOUT;
}


#define min9(a,b) ((a < b)?a:b)

void
VR_olvq(double *alpha, Sint *pn, Sint *p, double *x, Sint *cl,
	Sint *pncodes, double *xc, Sint *clc, Sint *niter,
	Sint *iters)
{
    int   index=0, iter, j, k, n = *pn, ncodes = *pncodes, npat, s;
    double *al;
    double dist, dm, tmp;

    al = Calloc(ncodes, double);
    for (j = 0; j < ncodes; j++)
	al[j] = *alpha;
    for (iter = 0; iter < *niter; iter++) {
	npat = iters[iter];
	dm = DOUBLE_XMAX;
	for (j = 0; j < ncodes; j++) {
	    dist = 0.0;
	    for (k = 0; k < *p; k++) {
		tmp = x[npat + k * n] - xc[j + k * ncodes];
		dist += tmp * tmp;
	    }
	    if (dist < dm) {
		dm = dist;
		index = j;
	    }
	}
	s = 2 * (clc[index] == cl[npat]) - 1;
	for (k = 0; k < *p; k++)
	    xc[index + k * ncodes] += s * al[index] *
		(x[npat + k * n] - xc[index + k * ncodes]);
	al[index] = min9(*alpha, al[index] / (1 + s * al[index]));
    }
    Free(al);
}

void
VR_lvq1(double *alpha, Sint *pn, Sint *p, double *x, Sint *cl,
	Sint *pncodes, double *xc, Sint *clc, Sint *niter,
	Sint *iters)
{
    int   index = 0, iter, j, k, n = *pn, ncodes = *pncodes, npat, s;
    double alpha_t;
    double dist, dm, tmp;

    for (iter = 0; iter < *niter; iter++) {
	npat = iters[iter];
	alpha_t = *alpha * (*niter - iter) / (double) *niter;
	dm = DOUBLE_XMAX;
	for (j = 0; j < ncodes; j++) {
	    dist = 0.0;
	    for (k = 0; k < *p; k++) {
		tmp = x[npat + k * n] - xc[j + k * ncodes];
		dist += tmp * tmp;
	    }
	    if (dist < dm) {
		dm = dist;
		index = j;
	    }
	}
	s = 2 * (clc[index] == cl[npat]) - 1;
	for (k = 0; k < *p; k++)
	    xc[index + k * ncodes] += s * alpha_t *
		(x[npat + k * n] - xc[index + k * ncodes]);
    }
}

void
VR_lvq2(double *alpha, double *win, Sint *pn, Sint *p, double *x,
	Sint *cl, Sint *pncodes, double *xc, Sint *clc,
	Sint *niter, Sint *iters)
{
    int index = 0, iter, j, k, n = *pn, ncodes = *pncodes, nindex = 0,
	npat, ntmp;
    double alpha_t;
    double dist, dm, ndm, tmp;

    for (iter = 0; iter < *niter; iter++) {
	npat = iters[iter];
	alpha_t = *alpha * (*niter - iter) / (double) *niter;
	ndm = dm = DOUBLE_XMAX;

	/* Find two nearest codebook vectors */
	for (j = 0; j < ncodes; j++) {
	    dist = 0.0;
	    for (k = 0; k < *p; k++) {
		tmp = x[npat + k * n] - xc[j + k * ncodes];
		dist += tmp * tmp;
	    }
	    if (dist < dm) {
		ndm = dm;
		nindex = index;
		dm = dist;
		index = j;
	    } else if (dist < ndm) {
		ndm = dist;
		nindex = j;
	    }
	}
	if (clc[index] != clc[nindex]) {
	    if (((clc[index] == cl[npat]) || (clc[nindex] == cl[npat]))
		&& dm / ndm > (1 - *win) / (1 + *win)) {
		if (clc[nindex] == cl[npat]) {
		    ntmp = index;
		    index = nindex;
		    nindex = ntmp;
		}
		for (k = 0; k < *p; k++) {
		    xc[index + k * ncodes] += alpha_t *
			(x[npat + k * n] - xc[index + k * ncodes]);
		    xc[nindex + k * ncodes] -= alpha_t *
			(x[npat + k * n] - xc[nindex + k * ncodes]);
		}
	    }
	}
    }
}

void
VR_lvq3(double *alpha, double *win, double *epsilon, Sint *pn, Sint *p,
	double *x, Sint *cl, Sint *pncodes, double *xc, Sint *clc,
	Sint *niter, Sint *iters)
{
    int index = 0, iter, j, k, n = *pn, ncodes = *pncodes, nindex = 0,
	npat, ntmp;
    double alpha_t;
    double dist, dm, ndm, tmp;

    for (iter = 0; iter < *niter; iter++) {
	npat = iters[iter];
	alpha_t = *alpha * (*niter - iter) / (double) *niter;
	ndm = dm = DOUBLE_XMAX;
	/* Find two nearest codebook vectors */
	for (j = 0; j < ncodes; j++) {
	    dist = 0.0;
	    for (k = 0; k < *p; k++) {
		tmp = x[npat + k * n] - xc[j + k * ncodes];
		dist += tmp * tmp;
	    }
	    if (dist < dm) {
		ndm = dm;
		nindex = index;
		dm = dist;
		index = j;
	    } else if (dist < ndm) {
		ndm = dist;
		nindex = j;
	    }
	}
	if (clc[index] != clc[nindex]) {
	    if (((clc[index] == cl[npat]) || (clc[nindex] == cl[npat]))
		&& dm / ndm > (1 - *win) / (1 + *win)) {
		if (clc[nindex] == cl[npat]) {
		    ntmp = index;
		    index = nindex;
		    nindex = ntmp;
		}
		for (k = 0; k < *p; k++) {
		    xc[index + k * ncodes] += alpha_t *
			(x[npat + k * n] - xc[index + k * ncodes]);
		    xc[nindex + k * ncodes] -= alpha_t *
			(x[npat + k * n] - xc[nindex + k * ncodes]);
		}
	    }
	} else if (clc[index] == cl[npat]) {
	    for (k = 0; k < *p; k++) {
		xc[index + k * ncodes] += *epsilon * alpha_t *
		    (x[npat + k * n] - xc[index + k * ncodes]);
		xc[nindex + k * ncodes] += *epsilon * alpha_t *
		    (x[npat + k * n] - xc[nindex + k * ncodes]);
	    }
	}
    }
}

void
VR_onlineSOM(double *data, double *codes, double *nhbrdist,
	     double *alpha, double *radii,
	     Sint *pn, Sint *pp, Sint *pncodes, Sint *rlen)
{
    int n = *pn, p = *pp, ncodes = *pncodes;
    int i, j, k, nearest = 0 /* -Wall */, nind;
    double dm, dist, tmp;
    unsigned int cd; /* avoid spurious warning from gcc pre-4.3.0 */

    RANDIN;
    for (k = 0; k < *rlen; k++) {
	/* pick a random data point */
	i = (int)(n * UNIF);
	/* find the nearest code 'near' */
	/* nind is the number of tied minima,  unlike VR_knn1 */
	nind = 1; // for compilers: set to 1 when first min found.
	dm = DOUBLE_XMAX;
	for (cd = 0; cd < ncodes; cd++) {
	    dist = 0.0;
	    for (j = 0; j < p; j++) {
		tmp = data[i + j*n] - codes[cd + j*ncodes];
		dist += tmp * tmp;
	    }
	    if (dist <= dm * (1 + EPS)) {
		if (dist < dm * (1 - EPS)) {
		    nind = 1;
		    nearest = cd;
		} else {
		    if(++nind * UNIF < 1.0) nearest = cd;
		}
		dm = dist;
	    }
	    /* update all codes within radii[k] of 'nearest' */
	    for (cd = 0; cd < ncodes; cd++) {
		if(nhbrdist[cd + ncodes*nearest] > radii[k]) continue;
		for(j = 0; j < p; j++)
		    codes[cd + j*ncodes] += alpha[k] *
			(data[i + j*n] - codes[cd + j*ncodes]);
	    }
	}
    }
    RANDOUT;
}

#include "R_ext/Rdynload.h"

static const R_CMethodDef CEntries[] = {
    {"VR_knn", (DL_FUNC) &VR_knn, 14},
    {"VR_knn1", (DL_FUNC) &VR_knn1, 10},
    {"VR_lvq1", (DL_FUNC) &VR_lvq1, 10},
    {"VR_lvq2", (DL_FUNC) &VR_lvq2, 11},
    {"VR_lvq3", (DL_FUNC) &VR_lvq3, 12},
    {"VR_olvq", (DL_FUNC) &VR_olvq, 10},
    {"VR_onlineSOM", (DL_FUNC) &VR_onlineSOM, 9},
    {NULL, NULL, 0}
};

void R_init_class(DllInfo *dll)
{
    R_registerRoutines(dll, CEntries, NULL, NULL, NULL);
    R_useDynamicSymbols(dll, FALSE);
    R_forceSymbols(dll, TRUE);
}