2

我在更新聚合物页面上的视觉效果时遇到问题。我的元素如下所示:

import { html, LitElement, property } from 'lit-element';
import { connect } from 'pwa-helpers/connect-mixin.js';

// These are the shared styles needed by this element.
import { SharedStyles } from '../../styles/shared-styles.js';

// This element is connected to the Redux store.
import { store, RootState } from '../../store.js';

class TFJSItem extends connect(store)(LitElement) {
  @property({type: Number})
  private _prediction = 0;

  static styles = SharedStyles;

  protected render() {
    console.log(this._prediction);
    return html`
      <section>
        <h2>TFJS</h2>
        <p>${this._prediction}</p>
      </section>
    `;
  }

  // This is called every time something is updated in the store.
  stateChanged(state: RootState) {
    console.log(state.network!.prediction);
    this._prediction = state.network!.prediction;
  }
}

window.customElements.define('tfjs-item', TFJSItem);

我有一个运行 1000 次迭代的脚本,它向 redux 发送一个操作以更新存储在network.prediction. 但是,在最后一次状态更改发生后,元素中显示的数字只会更新一次。但是,由于我希望这是一个实时运行的数字,因此我希望记录每个更改。奇怪的是,console.log()每次更改都会执行第二个,但是,render 只调用一次。

数据来自 tfjs 训练过程。每次进行新的迭代时,我都想更新预测:

import * as tf from '@tensorflow/tfjs';
import * as d from './data';
import * as m from './model';

import { store } from '../store.js';
import { newPrediction } from '../actions/network.js';

export class Training {
  model: m.Model;
  data: d.Data;
  iterations: number;

  constructor(model: m.Model, data: d.Data) {
    this.model = model;
    this.model.model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
    this.data = data;
    this.iterations = 0;
  }

  start() {
    var this_ = this;
    if (this.iterations < 1000) {
      this.iterate();
    }
  }

  iterate() {
    this.iterations++;
    tf.tidy(() => {
      const prediction = this.model.model.predict(tf.tensor2d([5], [1, 1]) as tf.Tensor) as tf.Tensor<tf.Rank>;
      store.dispatch(newPrediction(prediction));
      this.model.model.trainOnBatch(this.data.xs, this.data.ys);
    });
  }
}
4

1 回答 1

2

LitElement 批量调用render()(实际上是整个更新管道)。预计如果您在单个任务中大量更新状态,则只会调用一次render().

通常更快的渲染实际上不会在屏幕上更频繁地显示任何内容,因为同步函数和微任务都会阻止绘制,所以浏览器只会在所有更新之后才绘制屏幕。

于 2019-03-17T23:47:01.337 回答