Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow.js print() and dataSync methods on model.predict not working

I've distilled this down to as few lines of code as I could to get to the bottom of this issue.

currently these are the config constants below (I'm using a array of length 1 to represent tokenised words I'm doing semantic analysis on.

export const top_words = 10000; 
export const max_review_length = 1
export const embedding_vector_length = 32

Here is the code, I've substituted the tensors with mock tokens or one word length for now. I'm getting typescript linting errors showing that .print() or .dataSync()[0] will fail on the basis that they do not exist. the line of code in question (.predict) is returning a tensor which has no print or datasync method

const x_train = tf.tensor([[80], [86], [10], [1], [2]]);
const y_train = tf.tensor([[1],[1],[1],[0],[0]])
const x_val = tf.tensor([[1], [3], [102], [100], [104]]);
const y_val = tf.tensor([[0],[0],[1],[1],[1]])
const model = tf.sequential();


model.add(tf.layers.embedding({ inputDim: dictionary.size, inputLength: max_review_length, outputDim: 1 }))
model.add(tf.layers.lstm({units: 200, dropout: 0.2, recurrentDropout: 0.2}))
model.add(tf.layers.dense({units: 1, activation:'sigmoid'}))
model.compile({ loss:'binaryCrossentropy', optimizer:'rmsprop', metrics:['accuracy'] }) 
const history=model.fit(x_train, y_train,{epochs: 12, batchSize: 5}) 
history.then(hist => console.log(hist.history.loss)) // Show error loss vs epoch

const predictOut =  model.predict(tf.tensor2d([10]))

predictOut.print() or predictOut.dataSync()[0] returns

like image 676
Happy Machine Avatar asked Aug 31 '25 17:08

Happy Machine


1 Answers

If you are using TypeScript you need to specify what predict() returns in such way:

(model.predict(...) as tf.Tensor).print()

since predict() can return either a Tensor or Tensor[]

like image 62
Rostyslav Makhanko Avatar answered Sep 02 '25 23:09

Rostyslav Makhanko