@dniskav/neuron 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +122 -1
- package/dist/index.d.mts +290 -1
- package/dist/index.d.ts +290 -1
- package/dist/index.js +1118 -0
- package/dist/index.mjs +1110 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
A minimal, dependency-free neural network library built from scratch in TypeScript. Designed for learning and experimentation — every line of math is readable.
|
|
5
5
|
|
|
6
|
-
Each class is a building block for the next: from a single neuron to a full Transformer with causal attention.
|
|
6
|
+
Each class is a building block for the next: from a single neuron to a full Transformer with causal attention. Includes classical ML, unsupervised learning, generative models, embeddings, and autograd — all in pure TypeScript, zero dependencies.
|
|
7
7
|
|
|
8
8
|
```mermaid
|
|
9
9
|
graph TD
|
|
@@ -126,6 +126,17 @@ graph TD
|
|
|
126
126
|
|--------|-------------|
|
|
127
127
|
| `Value` | Scalar autograd node. Builds a computational graph and propagates gradients with `.backward()`. Inspired by micrograd. |
|
|
128
128
|
|
|
129
|
+
### Embeddings
|
|
130
|
+
|
|
131
|
+
| Export | Description |
|
|
132
|
+
|--------|-------------|
|
|
133
|
+
| `Word2Vec` | Learns word embeddings via Skip-gram or CBOW. Full-softmax, cosine similarity, analogies (`king - man + woman ≈ queen`). |
|
|
134
|
+
| `TSNE` | t-SNE dimensionality reduction. Binary-search perplexity, Student-t kernel, KL gradient, early exaggeration. |
|
|
135
|
+
| `PositionalEncoding` | Sinusoidal positional encoding (Vaswani et al.). Static — no parameters, generalizes to unseen lengths. |
|
|
136
|
+
| `LearnedPositionalEncoding` | Trainable positional encoding. Xavier-initialized, learnable up to a fixed `maxSeqLen`. |
|
|
137
|
+
| `ContrastiveLearning` | SimCLR-style self-supervised learning. NT-Xent loss, encoder + projection head, temperature τ. |
|
|
138
|
+
| `Augmenter` | Data augmentation helpers for contrastive pairs: Gaussian noise, feature dropout, `makePair()`. |
|
|
139
|
+
|
|
129
140
|
### Activations & math
|
|
130
141
|
|
|
131
142
|
| Export | Description |
|
|
@@ -396,6 +407,79 @@ const { mu, logVar } = vae.encode(image); // encode → distribution params
|
|
|
396
407
|
const z = vae.reparametrize(mu, logVar); // sample z ~ N(μ, σ²)
|
|
397
408
|
```
|
|
398
409
|
|
|
410
|
+
### Word2Vec — aprende embeddings de palabras
|
|
411
|
+
|
|
412
|
+
```ts
|
|
413
|
+
import { Word2Vec } from "@dniskav/neuron";
|
|
414
|
+
|
|
415
|
+
const w2v = new Word2Vec(64, { model: 'skipgram', windowSize: 2 });
|
|
416
|
+
|
|
417
|
+
const corpus = [
|
|
418
|
+
["the", "king", "rules", "the", "kingdom"],
|
|
419
|
+
["the", "queen", "rules", "the", "land"],
|
|
420
|
+
["man", "and", "woman", "are", "human"],
|
|
421
|
+
];
|
|
422
|
+
|
|
423
|
+
w2v.buildVocab(corpus);
|
|
424
|
+
w2v.train(corpus, 0.05, 200);
|
|
425
|
+
|
|
426
|
+
console.log(w2v.similarity("king", "queen")); // high
|
|
427
|
+
console.log(w2v.mostSimilar("king", 3));
|
|
428
|
+
// [{ word: 'queen', score: 0.91 }, ...]
|
|
429
|
+
|
|
430
|
+
// Vector arithmetic: king - man + woman ≈ queen
|
|
431
|
+
console.log(w2v.analogy("king", "man", "woman", 1));
|
|
432
|
+
// [{ word: 'queen', score: 0.87 }]
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
### t-SNE — visualiza embeddings en 2D
|
|
436
|
+
|
|
437
|
+
```ts
|
|
438
|
+
import { TSNE } from "@dniskav/neuron";
|
|
439
|
+
|
|
440
|
+
// Reduce 128-dim embeddings → 2D for plotting
|
|
441
|
+
const tsne = new TSNE({ perplexity: 30, nIter: 1000, seed: 42 });
|
|
442
|
+
const points2D = tsne.fitTransform(embeddings128D); // [n][2]
|
|
443
|
+
|
|
444
|
+
console.log(tsne.kl()); // KL divergence — lower is better
|
|
445
|
+
// Plot points2D with any charting library
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
### PositionalEncoding — orden sin parámetros
|
|
449
|
+
|
|
450
|
+
```ts
|
|
451
|
+
import { PositionalEncoding, LearnedPositionalEncoding } from "@dniskav/neuron";
|
|
452
|
+
|
|
453
|
+
// Sinusoidal — deterministic, no training needed
|
|
454
|
+
const pe = PositionalEncoding.encodeSequence(512, 128); // [512][128]
|
|
455
|
+
const withPos = PositionalEncoding.apply(tokenEmbeddings); // add PE to embeddings
|
|
456
|
+
|
|
457
|
+
// Learned — trainable, fixed maxSeqLen
|
|
458
|
+
const lpe = new LearnedPositionalEncoding(512, 128);
|
|
459
|
+
const withLearnedPos = lpe.apply(tokenEmbeddings);
|
|
460
|
+
lpe.update(gradients, 0.001); // update during backprop
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
### ContrastiveLearning — representaciones sin etiquetas
|
|
464
|
+
|
|
465
|
+
```ts
|
|
466
|
+
import { ContrastiveLearning, Augmenter } from "@dniskav/neuron";
|
|
467
|
+
|
|
468
|
+
// Encoder: 128 → [256, 128] → 64 latent, projection head: 64 → 32
|
|
469
|
+
const cl = new ContrastiveLearning(128, [256, 128], 64, { temperature: 0.5 });
|
|
470
|
+
|
|
471
|
+
// Create positive pairs from unlabeled data (two augmented views per sample)
|
|
472
|
+
const pairs = unlabeledData.map(x => Augmenter.makePair(x));
|
|
473
|
+
|
|
474
|
+
for (let step = 0; step < 1000; step++) {
|
|
475
|
+
const loss = cl.trainStep(pairs, 0.001);
|
|
476
|
+
if (step % 100 === 0) console.log(`step ${step}: ${loss.toFixed(4)}`);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// Use encoder for downstream tasks (classification, clustering, etc.)
|
|
480
|
+
const representation = cl.encode(newSample); // 64-dim vector
|
|
481
|
+
```
|
|
482
|
+
|
|
399
483
|
### Value / Tape — automatic differentiation
|
|
400
484
|
|
|
401
485
|
```ts
|
|
@@ -594,8 +678,45 @@ npm test # run test suite
|
|
|
594
678
|
|
|
595
679
|
If you are an AI agent or LLM working with this codebase, read [AGENTS.md](AGENTS.md) first. It contains the full class hierarchy, design constraints, and what this library does not do.
|
|
596
680
|
|
|
681
|
+
## Roadmap (nice to have)
|
|
682
|
+
|
|
683
|
+
These features are intentionally out of scope for the current didactic focus but are documented here for reference.
|
|
684
|
+
|
|
685
|
+
### ONNX export
|
|
686
|
+
|
|
687
|
+
Export trained models to the [ONNX](https://onnx.ai/) interchange format so they can be run in Python (onnxruntime), browsers (onnxruntime-web), mobile, or production inference servers.
|
|
688
|
+
|
|
689
|
+
**What it would require:**
|
|
690
|
+
- Serialize each layer's weights + op type to the protobuf ONNX schema (`onnx.proto`).
|
|
691
|
+
- Map neuron layer types to standard ONNX operators (`Gemm`, `MatMul`, `LSTM`, `Conv`, `Relu`, `Softmax`, …).
|
|
692
|
+
- Handle dynamic batch dimensions in the graph IR.
|
|
693
|
+
- Ship a build step that compiles the `.proto` definitions (adds a dev dependency on `protobufjs` or `onnx-proto`).
|
|
694
|
+
|
|
695
|
+
**Why it's skipped:** It adds a non-trivial build pipeline and a dependency. The library has zero runtime dependencies by design. ONNX export makes sense once you outgrow the library for training — at that point PyTorch/TF are the right tools.
|
|
696
|
+
|
|
697
|
+
### WebGL / WASM backend
|
|
698
|
+
|
|
699
|
+
Replace the current pure-JS number arrays with a GPU-accelerated or WASM-compiled backend so larger models (e.g. ViT, GPT-2 scale) become feasible in the browser.
|
|
700
|
+
|
|
701
|
+
**What it would require:**
|
|
702
|
+
- Abstract `Tensor` type that backends implement (JS arrays, WebGL textures, WASM memory).
|
|
703
|
+
- WebGL backend: encode matrix ops as fragment-shader programs (similar to `gpu.js` or `tfjs-backend-webgl`).
|
|
704
|
+
- WASM backend: compile a BLAS-like C/Rust core (e.g. `wasm-bindgen` + `ndarray`) and bind it to TypeScript.
|
|
705
|
+
- Every layer's `forward` / `backward` rewritten against the `Tensor` API.
|
|
706
|
+
|
|
707
|
+
**Why it's skipped:** The goal is to make the math readable. GPU shader code and WASM bindings are implementation details that obscure the algorithms. The library intentionally trades performance for pedagogical clarity.
|
|
708
|
+
|
|
709
|
+
---
|
|
710
|
+
|
|
597
711
|
## Changelog
|
|
598
712
|
|
|
713
|
+
### v0.3.2
|
|
714
|
+
- **New — NLP:** `Tokenizer` (char / word / whitespace modes, special tokens PAD/UNK/BOS/EOS, one-hot encoding, `fit` / `encode` / `decode` / `encodeBatch`, JSON serialization)
|
|
715
|
+
- **New — Data:** `DatasetLoader` (parse CSV and JSON into `DataPair`; auto one-hot encoding for string columns; returns `categoricalMaps` for decoding predictions)
|
|
716
|
+
|
|
717
|
+
### v0.3.1
|
|
718
|
+
- **New — Embeddings:** `Word2Vec` (Skip-gram + CBOW, full-softmax, cosine similarity, analogies), `TSNE` (binary-search perplexity, Student-t kernel, KL gradient, early exaggeration, seeded PRNG), `PositionalEncoding` (sinusoidal, Vaswani et al.), `LearnedPositionalEncoding` (trainable), `ContrastiveLearning` (NT-Xent, SimCLR encoder + projection head), `Augmenter` (noise, feature dropout, `makePair`)
|
|
719
|
+
|
|
599
720
|
### v0.3.0
|
|
600
721
|
- **New — Classical ML:** `Perceptron`, `LinearRegression` (normal equation + GD), `LogisticRegression`, `SoftmaxRegression`, `GaussianNaiveBayes`, `DecisionTree` (CART, Gini/MSE)
|
|
601
722
|
- **New — Unsupervised:** `KMeans` (K-Means++ init), `PCA` (power iteration + Hotelling deflation), `SOM` (Kohonen map), `HopfieldNetwork` (Hebbian storage + energy), `Autoencoder`
|
package/dist/index.d.mts
CHANGED
|
@@ -570,6 +570,63 @@ declare class Trainer {
|
|
|
570
570
|
private _computeMetricsArray;
|
|
571
571
|
}
|
|
572
572
|
|
|
573
|
+
interface DatasetLoaderOptions {
|
|
574
|
+
/** Column names to use as input features. */
|
|
575
|
+
featureCols: string[];
|
|
576
|
+
/** Column names to use as targets / labels. */
|
|
577
|
+
targetCols: string[];
|
|
578
|
+
/**
|
|
579
|
+
* When true, string values in feature/target columns are one-hot encoded.
|
|
580
|
+
* When false, non-numeric values throw an error. Default: true.
|
|
581
|
+
*/
|
|
582
|
+
encodeStrings?: boolean;
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Maps a column name to its {value → one-hot index} dictionary.
|
|
586
|
+
* Useful for decoding model predictions back to class names.
|
|
587
|
+
*/
|
|
588
|
+
type CategoricalMap = Record<string, Record<string, number>>;
|
|
589
|
+
interface DatasetLoaderResult extends DataPair {
|
|
590
|
+
/**
|
|
591
|
+
* For each string column that was one-hot encoded, maps the column name to
|
|
592
|
+
* the {category → index} dictionary used during encoding.
|
|
593
|
+
*/
|
|
594
|
+
categoricalMaps: CategoricalMap;
|
|
595
|
+
/** Column names in the order they appear in each input vector. */
|
|
596
|
+
featureNames: string[];
|
|
597
|
+
/** Column names (or expanded one-hot names) in the order they appear in each target vector. */
|
|
598
|
+
targetNames: string[];
|
|
599
|
+
/** Total number of rows parsed. */
|
|
600
|
+
numRows: number;
|
|
601
|
+
}
|
|
602
|
+
declare class DatasetLoader {
|
|
603
|
+
/**
|
|
604
|
+
* Parse a CSV string into a DataPair.
|
|
605
|
+
*
|
|
606
|
+
* - The first non-empty row is treated as a header.
|
|
607
|
+
* - Numeric values are parsed with parseFloat.
|
|
608
|
+
* - String values are one-hot encoded (one column → N binary columns).
|
|
609
|
+
* - Empty rows and comment lines (starting with #) are skipped.
|
|
610
|
+
*
|
|
611
|
+
* @param csv - raw CSV text
|
|
612
|
+
* @param options - which columns to use as features / targets
|
|
613
|
+
*/
|
|
614
|
+
static fromCSV(csv: string, options: DatasetLoaderOptions): DatasetLoaderResult;
|
|
615
|
+
/**
|
|
616
|
+
* Parse a JSON string (array of objects) into a DataPair.
|
|
617
|
+
*
|
|
618
|
+
* Expected format:
|
|
619
|
+
* [{ "col1": 1.0, "col2": "cat", "label": "dog" }, ...]
|
|
620
|
+
*
|
|
621
|
+
* @param json - raw JSON text or a pre-parsed array of objects
|
|
622
|
+
* @param options - which columns to use as features / targets
|
|
623
|
+
*/
|
|
624
|
+
static fromJSON(json: string | Record<string, unknown>[], options: DatasetLoaderOptions): DatasetLoaderResult;
|
|
625
|
+
private static _buildDataPair;
|
|
626
|
+
private static _parseCSV;
|
|
627
|
+
private static _parseCSVRow;
|
|
628
|
+
}
|
|
629
|
+
|
|
573
630
|
declare class LRScheduler {
|
|
574
631
|
stepDecay(lr: number, epoch: number, dropRate: number, epochsDrop: number): number;
|
|
575
632
|
exponentialDecay(lr: number, epoch: number, decayRate: number): number;
|
|
@@ -893,6 +950,123 @@ declare class TCN {
|
|
|
893
950
|
train(sequence: number[][], targets: number[][], lr: number): number;
|
|
894
951
|
}
|
|
895
952
|
|
|
953
|
+
type Word2VecModel = 'skipgram' | 'cbow';
|
|
954
|
+
interface Word2VecOptions {
|
|
955
|
+
/** Size of the sliding context window on each side of the center word. Default 2. */
|
|
956
|
+
windowSize?: number;
|
|
957
|
+
/** Training architecture. Default 'skipgram'. */
|
|
958
|
+
model?: Word2VecModel;
|
|
959
|
+
/** Ignore words with corpus frequency below this threshold. Default 1. */
|
|
960
|
+
minCount?: number;
|
|
961
|
+
}
|
|
962
|
+
declare class Word2Vec {
|
|
963
|
+
/** Learned word vectors, shape [vocabSize][embeddingDim]. */
|
|
964
|
+
embeddings: number[][];
|
|
965
|
+
/** Maps each vocabulary word to its integer index. */
|
|
966
|
+
vocab: Map<string, number>;
|
|
967
|
+
vocabSize: number;
|
|
968
|
+
embeddingDim: number;
|
|
969
|
+
private _indexToWord;
|
|
970
|
+
private _W2;
|
|
971
|
+
private _windowSize;
|
|
972
|
+
private _model;
|
|
973
|
+
private _minCount;
|
|
974
|
+
private _trained;
|
|
975
|
+
constructor(embeddingDim?: number, options?: Word2VecOptions);
|
|
976
|
+
buildVocab(sentences: string[][]): void;
|
|
977
|
+
static tokenize(text: string): string[];
|
|
978
|
+
train(sentences: string[][], lr?: number, epochs?: number): number[];
|
|
979
|
+
getEmbedding(word: string): number[];
|
|
980
|
+
similarity(word1: string, word2: string): number;
|
|
981
|
+
mostSimilar(word: string, topK?: number): {
|
|
982
|
+
word: string;
|
|
983
|
+
score: number;
|
|
984
|
+
}[];
|
|
985
|
+
analogy(positive1: string, negative: string, positive2: string, topK?: number): {
|
|
986
|
+
word: string;
|
|
987
|
+
score: number;
|
|
988
|
+
}[];
|
|
989
|
+
private _skipgramStep;
|
|
990
|
+
private _cbowStep;
|
|
991
|
+
private _hiddenToScores;
|
|
992
|
+
private _nearestByVector;
|
|
993
|
+
private _cosine;
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
interface TSNEOptions {
|
|
997
|
+
/** Dimensionality of the output embedding. Default 2. */
|
|
998
|
+
nComponents?: number;
|
|
999
|
+
/**
|
|
1000
|
+
* Perplexity — loosely controls the effective number of neighbors considered
|
|
1001
|
+
* for each point. Typical values: 5–50. Default 30.
|
|
1002
|
+
* Must be less than the number of data points.
|
|
1003
|
+
*/
|
|
1004
|
+
perplexity?: number;
|
|
1005
|
+
/** Learning rate for gradient descent. Default 200. */
|
|
1006
|
+
lr?: number;
|
|
1007
|
+
/** Number of gradient-descent iterations. Default 1000. */
|
|
1008
|
+
nIter?: number;
|
|
1009
|
+
/**
|
|
1010
|
+
* Seed for the pseudo-random number generator.
|
|
1011
|
+
* Set to any integer for reproducible results. Default uses Math.random.
|
|
1012
|
+
*/
|
|
1013
|
+
seed?: number;
|
|
1014
|
+
}
|
|
1015
|
+
declare class TSNE {
|
|
1016
|
+
/** Result of the embedding, shape [n][nComponents]. Available after fit(). */
|
|
1017
|
+
embedding: number[][];
|
|
1018
|
+
private readonly _nComponents;
|
|
1019
|
+
private readonly _perplexity;
|
|
1020
|
+
private readonly _lr;
|
|
1021
|
+
private readonly _nIter;
|
|
1022
|
+
private readonly _seed;
|
|
1023
|
+
private _klDivergence;
|
|
1024
|
+
private _P;
|
|
1025
|
+
constructor(options?: TSNEOptions);
|
|
1026
|
+
fit(X: number[][]): void;
|
|
1027
|
+
fitTransform(X: number[][]): number[][];
|
|
1028
|
+
kl(): number;
|
|
1029
|
+
private _computePcond;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
declare class PositionalEncoding {
|
|
1033
|
+
static encode(pos: number, dModel: number): number[];
|
|
1034
|
+
static encodeSequence(seqLen: number, dModel: number): number[][];
|
|
1035
|
+
static apply(embeddings: number[][], seqLen?: number): number[][];
|
|
1036
|
+
}
|
|
1037
|
+
declare class LearnedPositionalEncoding {
|
|
1038
|
+
readonly maxSeqLen: number;
|
|
1039
|
+
readonly dModel: number;
|
|
1040
|
+
weights: number[][];
|
|
1041
|
+
constructor(maxSeqLen: number, dModel: number);
|
|
1042
|
+
getEncoding(pos: number): number[];
|
|
1043
|
+
apply(embeddings: number[][], seqLen?: number): number[][];
|
|
1044
|
+
update(dWeights: number[][], lr: number): void;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
declare class Augmenter {
|
|
1048
|
+
static addNoise(x: number[], sigma?: number): number[];
|
|
1049
|
+
static dropoutFeatures(x: number[], rate?: number): number[];
|
|
1050
|
+
static augment(x: number[], noiseStd?: number, dropRate?: number): number[];
|
|
1051
|
+
static makePair(x: number[]): [number[], number[]];
|
|
1052
|
+
}
|
|
1053
|
+
declare class ContrastiveLearning {
|
|
1054
|
+
encoder: NetworkN;
|
|
1055
|
+
projectionHead: NetworkN;
|
|
1056
|
+
temperature: number;
|
|
1057
|
+
constructor(inputSize: number, encoderHidden: number[], projectionDim: number, options?: {
|
|
1058
|
+
temperature?: number;
|
|
1059
|
+
encoderOptions?: NetworkNOptions;
|
|
1060
|
+
});
|
|
1061
|
+
encode(x: number[]): number[];
|
|
1062
|
+
project(x: number[]): number[];
|
|
1063
|
+
static cosineSimilarity(a: number[], b: number[]): number;
|
|
1064
|
+
computeLoss(pairs: [number[], number[]][]): number;
|
|
1065
|
+
trainStep(pairs: [number[], number[]][], lr: number): number;
|
|
1066
|
+
private _forwardProjections;
|
|
1067
|
+
private _ntXentLoss;
|
|
1068
|
+
}
|
|
1069
|
+
|
|
896
1070
|
declare class GAN {
|
|
897
1071
|
readonly generator: NetworkN;
|
|
898
1072
|
readonly discriminator: NetworkN;
|
|
@@ -990,6 +1164,121 @@ declare function perplexity(yTrue: number[], probabilities: number[][]): number;
|
|
|
990
1164
|
declare function printConfusionMatrix(matrix: number[][], labels?: string[]): void;
|
|
991
1165
|
declare function classificationReport(yTrue: number[], yPred: number[], labels?: string[]): void;
|
|
992
1166
|
|
|
1167
|
+
type TokenizerMode = 'char' | 'word' | 'whitespace';
|
|
1168
|
+
interface TokenizerOptions {
|
|
1169
|
+
/** Tokenization strategy. Default: 'word' */
|
|
1170
|
+
mode?: TokenizerMode;
|
|
1171
|
+
/** Normalize text to lowercase before processing. Default: true */
|
|
1172
|
+
lowercase?: boolean;
|
|
1173
|
+
/** Maximum vocabulary size (most frequent tokens kept). 0 = unlimited. Default: 0 */
|
|
1174
|
+
maxVocab?: number;
|
|
1175
|
+
/** Additional special tokens to reserve (appended after PAD/UNK/BOS/EOS). */
|
|
1176
|
+
specialTokens?: string[];
|
|
1177
|
+
}
|
|
1178
|
+
interface EncodeOptions {
|
|
1179
|
+
/** Prepend <BOS> token. Default: false */
|
|
1180
|
+
addBOS?: boolean;
|
|
1181
|
+
/** Append <EOS> token. Default: false */
|
|
1182
|
+
addEOS?: boolean;
|
|
1183
|
+
}
|
|
1184
|
+
interface EncodeBatchOptions extends EncodeOptions {
|
|
1185
|
+
/**
|
|
1186
|
+
* Pad or truncate all sequences to this length.
|
|
1187
|
+
* Sequences shorter than padTo are right-padded with <PAD> (id 0).
|
|
1188
|
+
* Sequences longer than padTo are truncated on the right.
|
|
1189
|
+
* If omitted, sequences are left at their natural length.
|
|
1190
|
+
*/
|
|
1191
|
+
padTo?: number;
|
|
1192
|
+
}
|
|
1193
|
+
interface TokenizerSnapshot {
|
|
1194
|
+
mode: TokenizerMode;
|
|
1195
|
+
lowercase: boolean;
|
|
1196
|
+
maxVocab: number;
|
|
1197
|
+
token2id: Record<string, number>;
|
|
1198
|
+
}
|
|
1199
|
+
declare class Tokenizer {
|
|
1200
|
+
static readonly PAD = "<PAD>";
|
|
1201
|
+
static readonly UNK = "<UNK>";
|
|
1202
|
+
static readonly BOS = "<BOS>";
|
|
1203
|
+
static readonly EOS = "<EOS>";
|
|
1204
|
+
private readonly _mode;
|
|
1205
|
+
private readonly _lowercase;
|
|
1206
|
+
private readonly _maxVocab;
|
|
1207
|
+
private readonly _extraSpecial;
|
|
1208
|
+
private _token2id;
|
|
1209
|
+
private _id2token;
|
|
1210
|
+
private _fitted;
|
|
1211
|
+
constructor(options?: TokenizerOptions);
|
|
1212
|
+
/**
|
|
1213
|
+
* Build vocabulary from an array of text strings.
|
|
1214
|
+
* Calling fit() again resets and rebuilds the vocabulary from scratch.
|
|
1215
|
+
*
|
|
1216
|
+
* @param texts - corpus to build the vocabulary from
|
|
1217
|
+
* @returns this (chainable)
|
|
1218
|
+
*/
|
|
1219
|
+
fit(texts: string[]): this;
|
|
1220
|
+
/**
|
|
1221
|
+
* Split raw text into an array of string tokens (no ID conversion yet).
|
|
1222
|
+
* Useful for inspecting what the tokenizer produces before encoding.
|
|
1223
|
+
*/
|
|
1224
|
+
tokenize(text: string): string[];
|
|
1225
|
+
/**
|
|
1226
|
+
* Convert a text string to a sequence of token IDs.
|
|
1227
|
+
* Unknown tokens map to <UNK> (id 1).
|
|
1228
|
+
*
|
|
1229
|
+
* @param text - input text
|
|
1230
|
+
* @param options - addBOS / addEOS flags
|
|
1231
|
+
*/
|
|
1232
|
+
encode(text: string, options?: EncodeOptions): number[];
|
|
1233
|
+
/**
|
|
1234
|
+
* Encode an array of texts, optionally padding/truncating to a fixed length.
|
|
1235
|
+
*
|
|
1236
|
+
* @param texts - array of input texts
|
|
1237
|
+
* @param options - addBOS / addEOS / padTo
|
|
1238
|
+
*/
|
|
1239
|
+
encodeBatch(texts: string[], options?: EncodeBatchOptions): number[][];
|
|
1240
|
+
/**
|
|
1241
|
+
* Convert a sequence of token IDs back to a human-readable string.
|
|
1242
|
+
*
|
|
1243
|
+
* @param ids - array of token IDs
|
|
1244
|
+
* @param stripSpecial - remove PAD/BOS/EOS tokens from output. Default: true
|
|
1245
|
+
*/
|
|
1246
|
+
decode(ids: number[], stripSpecial?: boolean): string;
|
|
1247
|
+
/**
|
|
1248
|
+
* Convert a sequence of token IDs to one-hot vectors.
|
|
1249
|
+
* Each vector has length `vocabSize` with a single 1 at the token's position.
|
|
1250
|
+
* Useful when feeding tokens directly into a Network without an embedding layer.
|
|
1251
|
+
*
|
|
1252
|
+
* @param ids - array of token IDs (e.g. from encode())
|
|
1253
|
+
* @returns - 2D array of shape [seqLen, vocabSize]
|
|
1254
|
+
*/
|
|
1255
|
+
oneHot(ids: number[]): number[][];
|
|
1256
|
+
/** Number of tokens in the vocabulary (including special tokens). */
|
|
1257
|
+
get vocabSize(): number;
|
|
1258
|
+
/** True if fit() has been called at least once. */
|
|
1259
|
+
get isFitted(): boolean;
|
|
1260
|
+
/** Get the integer ID for a token string, or undefined if not in vocabulary. */
|
|
1261
|
+
tokenToId(token: string): number | undefined;
|
|
1262
|
+
/** Get the token string for an integer ID, or undefined if out of range. */
|
|
1263
|
+
idToToken(id: number): string | undefined;
|
|
1264
|
+
/**
|
|
1265
|
+
* Return the full vocabulary as an array ordered by ID.
|
|
1266
|
+
* Index i of the returned array is the token with ID i.
|
|
1267
|
+
*/
|
|
1268
|
+
getVocabulary(): string[];
|
|
1269
|
+
/**
|
|
1270
|
+
* Serialize the fitted tokenizer to a plain JSON-compatible object.
|
|
1271
|
+
* Store it with JSON.stringify(); reload with Tokenizer.fromJSON().
|
|
1272
|
+
*/
|
|
1273
|
+
toJSON(): TokenizerSnapshot;
|
|
1274
|
+
/**
|
|
1275
|
+
* Restore a Tokenizer from a snapshot produced by toJSON().
|
|
1276
|
+
*/
|
|
1277
|
+
static fromJSON(snapshot: TokenizerSnapshot): Tokenizer;
|
|
1278
|
+
private _register;
|
|
1279
|
+
private _assertFitted;
|
|
1280
|
+
}
|
|
1281
|
+
|
|
993
1282
|
declare class EarlyStopping {
|
|
994
1283
|
bestValue: number;
|
|
995
1284
|
readonly patience: number;
|
|
@@ -1062,4 +1351,4 @@ declare class DataAugmentation {
|
|
|
1062
1351
|
};
|
|
1063
1352
|
}
|
|
1064
1353
|
|
|
1065
|
-
export { type Activation, Adam, AttentionHead, Autoencoder, BatchNorm, BiasVector, CausalConv1D, ClipOptimizer, ClippedOptimizerFactory, Conv1D, Conv2D, DataAugmentation, DataLoader, type DataPair, DecisionTree, Dropout, EarlyStopping, EmbeddingMatrix, Flatten, GAN, GRULayer, GaussianNaiveBayes, HopfieldNetwork, KMeans, type KMeansOptions, LRScheduler, LSTMLayer, Layer, LayerNorm, LinearRegression, LogisticRegression, LossPlotter, MaxPool2D, ModelSaver, Momentum, MultiHeadAttention, Network, NetworkLSTM, type NetworkLSTMOptions, NetworkN, type NetworkNOptions, NetworkTransformer, type NetworkTransformerOptions, NetworkTransformerRL, type NetworkTransformerRLOptions, Neuron, NeuronN, type Optimizer, type OptimizerFactory, PCA, Perceptron, RNN, SGD, SOM, type SOMOptions, Seq2Seq, type Serializable, SoftmaxRegression, TCN, type TrainDataset, type TrainMetrics, type TrainableNetwork, type TrainableNetworkWithWeights, Trainer, type TrainerOptions, TransformerBlock, type TransformerBlockOptions, VAE, Value, WeightInspector, WeightMatrix, type WeightStats, accuracy, auc, classificationReport, confusionMatrix, crossEntropy, crossEntropyDelta, crossEntropyDeltaRaw, defaultOptimizer, elu, f1Score, leakyRelu, linear, mae, makeElu, makeLeakyRelu, matMul, mse, mseDelta, perplexity, precision, printConfusionMatrix, r2Score, recall, relu, rmse, rocCurve, sigmoid, softmax, softmaxBackward, tanh, transpose, validate2DArray, validateArray, validateArrayMinLength, validateNumber };
|
|
1354
|
+
export { type Activation, Adam, AttentionHead, Augmenter, Autoencoder, BatchNorm, BiasVector, type CategoricalMap, CausalConv1D, ClipOptimizer, ClippedOptimizerFactory, ContrastiveLearning, Conv1D, Conv2D, DataAugmentation, DataLoader, type DataPair, DatasetLoader, type DatasetLoaderOptions, type DatasetLoaderResult, DecisionTree, Dropout, EarlyStopping, EmbeddingMatrix, type EncodeBatchOptions, type EncodeOptions, Flatten, GAN, GRULayer, GaussianNaiveBayes, HopfieldNetwork, KMeans, type KMeansOptions, LRScheduler, LSTMLayer, Layer, LayerNorm, LearnedPositionalEncoding, LinearRegression, LogisticRegression, LossPlotter, MaxPool2D, ModelSaver, Momentum, MultiHeadAttention, Network, NetworkLSTM, type NetworkLSTMOptions, NetworkN, type NetworkNOptions, NetworkTransformer, type NetworkTransformerOptions, NetworkTransformerRL, type NetworkTransformerRLOptions, Neuron, NeuronN, type Optimizer, type OptimizerFactory, PCA, Perceptron, PositionalEncoding, RNN, SGD, SOM, type SOMOptions, Seq2Seq, type Serializable, SoftmaxRegression, TCN, TSNE, type TSNEOptions, Tokenizer, type TokenizerMode, type TokenizerOptions, type TokenizerSnapshot, type TrainDataset, type TrainMetrics, type TrainableNetwork, type TrainableNetworkWithWeights, Trainer, type TrainerOptions, TransformerBlock, type TransformerBlockOptions, VAE, Value, WeightInspector, WeightMatrix, type WeightStats, Word2Vec, type Word2VecModel, type Word2VecOptions, accuracy, auc, classificationReport, confusionMatrix, crossEntropy, crossEntropyDelta, crossEntropyDeltaRaw, defaultOptimizer, elu, f1Score, leakyRelu, linear, mae, makeElu, makeLeakyRelu, matMul, mse, mseDelta, perplexity, precision, printConfusionMatrix, r2Score, recall, relu, rmse, rocCurve, sigmoid, softmax, softmaxBackward, tanh, transpose, validate2DArray, validateArray, validateArrayMinLength, validateNumber };
|