Getting Started with TensorFlow.js
2024-09-28 06:06:12
使用TensorFlow.js,您不仅可以在浏览器中运行深度学习模型进行推理,你还能够训练它们。在这个简单的样例中,将展示一个相当于“Hello World”的示例。
1、引入TensorFlow.js
使用CDN上的文件,你就可以使用TensorFlow APIs。
<html>
<head>
<!-- Load TensorFlow.js -->
<!-- Get latest version at https://github.com/tensorflow/tfjs -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.2"> </script>
这里使用的版本是 0.11.2,你可以去github上找最新的。
2、创建一个简单的神经网络
由于这只有一个输入值和输出值,因此它可以是单个节点。在JavaScript中,我们可以创建一个tf.sequential,并向其添加layers。
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
我们还需要指定损失函数和优化器:
model.compile({
loss: 'meanSquaredError',
optimizer: 'sgd'
});
为了训练模型,我们需要数据集来训练模型。构造几个符合Y=2X-1的点,那么当X取[-1, 0, 1, 2, 3],Y取[-3, -1, 1, 3, 5]
const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);
调用fit函数进行训练,传入X和Y并指定训练轮数。请注意,只是异步的,在进入下一步之前必须等待返回值,所以这些代码都要写在一个async函数中。
await model.fit(xs, ys, {epochs: 500});
最后传入一个值进行预测。
完整的代码如下:
<html> <head>
<!-- Load TensorFlow.js -->
<!-- Get latest version at https://github.com/tensorflow/tfjs -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.2">
</script>
</head> <body>
<div id="output_field"></div>
</body> <script>
async function learnLinear(){ const model = tf.sequential();
model.add(tf.layers.dense({
units: 1,
inputShape: [1]
})); model.compile({
loss: 'meanSquaredError',
optimizer: 'sgd'
}); const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]); await model.fit(xs, ys, {epochs: 100}); document.getElementById('output_field').innerText =
model.predict( tf.tensor2d([10], [1, 1]) );
} learnLinear();
</script> <html>
参考链接:
1. https://medium.com/tensorflow/getting-started-with-tensorflow-js-50f6783489b2
2.https://blog.csdn.net/aliceyangxi1987/article/details/80743590
最新文章
- BPM配置故事之案例14-数据字典与数据联动
- python学习之路 第四天
- oracle 字符串
- PHPExcel(1.8.0) 帮助代码
- WCF的传输安全(读书笔记)
- SQL函数学习(十九):CAST()函数和CONVERT()函数
- RMI
- sqlsevrer中output的用法
- 浅谈Linux的内存管理机制
- SDK 组件 Qupaisdk 启动出错,错误消息为 [Qupaisdk], the android stack error message is Fail to start the plugin, which is caused by Failed resolution of: Lcom/duanqu/qupai/recorder/R$array;
- async 函数
- MyBatis系列目录--5. MyBatis一级缓存和二级缓存(redis实现)
- echarts堆叠图添加总量
- MT【229】最小值函数
- 在eclipse中启动项目报java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: PermGen space
- spring cloud Feign 使用 @RequestLine 注解遇到的问题
- Python提取MD5
- 【PyQt5 学习记录】011:使用 QListWidet 创建列表
- 转载:python的编码处理(一)
- 026.2 网络编程 UDP聊天
热门文章
- 【BZOJ4556】[TJOI2016&;HEOI2016] 字符串(后缀自动机+线段树合并+二分)
- Excel日历控件实现下拉选取日期含VB代码实现
- docker Dockerfile实战
- git 邮箱错误-git log 中发现 XXX@163.com邮箱不符合要求,请务必使用公司邮箱。
- 入门理解mysql-binlog
- Jvisualvm简单使用教程
- pymysql 读取大数据内存卡死的解决方案
- Chrome教程之使用Chrome DevTools命令菜单运行命令
- Spring源码系列 — BeanDefinition
- OpenGL入门1.3:着色器 GLSL