前端人工智能-身高体重预测

<script src="js/tf.js">
</script>
<script src="js/vis.js"></script>
<script>
    window.onload = async() => {
        const heights = [150, 160, 170];
        const weights = [40, 50, 60];

        tfvis.render.scatterplot({
            name: '身高体重训练数据'
        }, {
            values: heights.map((x, i) => ({
                x,
                y: weights[i]
            }))
        }, {
            xAxisDomain: [140, 180],
            yAxisDomain: [30, 70]
        });
        // 进行数据归一化
        const inputs = tf.tensor(heights).sub(150).div(20);
        const labels = tf.tensor(weights).sub(40).div(20);
        // 简历连续性模型
        const model = tf.sequential();
        // 添加全连接层
        model.add(tf.layers.dense({
            // 神经元个数
            units: 1,
            // 输入数据的形状
            inputShape: [1]
        }));
        // 设置损失函数和优化器
        model.compile({
            loss: tf.losses.meanSquaredError,
            // 随机梯度下降法
            optimizer: tf.train.sgd(0.1)
        });

        await model.fit(inputs, labels, {
            batchSize: 3, //批量数据
            epochs: 200,
            callbacks: tfvis.show.fitCallbacks({
                name: '训练过程'
            }, ['loss'])
        });

        const output = model.predict(tf.tensor([180]).sub(150).div(20));
        alert(`如果身高为 180cm,那么预测体重为 ${output.mul(20).add(40).dataSync()[0]}kg`);
    }
</script>

资源下载 https://download.csdn.net/download/liuhao9999/15865871

猜你喜欢

转载自blog.csdn.net/liuhao9999/article/details/114920515