Tensorflow.js的预测不一致,返回0或按预期工作

时间:2019-01-05 19:51:57

标签: tensorflow.js

我试图做一个简单的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());
}

}

1 个答案:

答案 0 :(得分:0)

您的问题与密集层内核的随机初始化有关。 给定权重的值和偏差,学习率可能导致损失没有减少。可以跟踪损失值,如果发生这种情况会降低学习率。

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

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

实时代码here