Skip to content

chore: Add toJSON and fromJSON to AE #950

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/autoencoder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,25 @@ test('test a data sample for anomalies', async () => {
includesAnomalies(1, 0, 1);
includesAnomalies(1, 1, 0);
});

test('restores a net fromJSON', () => {
expect(result.error).toBeLessThanOrEqual(errorThresh);
function xor(net: AE<number[], number[]>, ...args: number[]) {
return Math.round(net.denoise(args)[2]);
}

const json = xornet.toJSON();
const net = new AE<number[], number[]>({
json,
});

const run1 = xor(net, 0, 0, 0);
const run2 = xor(net, 0, 1, 1);
const run3 = xor(net, 1, 0, 1);
const run4 = xor(net, 1, 1, 0);

expect(run1).toBe(0);
expect(run2).toBe(1);
expect(run3).toBe(1);
expect(run4).toBe(0);
});
17 changes: 16 additions & 1 deletion src/autoencoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
IJSONLayer,
INeuralNetworkData,
INeuralNetworkDatum,
INeuralNetworkJSON,
INeuralNetworkTrainOptions,
} from './neural-network';
import {
Expand All @@ -16,6 +17,7 @@ export interface IAEOptions {
binaryThresh: number;
decodedSize: number;
hiddenLayers: number[];
json?: INeuralNetworkJSON;
}

/**
Expand All @@ -26,7 +28,7 @@ export class AE<
EncodedData extends INeuralNetworkData
> {
private decoder?: NeuralNetworkGPU<EncodedData, DecodedData>;
private readonly denoiser: NeuralNetworkGPU<DecodedData, DecodedData>;
private denoiser: NeuralNetworkGPU<DecodedData, DecodedData>;

constructor(options?: Partial<IAEOptions>) {
// Create default options for the autoencoder.
Expand All @@ -47,6 +49,10 @@ export class AE<

// Create the denoiser subnet of the autoencoder.
this.denoiser = new NeuralNetworkGPU<DecodedData, DecodedData>(options);

if (options.json) {
this.denoiser = this.denoiser.fromJSON(options.json);
}
}

/**
Expand Down Expand Up @@ -191,6 +197,15 @@ export class AE<
return (decoder as unknown) as NeuralNetworkGPU<EncodedData, DecodedData>;
}

toJSON(): INeuralNetworkJSON {
return this.denoiser.toJSON();
}

fromJSON(json: INeuralNetworkJSON): this {
this.denoiser = this.denoiser.fromJSON(json);
return this;
}

/**
* Get the layer containing the encoded representation.
*/
Expand Down