cp500 commited on
Commit
e9fe87b
·
verified ·
1 Parent(s): ab0bd1b

Upload js/src/softmax.ts with huggingface_hub

Browse files
Files changed (1) hide show
  1. js/src/softmax.ts +27 -0
js/src/softmax.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Numerically stable softmax + argmax-with-confidence.
3
+ *
4
+ * Pure JS — no ORT, no DOM. The classifier ONNX emits raw logits
5
+ * because softmax-inside-graph would erase the per-class info we
6
+ * use to surface ``confidence`` to downstream callers.
7
+ */
8
+
9
+ /** Argmax + softmax probability of the winning class. Numerically
10
+ * stable (subtract max before exp). */
11
+ export function argmaxWithProb(
12
+ logits: Float32Array | number[],
13
+ ): { idx: number; prob: number } {
14
+ let maxLogit = -Infinity;
15
+ let argmax = 0;
16
+ for (let i = 0; i < logits.length; i++) {
17
+ if (logits[i] > maxLogit) {
18
+ maxLogit = logits[i];
19
+ argmax = i;
20
+ }
21
+ }
22
+ let z = 0;
23
+ for (let i = 0; i < logits.length; i++) {
24
+ z += Math.exp(logits[i] - maxLogit);
25
+ }
26
+ return { idx: argmax, prob: 1 / z };
27
+ }