zl程序教程

您现在的位置是:首页 >  后端

当前栏目

在浏览器中运行 TensorFlow.js 来训练模型并给出预测结果(Iris 数据集)

JS训练浏览器数据 模型 运行 结果 预测
2023-09-11 14:14:13 时间

https://blog.csdn.net/myDarling_/article/details/128153714

 

<html>
<head></head>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>
    <script lang="js">
        async function doTraining(model){
            const history = 
                  await model.fit(xs, ys,
                                  {epochs: 500,
                                   callbacks: {
                                       onEpochEnd: async(epoch, logs) =>{
                                           console.log("Epoch:"
                                                       + epoch
                                                       + " Loss:"
                                                       + logs.loss);
                                       }
                                   }});
        }
        
        const model = tf.sequential();
        model.add(tf.layers.dense({units: 1, inputShape: [1]}));
        model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); 
        model.summary();
        
        const xs = tf.tensor2d([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], [6, 1]);
        const ys = tf.tensor2d([-3.0, -1.0, 2.0, 3.0, 5.0, 7.0], [6, 1]);
        
        
        doTraining(model).then(() => {
            alert(model.predict(tf.tensor2d([10], [1, 1])));
        });
    </script>>
<body>
    <h1>First HTML Page</h1>
</body>
</html>