tensorflow.js - 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'}
现场代码在这里
推荐阅读
- java - 如何将此 Java 代码转换为 Lambda 和 Stream 实现?
- python - mac catalina pip 无法安装 numpy (zsh)
- c++ - 需要帮助在 C++ 中创建类 Counter
- json - 我可以在 WSO2 中使用列名作为 json 键吗?
- java - Java 泛型 - 带有有限大小列表的映射
- reactjs - 在我的 TextInput 上更新我的 defaultValue 的值
- javascript - JavaScript 在编辑时显示字段的 varchar 描述
- android - 启用 TabLayout 不会启用 onTouchEvents - 选项卡不可点击
- containers - 关于容器的 AWS Marketplace Metering 服务
- python - 为什么占位符在张量流中不起作用?