前端学算法:通过tensorflow.js来推导出等差数列公式

65 阅读1分钟
<template>
  <div class="container">
    <div class="cal-container">
      <div>
      计算结果:{{ result }}
    </div>
    <div>
      次数:{{ calculateNum }}
    </div>
    <button @click="train">计算</button>
    <!-- <div class="box"></div> -->
    </div>
  </div>
</template>

<script>
//@tensorflow/tfjs中文官网:https://tensorflow.google.cn/?hl=zh-cn
import * as tf from '@tensorflow/tfjs'
  export default {
    data() {
      return {
        result: null,//计算结果
        model: tf.sequential(),//初始化深度学习模式
        xs: null,
        ys:null,
        calculateNum:0,
      }
    },
    methods: {
      // 提前计算参数
      preCalculate() {
        this.model.add(tf.layers.dense({units: 1, inputShape: [1]}))
        this.model.compile({loss: 'meanSquaredError', optimizer: 'sgd'})
        //这里是定义x轴的计算顺序
        this.xs = tf.tensor2d([1, 2, 3, 4], [4, 1])
        //这里是输出参数
        this.ys = tf.tensor2d([1, 3, 5, 7], [4, 1])
        //xs和ys两个变量在当前计算中表达的实际意义是:xs是代表计算次数,
        //结合当前xs和ys的数据:xs中的第1次计算结果是1,第2次是3,第3次是5,第4次是7,那么由此可知第5次是9
        //模型会根据提前设置的维度层级进行计算,计算次数越多,越准确,如下图所示,计算次数达到2000次,那么计算结果是8.99,那就是说无限接近9
      },
      async train(){
        await this.preCalculate()
        for(let index = 0; index <= 10000; index++){
          this.calculateNum = index
          await this.model.fit(this.xs, this.ys, {eopchs: 10})
          this.result = this.model.predict(tf.tensor2d([5], [1, 1]))
        }
      }
    },
  }
</script>

image.png