ionic3+tensorflow深度学习

2018年3月31 日举行的 2018 TensorFlow 开发者峰会上,TensorFlow 宣布重大更新:增加支持 JavaScript,并推出开源库 TensorFlow.js,用户可以完全在浏览器定义、训练和运行机器学习模型。

我们就做一个ionic3+tensorflow的小demo运行结果如下:


步骤如下:

1:运行命令npm install @tensorflow/tfjs 来下载tensrflowjs


2:在相应的ts文件中加入如下代码来引入tf

import * as tf from '@tensorflow/tfjs';

3:在相应的ts文件中加入demo代码,我这边对应是home.ts

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

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

  // Generate some synthetic data for training.
  const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
  const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);


  // Train the model using the data.
  model.fit(xs, ys).then(() => {
    // Use the model to do inference on a data point the model hasn't seen before:
    console.log(model.predict(tf.tensor2d([5], [1, 1])));
    this.message = model.predict(tf.tensor2d([[5]], [1, 1])).toString()
  });
}

这样就可以实现对tfjs的简单应用了!!


完整ts代码如下:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import * as tf from '@tensorflow/tfjs';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage{

  message:any = ''

  constructor(public navCtrl: NavController) {

  }

  public tensorflowjs(){

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

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

    // Generate some synthetic data for training.
    const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
    const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);


    // Train the model using the data.
    model.fit(xs, ys).then(() => {
      // Use the model to do inference on a data point the model hasn't seen before:
      console.log(model.predict(tf.tensor2d([5], [1, 1])));
      this.message = model.predict(tf.tensor2d([[5]], [1, 1])).toString()
    });
  }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值