@tensorflow/tfjs-node
Version:
This repository provides native TensorFlow execution in backend JavaScript applications under the Node.js runtime, accelerated by the TensorFlow C binary under the hood. It provides the same API as [TensorFlow.js](https://js.tensorflow.org/api/latest/).
392 lines (391 loc) • 22.7 kB
JavaScript
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* 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.
* =============================================================================
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var tf = require("@tensorflow/tfjs");
var callbacks_1 = require("./callbacks");
describe('progbarLogger', function () {
// Fake progbar class written for testing.
var FakeProgbar = /** @class */ (function () {
function FakeProgbar(specs, config) {
this.specs = specs;
this.config = config;
this.tickConfigs = [];
}
FakeProgbar.prototype.tick = function (tickConfig) {
this.tickConfigs.push(tickConfig);
};
return FakeProgbar;
}());
var originalStderrColumns;
beforeEach(function () {
// In some CI environments, process.stderr.columns has a null value.
originalStderrColumns = process.stderr.columns;
process.stderr.columns = 100;
});
afterEach(function () {
process.stderr.columns = originalStderrColumns;
});
it('Model.fit with loss, no metric, no validation, verobse = 1', function () { return __awaiter(void 0, void 0, void 0, function () {
var fakeProgbars, consoleMessages, model, numSamples, epochs, batchSize, xs, ys, _i, fakeProgbars_1, fakeProgbar, tickConfigs, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fakeProgbars = [];
spyOn(callbacks_1.progressBarHelper, 'ProgressBar')
.and.callFake(function (specs, config) {
var fakeProgbar = new FakeProgbar(specs, config);
fakeProgbars.push(fakeProgbar);
return fakeProgbar;
});
consoleMessages = [];
spyOn(callbacks_1.progressBarHelper, 'log').and.callFake(function (message) {
consoleMessages.push(message);
});
model = tf.sequential();
model.add(tf.layers.dense({ units: 10, inputShape: [8], activation: 'relu' }));
model.add(tf.layers.dense({ units: 1 }));
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });
numSamples = 14;
epochs = 3;
batchSize = 8;
xs = tf.randomNormal([numSamples, 8]);
ys = tf.randomNormal([numSamples, 1]);
return [4 /*yield*/, model.fit(xs, ys, { epochs: epochs, batchSize: batchSize, verbose: 1 })];
case 1:
_a.sent();
// A progbar object is created for each epoch.
expect(fakeProgbars.length).toEqual(3);
for (_i = 0, fakeProgbars_1 = fakeProgbars; _i < fakeProgbars_1.length; _i++) {
fakeProgbar = fakeProgbars_1[_i];
tickConfigs = fakeProgbar.tickConfigs;
// There are ceil(14 / 8) = 2 batchs per epoch. There should be 1 tick
// for epoch batch, plus a tick at the end of the epoch.
expect(tickConfigs.length).toEqual(3);
for (i = 0; i < 2; ++i) {
expect(Object.keys(tickConfigs[i])).toEqual([
'placeholderForLossesAndMetrics'
]);
expect(tickConfigs[i]['placeholderForLossesAndMetrics'])
.toMatch(/^loss=.*/);
}
expect(tickConfigs[2]).toEqual({ placeholderForLossesAndMetrics: '' });
}
expect(consoleMessages.length).toEqual(6);
expect(consoleMessages[0]).toEqual('Epoch 1 / 3');
expect(consoleMessages[1]).toMatch(/.*ms .*us\/step - loss=.*/);
expect(consoleMessages[2]).toEqual('Epoch 2 / 3');
expect(consoleMessages[3]).toMatch(/.*ms .*us\/step - loss=.*/);
expect(consoleMessages[4]).toEqual('Epoch 3 / 3');
expect(consoleMessages[5]).toMatch(/.*ms .*us\/step - loss=.*/);
return [2 /*return*/];
}
});
}); });
it('Model.fit with loss, metric and validation, verbose = 2', function () { return __awaiter(void 0, void 0, void 0, function () {
var fakeProgbars, consoleMessages, model, numSamples, epochs, batchSize, validationSplit, xs, ys, _i, fakeProgbars_2, fakeProgbar, tickConfigs, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fakeProgbars = [];
spyOn(callbacks_1.progressBarHelper, 'ProgressBar')
.and.callFake(function (specs, config) {
var fakeProgbar = new FakeProgbar(specs, config);
fakeProgbars.push(fakeProgbar);
return fakeProgbar;
});
consoleMessages = [];
spyOn(callbacks_1.progressBarHelper, 'log').and.callFake(function (message) {
consoleMessages.push(message);
});
model = tf.sequential();
model.add(tf.layers.dense({ units: 10, inputShape: [8], activation: 'relu' }));
model.add(tf.layers.dense({ units: 1 }));
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd', metrics: ['acc'] });
numSamples = 40;
epochs = 2;
batchSize = 8;
validationSplit = 0.15;
xs = tf.randomNormal([numSamples, 8]);
ys = tf.randomNormal([numSamples, 1]);
return [4 /*yield*/, model.fit(xs, ys, { epochs: epochs, batchSize: batchSize, validationSplit: validationSplit, verbose: 2 })];
case 1:
_a.sent();
// A progbar object is created for each epoch.
expect(fakeProgbars.length).toEqual(2);
for (_i = 0, fakeProgbars_2 = fakeProgbars; _i < fakeProgbars_2.length; _i++) {
fakeProgbar = fakeProgbars_2[_i];
tickConfigs = fakeProgbar.tickConfigs;
// There are 5 batchs per epoch. There should be 1 tick for epoch batch,
// plus a tick at the end of the epoch.
expect(tickConfigs.length).toEqual(6);
for (i = 0; i < 5; ++i) {
expect(Object.keys(tickConfigs[i])).toEqual([
'placeholderForLossesAndMetrics'
]);
expect(tickConfigs[i]['placeholderForLossesAndMetrics'])
.toMatch(/^acc=.* loss=.*/);
}
expect(tickConfigs[5]).toEqual({ placeholderForLossesAndMetrics: '' });
}
expect(consoleMessages.length).toEqual(4);
expect(consoleMessages[0]).toEqual('Epoch 1 / 2');
expect(consoleMessages[1])
.toMatch(/.*ms .*us\/step - acc=.* loss=.* val_acc=.* val_loss=.*/);
expect(consoleMessages[2]).toEqual('Epoch 2 / 2');
expect(consoleMessages[3])
.toMatch(/.*ms .*us\/step - acc=.* loss=.* val_acc=.* val_loss=.*/);
return [2 /*return*/];
}
});
}); });
it('Model.fit does not create ProgbarLogger if verbose is 0', function () { return __awaiter(void 0, void 0, void 0, function () {
var fakeProgbars, consoleMessages, model, numSamples, epochs, batchSize, validationSplit, xs, ys;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fakeProgbars = [];
spyOn(callbacks_1.progressBarHelper, 'ProgressBar')
.and.callFake(function (specs, config) {
var fakeProgbar = new FakeProgbar(specs, config);
fakeProgbars.push(fakeProgbar);
return fakeProgbar;
});
consoleMessages = [];
spyOn(callbacks_1.progressBarHelper, 'log').and.callFake(function (message) {
consoleMessages.push(message);
});
model = tf.sequential();
model.add(tf.layers.dense({ units: 10, inputShape: [8], activation: 'relu' }));
model.add(tf.layers.dense({ units: 1 }));
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd', metrics: ['acc'] });
numSamples = 40;
epochs = 2;
batchSize = 8;
validationSplit = 0.15;
xs = tf.randomNormal([numSamples, 8]);
ys = tf.randomNormal([numSamples, 1]);
return [4 /*yield*/, model.fit(xs, ys, { epochs: epochs, batchSize: batchSize, validationSplit: validationSplit, verbose: 0 })];
case 1:
_a.sent();
expect(fakeProgbars.length).toEqual(0);
return [2 /*return*/];
}
});
}); });
it('Model.fitDataset: batchesPerEpoch specified, verbose = 1', function () { return __awaiter(void 0, void 0, void 0, function () {
var fakeProgbars, consoleMessages, epochs, xDataset, yDataset, dataset, model;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fakeProgbars = [];
spyOn(callbacks_1.progressBarHelper, 'ProgressBar')
.and.callFake(function (specs, config) {
var fakeProgbar = new FakeProgbar(specs, config);
fakeProgbars.push(fakeProgbar);
return fakeProgbar;
});
consoleMessages = [];
spyOn(callbacks_1.progressBarHelper, 'log').and.callFake(function (message) {
consoleMessages.push(message);
});
epochs = 2;
xDataset = tf.data.array([[1, 2], [3, 4], [5, 6], [7, 8]])
.map(function (x) { return tf.tensor2d(x, [1, 2]); });
yDataset = tf.data.array([[1], [2], [3], [4]]).map(function (y) { return tf.tensor2d(y, [1, 1]); });
dataset = tf.data.zip({ xs: xDataset, ys: yDataset }).repeat(epochs);
model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [2] }));
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });
return [4 /*yield*/, model.fitDataset(dataset, { batchesPerEpoch: 4, epochs: epochs, verbose: 1 })];
case 1:
_a.sent();
expect(consoleMessages.length).toEqual(4);
expect(consoleMessages[0]).toEqual('Epoch 1 / 2');
expect(consoleMessages[1]).toMatch(/.*ms .*us\/step - loss=.*/);
expect(consoleMessages[2]).toEqual('Epoch 2 / 2');
expect(consoleMessages[3]).toMatch(/.*ms .*us\/step - loss=.*/);
return [2 /*return*/];
}
});
}); });
it('Model.fitDataset: batchesPerEpoch unavailable, verbose = 1', function () { return __awaiter(void 0, void 0, void 0, function () {
var fakeProgbars, consoleMessages, epochs, xDataset, yDataset, dataset, model;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fakeProgbars = [];
spyOn(callbacks_1.progressBarHelper, 'ProgressBar')
.and.callFake(function (specs, config) {
var fakeProgbar = new FakeProgbar(specs, config);
fakeProgbars.push(fakeProgbar);
return fakeProgbar;
});
consoleMessages = [];
spyOn(callbacks_1.progressBarHelper, 'log').and.callFake(function (message) {
consoleMessages.push(message);
});
epochs = 2;
xDataset = tf.data.array([[1, 2], [3, 4], [5, 6], [7, 8]])
.map(function (x) { return tf.tensor2d(x, [1, 2]); });
yDataset = tf.data.array([[1], [2], [3], [4]]).map(function (y) { return tf.tensor2d(y, [1, 1]); });
dataset = tf.data.zip({ xs: xDataset, ys: yDataset }).repeat(epochs);
model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [2] }));
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });
// `batchesPerEpoch` is not specified. Instead, `fitDataset()` relies on
// the `done` field being `true` to terminate the epoch(s).
return [4 /*yield*/, model.fitDataset(dataset, { epochs: epochs, verbose: 1 })];
case 1:
// `batchesPerEpoch` is not specified. Instead, `fitDataset()` relies on
// the `done` field being `true` to terminate the epoch(s).
_a.sent();
expect(consoleMessages.length).toEqual(4);
expect(consoleMessages[0]).toEqual('Epoch 1 / 2');
expect(consoleMessages[1]).toMatch(/.*ms .*us\/step - loss=.*/);
expect(consoleMessages[2]).toEqual('Epoch 2 / 2');
expect(consoleMessages[3]).toMatch(/.*ms .*us\/step - loss=.*/);
return [2 /*return*/];
}
});
}); });
it('Model.fitDataset: verbose = 0 leads to no logging', function () { return __awaiter(void 0, void 0, void 0, function () {
var fakeProgbars, consoleMessages, xDataset, yDataset, dataset, model, history;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fakeProgbars = [];
spyOn(callbacks_1.progressBarHelper, 'ProgressBar')
.and.callFake(function (specs, config) {
var fakeProgbar = new FakeProgbar(specs, config);
fakeProgbars.push(fakeProgbar);
return fakeProgbar;
});
consoleMessages = [];
spyOn(callbacks_1.progressBarHelper, 'log').and.callFake(function (message) {
consoleMessages.push(message);
});
xDataset = tf.data.array([[1, 2], [3, 4], [5, 6], [7, 8]])
.map(function (x) { return tf.tensor2d(x, [1, 2]); });
yDataset = tf.data.array([[1], [2], [3], [4]]).map(function (y) { return tf.tensor2d(y, [1, 1]); });
dataset = tf.data.zip({ xs: xDataset, ys: yDataset });
model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [2] }));
model.compile({ loss: 'meanSquaredError', optimizer: 'sgd' });
return [4 /*yield*/, model.fitDataset(dataset, { epochs: 1, verbose: 0 })];
case 1:
history = _a.sent();
expect(history.history.loss.length).toEqual(1);
expect(consoleMessages.length)
.toEqual(0); // No logging should have happened.
return [2 /*return*/];
}
});
}); });
});
describe('getSuccinctNumberDisplay', function () {
it('Not finite', function () {
expect((0, callbacks_1.getSuccinctNumberDisplay)(Infinity)).toEqual('Infinity');
expect((0, callbacks_1.getSuccinctNumberDisplay)(-Infinity)).toEqual('-Infinity');
expect((0, callbacks_1.getSuccinctNumberDisplay)(NaN)).toEqual('NaN');
});
it('zero', function () {
expect((0, callbacks_1.getSuccinctNumberDisplay)(0)).toEqual('0.00');
});
it('Finite and positive', function () {
expect((0, callbacks_1.getSuccinctNumberDisplay)(300)).toEqual('300.00');
expect((0, callbacks_1.getSuccinctNumberDisplay)(30)).toEqual('30.00');
expect((0, callbacks_1.getSuccinctNumberDisplay)(1)).toEqual('1.00');
expect((0, callbacks_1.getSuccinctNumberDisplay)(1e-2)).toEqual('0.0100');
expect((0, callbacks_1.getSuccinctNumberDisplay)(1e-3)).toEqual('1.00e-3');
expect((0, callbacks_1.getSuccinctNumberDisplay)(4e-3)).toEqual('4.00e-3');
expect((0, callbacks_1.getSuccinctNumberDisplay)(1e-6)).toEqual('1.00e-6');
});
it('Finite and negative', function () {
expect((0, callbacks_1.getSuccinctNumberDisplay)(-300)).toEqual('-300.00');
expect((0, callbacks_1.getSuccinctNumberDisplay)(-30)).toEqual('-30.00');
expect((0, callbacks_1.getSuccinctNumberDisplay)(-1)).toEqual('-1.00');
expect((0, callbacks_1.getSuccinctNumberDisplay)(-1e-2)).toEqual('-0.0100');
expect((0, callbacks_1.getSuccinctNumberDisplay)(-1e-3)).toEqual('-1.00e-3');
expect((0, callbacks_1.getSuccinctNumberDisplay)(-4e-3)).toEqual('-4.00e-3');
expect((0, callbacks_1.getSuccinctNumberDisplay)(-1e-6)).toEqual('-1.00e-6');
});
});
describe('getDisplayDecimalPlaces', function () {
it('Not finite', function () {
expect((0, callbacks_1.getDisplayDecimalPlaces)(Infinity)).toEqual(2);
expect((0, callbacks_1.getDisplayDecimalPlaces)(-Infinity)).toEqual(2);
expect((0, callbacks_1.getDisplayDecimalPlaces)(NaN)).toEqual(2);
});
it('zero', function () {
expect((0, callbacks_1.getDisplayDecimalPlaces)(0)).toEqual(2);
});
it('Finite and positive', function () {
expect((0, callbacks_1.getDisplayDecimalPlaces)(300)).toEqual(2);
expect((0, callbacks_1.getDisplayDecimalPlaces)(30)).toEqual(2);
expect((0, callbacks_1.getDisplayDecimalPlaces)(1)).toEqual(2);
expect((0, callbacks_1.getDisplayDecimalPlaces)(1e-2)).toEqual(4);
expect((0, callbacks_1.getDisplayDecimalPlaces)(1e-3)).toEqual(5);
expect((0, callbacks_1.getDisplayDecimalPlaces)(4e-3)).toEqual(5);
expect((0, callbacks_1.getDisplayDecimalPlaces)(1e-6)).toEqual(8);
});
it('Finite and negative', function () {
expect((0, callbacks_1.getDisplayDecimalPlaces)(-300)).toEqual(2);
expect((0, callbacks_1.getDisplayDecimalPlaces)(-30)).toEqual(2);
expect((0, callbacks_1.getDisplayDecimalPlaces)(-1)).toEqual(2);
expect((0, callbacks_1.getDisplayDecimalPlaces)(-1e-2)).toEqual(4);
expect((0, callbacks_1.getDisplayDecimalPlaces)(-1e-3)).toEqual(5);
expect((0, callbacks_1.getDisplayDecimalPlaces)(-4e-3)).toEqual(5);
expect((0, callbacks_1.getDisplayDecimalPlaces)(-1e-6)).toEqual(8);
});
});
;