TensorFlow.
JS Cheat Sheet
Tensors
Dimensions are given as height, width, and
depth, OR number of channels. This format is
used in many TFJS methods. These values are an
example of the dimensions of a common desktop
image size
const dims = [1080, 1920, 3]
Create a tensor with given dimensions.
tf.randomUniform([108, 192, 3], 0,1)
tf.tensor(myArray, dimensions)
Join Tensors, stackinDimension 0=y, 1=x
This example creates a 3-high, 2-wide, 1-deep You wouldn’t typically stack on channels.
tensor
tf.concat([tensor1, tensor2],
tf.tensor([1, 2, 7, 49, 733, 29760], [3, stackingAxis)
2, 1])
Note: This is a special case of concat that always
Special creator function for 2d tensors stacks along the y axis
tf.tensor2d([[4, 832, 22708], [312956,
2716096, 17117832]]) tf.stack( [tensor1, tensor2, tensor3, ...
])
Create a tensor of ones, any dimensions
Reverse the order of elements along a given axis
tf.ones(dims)
tf.reverse(myTensor, reversingAxis)
Create a tensor filled with a given value Introspection. Prints values of tensor in proper
shape
tf.fill(dims, value)
myTensor.print()
Example - creates a 2-high, 4-wide tensor filled
with 5s (but what about Rex?!) Output the shape of a tensor (height, width,
channels).
tf.fill([2, 4], 5)
myTensor.shape // => [ 3, 3, 1 ] (for
Create a tensor where each value is randomly example)
assigned from a uniform distribution over the
interval [ minValue, maxValue ]
tf.randomUniform(dims, minValue,
maxValue)
1
TensorFlow.JS Cheat Sheet
Models: Training and Prediction fig. a fig. b
Create a sequential model
const model = tf.sequential()
Create and add a layer to the model. Can use
other kinds of layers besides dense.
const layer = tf.layers.dense( Resize without interpolating data. alignCorners
units: 10, inputShape: [2], activation: should usually be true (See fig. b)
'relu' ) model.add(layer)
tf.image.resizeBilinear(image, size,
Compile alignCorners)
model.compile({optimizer: "sgd", Use for tensors with values in 0-255
loss: "meanSquaredError"})
myTensor.asType('int32')
Train
(Example)
model.fit(xs, ys, { epochs: 500 }) const myTensor =
tf.randomUniform(dimensions, 0, 255))
Load and predict
const model = Use for tensors with values in 0-1
tf.loadLayersModel(modelURL)
const result = model.predict(input) myTensor.asType('float32')
Convert image to tensor (Example)
const myTensor =
const myTensor = tf.randomUniform(dimensions, 0, 1)
tf.browser.fromPixels(image,
numberOfChannels)
Coordinates
Convert tensor back to image
const startPosition = [y, x, z]
const printCanvas =
document.getElementByID("#dom-element") Note the order: the variables are matched up with
const image = tf.browser.toPixels(tensor, their respective dimension to keep the convention of
printCanvas) dimension ordering
Resize without interpolating data (See fig. a) Crop an image
tf.image.resizeNearestNeighbor(image, const cropped =
size, true) myImageTensor.slice(startPosition, dims)