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());
}

}

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

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

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

实时代码在这里

最新更新