线性回归测试

<script src="js/tf.js">
</script>
<script src="js/vis.js"></script>
<script>
    window.onload = async() => {
        const xs = [1, 2, 3, 4];
        const ys = [1, 3, 5, 7];
        // 可视化
        tfvis.render.scatterplot({
            name: '线性回归训练集'
        }, {
            values: xs.map((x, i) => ({
                x,
                y: ys[i]
            }))
        }, {
            xAxisDomain: [0, 5],
            yAxisDomain: [0, 8]
        });
        // 创建连续的模型
        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) //优化器-随机梯度下降
        });
        // 训练模型
        // 将训练数据转为tensor
        const inputs = tf.tensor(xs);
        const labels = tf.tensor(ys);
        // 拟合方法来训练
        /*
        *
        inputs:输入
        labels:正确的值

        */
        await model.fit(inputs, labels, {
            batchSize: 4, //小批量 每次模型需要训练的数据量有多大
            epochs: 200, //迭代整个训练数据的次数
            callbacks: tfvis.show.fitCallbacks({
                    name: '训练过程'
                }, ['loss'] //度量单位  指定要看啥   loss损失函数
            )
        });
        // 将待预测测数据转换为tensor
        // 预测数据
        const output = model.predict(tf.tensor([5]));
        alert(`如果 x 为 5,那么预测 y 为 ${output.dataSync()[0]}`);
    };
</script>

 

posted @ 2020-11-17 17:04  刘浩2561179983  阅读(162)  评论(0编辑  收藏  举报