Skip to content

Commit

Permalink
Migrate more old API (Tensor3D.new and Tensor4D.new) (tensorflow#657)
Browse files Browse the repository at this point in the history
  • Loading branch information
dsmilkov authored Feb 6, 2018
1 parent c172b23 commit 803b7e7
Show file tree
Hide file tree
Showing 45 changed files with 852 additions and 833 deletions.
2 changes: 1 addition & 1 deletion demos/GraphSource.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ limitations under the License.
Include this file in Vue applications that need Chart. -->
</template>

<<script>
<script>
const Chart = require('chart.js');
</script>
4 changes: 2 additions & 2 deletions demos/adder/adder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ const inA: HTMLInputElement = document.getElementById('A') as HTMLInputElement;
const inB: HTMLInputElement = document.getElementById('B') as HTMLInputElement;

export async function execute(event?: Event) {
const a = dl.Scalar.new(+inA.value);
const b = dl.Scalar.new(+inB.value);
const a = dl.scalar(+inA.value);
const b = dl.scalar(+inB.value);
const result = await a.add(b).data();
outputElement.innerText = result.toString();
}
Expand Down
8 changes: 4 additions & 4 deletions demos/benchmarks/batchnormalization3d_benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ export class BatchNormalization3DCPUBenchmark implements BenchmarkTest {
const math = new dl.NDArrayMath('cpu', safeMode);
dl.ENV.setMath(math);
const x: dl.Tensor3D = dl.randomUniform([size, size, 8], -1, 1);
const mean = dl.Tensor1D.new([0]);
const variance = dl.Tensor1D.new([1]);
const mean = dl.tensor1d([0]);
const variance = dl.tensor1d([1]);
const varianceEpsilon = .001;
const start = performance.now();

Expand All @@ -55,8 +55,8 @@ export class BatchNormalization3DGPUBenchmark implements BenchmarkTest {
dl.ENV.setMath(math);

const x: dl.Tensor3D = dl.randomUniform([size, size, 8], -1, 1);
const mean = dl.Tensor1D.new([0]);
const variance = dl.Tensor1D.new([1]);
const mean = dl.tensor1d([0]);
const variance = dl.tensor1d([1]);
const varianceEpsilon = .001;

const benchmark = () =>
Expand Down
3 changes: 1 addition & 2 deletions demos/benchmarks/conv_benchmarks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class ConvGPUBenchmark implements BenchmarkTest {
dl.ENV.setMath(math);

const inDepth = params.inDepth;
const inShape: [number, number, number] = [size, size, inDepth, 3];
const inShape: [number, number, number] = [size, size, inDepth];
const filterSize = params.filterSize;
const stride = params.stride;
const pad = params.pad;
Expand All @@ -54,7 +54,6 @@ export class ConvGPUBenchmark implements BenchmarkTest {
inDepth, regParams.outDepth, filterSize, filterSize);
W = dl.randomUniform(wShape, -1, 1);
b = dl.randomUniform([regParams.outDepth], -1, 1);

benchmark = () => x.conv2d(W, b, stride, pad);
} else if (opType === 'transposed') {
const regParams = params as RegularConvParams;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ class ComplementaryColorModel {
dl.tidy(() => {
const mapping = [{
tensor: this.inputTensor,
data: dl.Tensor1D.new(this.normalizeColor(rgbColor)),
data: dl.tensor1d(this.normalizeColor(rgbColor)),
}];
const evalOutput = this.session.eval(this.predictionTensor, mapping);
const values = evalOutput.dataSync();
Expand Down Expand Up @@ -165,9 +165,9 @@ class ComplementaryColorModel {

// Store the data within Tensor1Ds so that learnjs can use it.
const inputArray: dl.Tensor1D[] =
rawInputs.map(c => dl.Tensor1D.new(this.normalizeColor(c)));
rawInputs.map(c => dl.tensor1d(this.normalizeColor(c)));
const targetArray: dl.Tensor1D[] = rawInputs.map(
c => dl.Tensor1D.new(
c => dl.tensor1d(
this.normalizeColor(this.computeComplementaryColor(c))));

// This provider will shuffle the training data (and will do so in a way
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ We store each input (now a list of 3 values between 0 and 1) within an `Tensor1D

```ts
const inputArray: Tensor1D[] =
rawInputs.map(c => Tensor1D.new(this.normalizeColor(c)));
rawInputs.map(c => dl.tensor1d(this.normalizeColor(c)));
const targetArray: Tensor1D[] = rawInputs.map(
c => Tensor1D.new(
c => dl.tensor1d(
this.normalizeColor(this.computeComplementaryColor(c))));
```

Expand Down Expand Up @@ -253,7 +253,7 @@ predict(rgbColor: number[]): number[] {
dl.tidy((keep, track) => {
const mapping = [{
tensor: this.inputTensor,
data: Tensor1D.new(this.normalizeColor(rgbColor)),
data: dl.tensor1d(this.normalizeColor(rgbColor)),
}];
const evalOutput = this.session.eval(this.predictionTensor, mapping);
const values = evalOutput.dataSync();
Expand Down
8 changes: 4 additions & 4 deletions demos/fast-style-transfer/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ export class TransformNet implements dl.Model {

constructor(private style: string) {
this.variableDictionary = {};
this.timesScalar = dl.Scalar.new(150);
this.plusScalar = dl.Scalar.new(255. / 2);
this.epsilonScalar = dl.Scalar.new(1e-3);
this.timesScalar = dl.scalar(150);
this.plusScalar = dl.scalar(255. / 2);
this.epsilonScalar = dl.scalar(1e-3);
}

setStyle(style: string) {
Expand Down Expand Up @@ -78,7 +78,7 @@ export class TransformNet implements dl.Model {
.mul(this.timesScalar)
.add(this.plusScalar)
.clip(0, 255)
.div(dl.Scalar.new(255)) as dl.Tensor3D;
.div(dl.scalar(255)) as dl.Tensor3D;
});

return img;
Expand Down
6 changes: 3 additions & 3 deletions demos/game_of_life/game_of_life.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class GameOfLife {
}
world = dl.keep(worldPadded);
worldNext = dl.keep(GameOfLife.padArray(
dl.Tensor2D.new(randWorld.shape, nextWorldValues, 'int32')));
dl.tensor2d(nextWorldValues, randWorld.shape, 'int32')));
});
return [world, worldNext];
}
Expand Down Expand Up @@ -106,7 +106,7 @@ export class GameOfLife {
}
}
}
return dl.Tensor2D.new(shape as [number, number], values, 'int32');
return dl.tensor2d(values, shape as [number, number], 'int32');
}
}

Expand Down Expand Up @@ -191,7 +191,7 @@ export class GameOfLifeModel {
const evalOutput = this.session.eval(this.predictionTensor, mapping);
values = evalOutput.dataSync();
});
return dl.Tensor2D.new([this.size, this.size], values);
return dl.tensor2d(values, [this.size, this.size]);
}

private setTrainingData(worlds: Array<[dl.Tensor, dl.Tensor]>): void {
Expand Down
19 changes: 9 additions & 10 deletions demos/intro/intro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ import * as dl from 'deeplearn';
* 'NDArrayMath with WebGL backend' section of tutorial
*/
async function intro() {
const a = dl.Tensor2D.new([2, 2], [1.0, 2.0, 3.0, 4.0]);
const b = dl.Tensor2D.new([2, 2], [0.0, 2.0, 4.0, 6.0]);
const a = dl.tensor2d([1.0, 2.0, 3.0, 4.0], [2, 2]);
const b = dl.tensor2d([0.0, 2.0, 4.0, 6.0], [2, 2]);

const size = dl.Scalar.new(a.size);
const size = dl.scalar(a.size);

// Non-blocking math calls.
const average = a.sub(b).square().sum().div(size);
Expand All @@ -49,7 +49,7 @@ async function intro() {
// Variables are containers that hold a value that can be updated from
// training.
// Here we initialize the multiplier variable randomly.
const multiplier = g.variable('multiplier', dl.Tensor2D.randNormal([1, 3]));
const multiplier = g.variable('multiplier', dl.randomNormal([1, 3]));

// Top level graph methods take Tensors and return Tensors.
const outputTensor = g.matmul(multiplier, inputTensor);
Expand All @@ -69,13 +69,12 @@ async function intro() {
const optimizer = new dl.SGDOptimizer(learningRate);

const inputs: dl.Tensor1D[] = [
dl.Tensor1D.new([1.0, 2.0, 3.0]), dl.Tensor1D.new([10.0, 20.0, 30.0]),
dl.Tensor1D.new([100.0, 200.0, 300.0])
dl.tensor1d([1.0, 2.0, 3.0]), dl.tensor1d([10.0, 20.0, 30.0]),
dl.tensor1d([100.0, 200.0, 300.0])
];

const labels: dl.Tensor1D[] = [
dl.Tensor1D.new([4.0]), dl.Tensor1D.new([40.0]), dl.Tensor1D.new([400.0])
];
const labels: dl.Tensor1D[] =
[dl.tensor1d([4.0]), dl.tensor1d([40.0]), dl.tensor1d([400.0])];

// Shuffles inputs and labels and keeps them mutually in sync.
const shuffledInputProviderBuilder =
Expand Down Expand Up @@ -103,7 +102,7 @@ async function intro() {
});
}

const testInput = dl.Tensor1D.new([0.1, 0.2, 0.3]);
const testInput = dl.tensor1d([0.1, 0.2, 0.3]);

// session.eval can take Tensors as input data.
const testFeedEntries: dl.FeedEntry[] =
Expand Down
4 changes: 2 additions & 2 deletions demos/latent-space-explorer/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ import BasisDimensions from './components/BasisDimensions.vue';
import FontChooser from './components/FontChooser.vue';
import Alphabet from './components/Alphabet.vue';
import {FontModel} from './utils/FontModel';
import {Tensor1D} from 'deeplearn';
import * as dl from 'deeplearn';

export default {
components: {
Expand Down Expand Up @@ -157,7 +157,7 @@ export default {
// Set the selected sample and initial dimension slider values based
// on the provided URL hash.
this.dimSliderVals = dimVals;
this.selectedSample = Tensor1D.new(dimVals);
this.selectedSample = dl.tensor1d(dimVals);
}
}

Expand Down
6 changes: 3 additions & 3 deletions demos/latent-space-explorer/components/BasisDimensions.vue
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ limitations under the License.
import Sample from './Sample.vue';
import Tray from './Tray.vue';
import {range} from 'd3-array';
import {Tensor1D, ENV} from 'deeplearn';
import * as dl from 'deeplearn';

const math = ENV.math;
const math = dl.ENV.math;

export default {
components: {Sample, Tray},
Expand All @@ -54,7 +54,7 @@ export default {
model: function(m) {
const dims = m ? m.dimensions: 0;
this.basisDimensions = range(dims).map(dim => {
return math.oneHot(Tensor1D.new([dim]), dims).as1D();
return math.oneHot(dl.tensor1d([dim]), dims).as1D();
});
}
},
Expand Down
8 changes: 4 additions & 4 deletions demos/latent-space-explorer/components/Tray.vue
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ import Axis from './XAxis.vue';
import {range} from 'd3-array';
import {format} from 'd3-format';
import {scaleLinear, scaleBand} from 'd3-scale';
import {Scalar, ENV} from 'deeplearn';
import * as dl from 'deeplearn';

const math = ENV.math;
const math = dl.ENV.math;

export default {
components: {Sample, Axis},
Expand Down Expand Up @@ -135,7 +135,7 @@ export default {
let samples = [];
for (var i = 0; i < this.numSamples; i++) {
let delta = math.sub(
Scalar.new(this.pos(i)), Scalar.new(this.selectedValue));
dl.scalar(this.pos(i)), dl.scalar(this.selectedValue));
let newSample = math.add(math.multiply(
this.unitDirection, delta), this.selectedSample);
samples.push({
Expand All @@ -156,7 +156,7 @@ export default {
},
select: function(x) {
const value = this.hoverScale(x)
let delta = math.sub(Scalar.new(value), Scalar.new(this.selectedValue));
let delta = math.sub(dl.scalar(value), dl.scalar(this.selectedValue));
let newSample = math.add(math.multiply(
this.unitDirection, delta), this.selectedSample);
this.$emit("select", {selectedSample: newSample});
Expand Down
4 changes: 2 additions & 2 deletions demos/latent-space-explorer/utils/FontExamples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

import {Tensor1D} from 'deeplearn';
import * as dl from 'deeplearn';

function convert(arr: number[]) {
return Tensor1D.new(arr);
return dl.tensor1d(arr);
}
/* tslint:disable:max-line-length */
export const zero = convert([
Expand Down
4 changes: 2 additions & 2 deletions demos/latent-space-explorer/utils/FontModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class FontModel {
private variables: {[varName: string]: dl.Tensor};
private inferCache = new Cache(this, this.infer);
private numberOfValidChars = 62;
private multiplierScalar = dl.Scalar.new(255);
private multiplierScalar = dl.scalar(255);

constructor() {
// Set up character ID mapping.
Expand Down Expand Up @@ -71,7 +71,7 @@ export class FontModel {
}

const adjusted = dl.tidy(() => {
const idx = dl.Tensor1D.new([charId]);
const idx = dl.tensor1d([charId]);
const onehotVector = dl.oneHot(idx, this.numberOfValidChars).as1D();

const axis = 0;
Expand Down
4 changes: 2 additions & 2 deletions demos/lstm/lstm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ reader.getAllVariables().then(async vars => {
const results: number[] = [];

await dl.tidy(async () => {
const forgetBias = dl.Scalar.new(1.0);
const forgetBias = dl.scalar(1.0);
const lstm1 = (data: dl.Tensor2D, c: dl.Tensor2D, h: dl.Tensor2D) =>
dl.basicLSTMCell(forgetBias, lstmKernel1, lstmBias1, data, c, h);
const lstm2 = (data: dl.Tensor2D, c: dl.Tensor2D, h: dl.Tensor2D) =>
Expand All @@ -55,7 +55,7 @@ reader.getAllVariables().then(async vars => {

let input = primerData;
for (let i = 0; i < expected.length; i++) {
const onehot = dl.oneHot(dl.Tensor1D.new([input]), 10);
const onehot = dl.oneHot(dl.tensor1d([input]), 10);

const output = dl.multiRNNCell([lstm1, lstm2], onehot, c, h);

Expand Down
24 changes: 10 additions & 14 deletions demos/ml_beginners/ml_beginners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ async function mlBeginners() {
// This file parallels (some of) the code in the ML Beginners tutorial.
{
const matrixShape: [number, number] = [2, 3]; // 2 rows, 3 columns.
const matrix = dl.Tensor2D.new(matrixShape, [10, 20, 30, 40, 50, 60]);
const vector = dl.Tensor1D.new([0, 1, 2]);
const matrix = dl.tensor2d([10, 20, 30, 40, 50, 60], matrixShape);
const vector = dl.tensor1d([0, 1, 2]);
const result = dl.matrixTimesVector(matrix, vector);

console.log('result shape:', result.shape);
Expand All @@ -37,9 +37,9 @@ async function mlBeginners() {
const x = g.placeholder('x', []);
// Make new variables in the dl.Graph, 'a', 'b', 'c' with shape [] and
// random initial values.
const a = g.variable('a', dl.Scalar.new(Math.random()));
const b = g.variable('b', dl.Scalar.new(Math.random()));
const c = g.variable('c', dl.Scalar.new(Math.random()));
const a = g.variable('a', dl.scalar(Math.random()));
const b = g.variable('b', dl.scalar(Math.random()));
const c = g.variable('c', dl.scalar(Math.random()));
// Make new tensors representing the output of the operations of the
// quadratic.
const order2 = g.multiply(a, g.square(x));
Expand All @@ -63,7 +63,7 @@ async function mlBeginners() {
// providing a value 4 for "x".
// NOTE: "a", "b", and "c" are randomly initialized, so this will give us
// something random.
let result = session.eval(y, [{tensor: x, data: dl.Scalar.new(4)}]);
let result = session.eval(y, [{tensor: x, data: dl.scalar(4)}]);
console.log(await result.data());

/**
Expand All @@ -73,13 +73,9 @@ async function mlBeginners() {
// To do this, we need to provide examples of x and y.
// The values given here are for values a = 3, b = 2, c = 1, with random
// noise added to the output so it's not a perfect fit.
const xs = [
dl.Scalar.new(0), dl.Scalar.new(1), dl.Scalar.new(2), dl.Scalar.new(3)
];
const ys = [
dl.Scalar.new(1.1), dl.Scalar.new(5.9), dl.Scalar.new(16.8),
dl.Scalar.new(33.9)
];
const xs = [dl.scalar(0), dl.scalar(1), dl.scalar(2), dl.scalar(3)];
const ys =
[dl.scalar(1.1), dl.scalar(5.9), dl.scalar(16.8), dl.scalar(33.9)];
// When training, it's important to shuffle your data!
const shuffledInputProviderBuilder =
new dl.InCPUMemoryShuffledInputProviderBuilder([xs, ys]);
Expand Down Expand Up @@ -109,7 +105,7 @@ async function mlBeginners() {
}

// Now print the value from the trained model for x = 4, should be ~57.0.
result = session.eval(y, [{tensor: x, data: dl.Scalar.new(4)}]);
result = session.eval(y, [{tensor: x, data: dl.scalar(4)}]);
console.log('result should be ~57.0:');
console.log(await result.data());
});
Expand Down
6 changes: 3 additions & 3 deletions demos/mnist/mnist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ reader.getAllVariables().then(vars => {

let numCorrect = 0;
for (let i = 0; i < data.images.length; i++) {
const x = dl.Tensor1D.new(data.images[i]);
const x = dl.tensor1d(data.images[i]);

// Infer through the model to get a prediction.
const predictedLabel = Math.round(await infer(x, vars).val());
Expand All @@ -45,8 +45,8 @@ reader.getAllVariables().then(vars => {
}

// Show the image.
const result = renderResults(
dl.Tensor1D.new(data.images[i]), label, predictedLabel);
const result =
renderResults(dl.tensor1d(data.images[i]), label, predictedLabel);
document.body.appendChild(result);
}

Expand Down
Loading

0 comments on commit 803b7e7

Please sign in to comment.