简体   繁体   English

将 TensorFlow JS model.predict 的值转化为变量

[英]Get value of TensorFlow JS model.predict into a variable

I am trying to implement a neural network in JS, which can predict certain values and then store these values in a variable for later use.我正在尝试在 JS 中实现一个神经网络,它可以预测某些值,然后将这些值存储在一个变量中以备后用。

async function processModel(inputs) {
  const model = await tf.loadLayersModel(modelURL);
  inputs = tf.tensor(inputs);

  var predictions = model.predict(inputs);
  predictions = predictions.dataSync();

  console.log(typeof(predictions));

  return predictions;
}

Launching this informs me that predictions is of type object .启动它告诉我predictionsobject类型。 I would like to get the values of the Promise which is returned and store these values in a variable, so I can compare them to other variables.我想获取返回的 Promise 的值并将这些值存储在一个变量中,以便我可以将它们与其他变量进行比较。

Can anyone help me with this please?任何人都可以帮我解决这个问题吗?

prredictions in an array. prredictions中的prredictions The array indexing is the way to get the predicted value数组索引是获取预测值的方式

According to datasync method , variable.dataSync() returns DataTypeMap[NumericDataType] .根据datasync 方法variable.dataSync()返回DataTypeMap[NumericDataType] It returns a TypedArray of any NumericDataType .它返回一个TypedArray任何NumericDataType

According to MDN documentation on TypedArray ,根据关于 TypedArray 的 MDN 文档

a TypedArray object describes an array-like view of an underlying binary data buffer. TypedArray对象描述了底层二进制数据缓冲区的类似数组的视图。

So, you are correct that console.log(typeof(predictions)) will print object in the console.因此,您对console.log(typeof(predictions))将在控制台中打印object是正确的。

But as predictions is a TypedArray , you can use it like regular JavaScript array.但由于predictions是一个TypedArray ,您可以像使用常规 JavaScript 数组一样使用它。 You can print predictions[0] and so on.您可以打印predictions[0]等。

Let's see an example of TypedArray :让我们看一个TypedArray的例子:

 // create a TypedArray with a size in bytes const typedArrayExample = new Float32Array(2); typedArrayExample[0] = 32.36; console.log(typeof(typedArrayExample)); // object console.log(typedArrayExample); // {"0": 32.36000061035156, "1": 0} console.log(typedArrayExample[0]); // 32.36000061035156

Reference:参考:

You can access the predicted values in the output Tensor using the arraySync() method.您可以使用 arraySync() 方法访问输出张量中的预测值。 For eg if the output Tensor is a two dimensional array with only a single output value, then the code below will give you the predicted value.例如,如果输出张量是一个只有一个输出值的二维数组,那么下面的代码将为您提供预测值。

 const resultTensor = model.predict(tf.tensor2d([50], [1, 1]));
 const predictedValue = resultTensor.arraySync()[0][0];
 console.log(predictedValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM