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