首页 > 解决方案 > tfjs codelab“从二维数据进行预测”在 tf-vis.render.scatterplot 中使用 values 关键字

问题描述

为什么我不能用其他变量名(如 values1)替换值?values 是一个 js 关键字,所以我认为这里发生了一些非常有趣的事情。

在此代码实验室中: https ://codelabs.developers.google.com/codelabs/tfjs-training-regression/index.html#2

在此代码段中:

async function run() {
  // Load and plot the original input data that we are going to train on.
  const data = await getData();
  const values = data.map(d => ({
    x: d.horsepower,
    y: d.mpg,
  }));

  tfvis.render.scatterplot(
    {name: 'Horsepower v MPG'},
    {values}, 
    {
      xLabel: 'Horsepower',
      yLabel: 'MPG',
      height: 300
    }
  );

  // More code will be added below
}

tfjs 文档不需要使用 values 关键字: https ://js.tensorflow.org/api_vis/latest/#render.scatterplot

如果我按照教程中的说明设置 HTML 并使用相同的 js 代码,我会在浏览器 (firefox) 中获得预期的绘图。

如果我使用以下 js 代码,它会中断。浏览器保持完全空白,控制台错误消息状态:TypeError: r is undefined

在下面的代码中,两个地方的值都更改为 values1。这是唯一的变化。

async function getData() {
    const dataRequest = await fetch('https://storage.googleapis.com/tfjs-tutorials/carsData.json');
    const data = await dataRequest.json();
    const cleaned = data.map(car => ({
        mpg: car.Miles_per_Gallon,
        hp: car.Horsepower,
    }))
    .filter(car => (car.mpg != null && car.hp != null));

    return cleaned
}

async function run() {
    // Load and plot the original input data that we are going to train on.
    const data = await getData();
    const values1 = data.map(d => ({
      x: d.hp,
      y: d.mpg,
    }));

    tfvis.render.scatterplot(
      {name: 'Horsepower v MPG'},
      {values1}, 
      {
        xLabel: 'Horsepower',
        yLabel: 'MPG',
        height: 300
      }
    );

    // More code will be added below
  }

  document.addEventListener('DOMContentLoaded', run);

我希望上面的代码会产生一个与原始代码一样的情节,但我没有得到情节,而是一个 TypeError 。

标签: tensorflow.js

解决方案


values不是 js 关键字。它是对象的属性data,是scatterplot的参数。如果要将 更改const valuesvalues1,则必须执行以下操作:

tfvis.render.scatterplot(
      {name: 'Horsepower v MPG'},
      {values: values1}, 
      {
        xLabel: 'Horsepower',
        yLabel: 'MPG',
        height: 300
      }
    )

推荐阅读