首页 > 解决方案 > Tensorflow.js 预测不一致,返回 0 或按预期工作

问题描述

我正在尝试做一个简单的 Tensorflow.js 线性模型,但结果不一致。对于输入的任何输入值,它要么返回 0,要么按预期工作(例如,如果我为输入输入 11,它返回接近 110)。

当页面加载时,它要么工作要么不工作。如果我刷新页面 3 或 4 次,我可以让它工作。一旦它工作,它似乎继续工作。

我究竟做错了什么?

import {Component, OnInit} from '@angular/core';
import * as tf from '@tensorflow/tfjs';

@Component({
selector: 'app-linear-model',
templateUrl: './linear-model.component.html',
styleUrls: ['./linear-model.component.css']
})
export class LinearModelComponent implements OnInit {
title = 'Linear Model example';
linearModel: tf.Sequential;
prediction: any;

xData: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
yData: number[] = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];

constructor() {
}

ngOnInit() {
  this.trainNewModel();
}

async trainNewModel() {
  // this is based on the following tutorial:
  // https://angularfirebase.com/lessons/tensorflow-js-quick-start/#Step-2-Install-Tensorflow-js
  const learningRate = 0.01;
  const optimizerVar = tf.train.sgd(learningRate);

  // Define a model for linear regression.
  this.linearModel = tf.sequential();
  this.linearModel.add(tf.layers.dense({units: 1, inputShape: [1], activation: 'relu'}));

  // Prepare the model for training: Specify the loss and the optimizer.
  this.linearModel.compile({loss: 'meanSquaredError', optimizer: optimizerVar});

  // Training data defined at top
  const x = tf.tensor1d(this.xData);
  const y = tf.tensor1d(this.yData);

  // Train
  await this.linearModel.fit(x, y, {epochs: 10});
  console.log('model trained!');

}

predict(val) {
  val = parseFloat(val);
  const output = this.linearModel.predict(tf.tensor2d([val], [1, 1])) as any;
  this.prediction = Array.from(output.dataSync())[0];
  console.log(output.toString());
}

}

标签: tensorflow.js

解决方案


您的问题与密集层内核的随机初始化有关。给定权重和偏差的值,学习率可能会导致损失不减少。可以跟踪损失值,以及是否会降低学习率。

解决该问题的另一种方法是为密集层设置初始化矩阵。

this.linearModel.add(tf.layers.dense({units: 1, inputShape: [1], activation: 'relu', kernelInitializer:'ones'}

现场代码在这里


推荐阅读