tensorflow.js基本使用 线性回归(一)

2022/6/29 23:20:26

本文主要是介绍tensorflow.js基本使用 线性回归(一),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

根据身高推测体重

const $ = require('jquery');
const tf = require('@tensorflow/tfjs');
const tfvis = require('@tensorflow/tfjs-vis');

/* 根据身高推测体重 */

//把数据处理成符合模型要求的格式
function getData() {
//学习数据
const heights = [150, 151, 160, 161, 166, 170, 177, 180, 183, 190, 196];
const weights = [45, 43, 50, 61, 68, 60, 70, 70, 65, 89, 98];

//验证数据
const testh = [183, 160, 151, 166, 183, 177, 170];
const testw = [67, 61, 43, 67, 80, 77, 70];

//归一化数据
const inputs = tf.tensor(heights).sub(150).div(50);
const labels = tf.tensor(weights).sub(40).div(60);

const xs = tf.tensor(testh).sub(150).div(50);
const ys = tf.tensor(testw).sub(40).div(60);

//绘制图表
tfvis.render.scatterplot(
{ name: '身高体重' },
//x轴身高,y轴体重
{ values: heights.map((x, i) => ({ x, y: weights[i] })) },
//设置x轴范围,设置y轴范围
{ xAxisDomain: [140, 200], yAxisDomain: [40, 110] }
);

return { inputs, labels, xs, ys };
}


$(async () => {
const { inputs, labels, xs, ys } = getData();

//设置连续模型
const model = tf.sequential();

//设置全连接层
model.add(tf.layers.dense({
units: 10,
inputShape: [1]
}));

model.add(tf.layers.dense({
units: 1
}));

//设置损失函数,优化函数学习速率为0.1
model.compile({
loss: tf.losses.meanSquaredError,
optimizer: tf.train.adam(0.1)
});

await model.fit(inputs, labels, {
batchSize: 1,
epochs: 20,
//设置验证集
validationData: [xs, ys],
callbacks: tfvis.show.fitCallbacks(
{ name: '训练过程' },
['loss', 'val_loss', 'acc', 'val_acc'],
{ callbacks: ['onEpochEnd'] }
)
});

//对身高180的体重进行推测
let res = model.predict(tf.tensor([180]).sub(150).div(50));
console.log(res.mul(60).add(40).dataSync()[0]);

//保存模型
window.download = async () => {
await model.save('downloads://my-model');
}
});
html部分

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="download()">保存模型</button>
</body>
<script src="./t1.js"></script>
</html>
运行结果

 

 


————————————————
版权声明:本文为CSDN博主「(; ̄ェ ̄)。」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_35496811/article/details/122527040



这篇关于tensorflow.js基本使用 线性回归(一)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程