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

<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>

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值