美文网首页
Introduction to TensorFlow for A

Introduction to TensorFlow for A

作者: 学术界末流打工人 | 来源:发表于2020-04-08 21:13 被阅读0次

Week1

Building the model

导入tensorflow:

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>

定义模型:

<script lang="js">
    // 表示定义将按照一系列顺序进行操作,我们说我们的模型是按顺序定义的
    const model = tf.sequential();

    // 我们的模型是一层的,所以我们添加了一个dense,这个dense只有一个神经元
    model.add(tf.layers.dense({units:1,inputShape:[1]}))

    // 定义损失函数为均方误差, 定义随机梯度下降
    model.compile({loss:'meanSquaredError',optimizer:'sgd'})

    // 输出结构的summary
    model.summary();
</script>

定义训练函数并调用

<script lang="js">

    async function doTraining(model){
        const history =
            // fit x 和 y,js的异步操作,等待结果
            await model.fit(
                xs,ys,
                {epochs:500,
                    callback:{
                        onEpochEnd: async(epoch,logs) =>{
                            console.log("Epoch:" + epoch + "Loss:"+logs.loss)
                        }
                    }}
            )
    }
    
    // 表示定义将按照一系列顺序进行操作,我们说我们的模型是按顺序定义的
    const model = tf.sequential();

    // 我们的模型是一层的,所以我们添加了一个dense,这个dense只有一个神经元
    model.add(tf.layers.dense({units:1,inputShape:[1]}))

    // 定义损失函数为均方误差, 定义随机梯度下降
    model.compile({loss:'meanSquaredError',optimizer:'sgd'})

    // 输出结构的summary
    model.summary();


    async function doTraining(model){
        const history =
                // fit x 和 y,js的异步操作,等待结果
                await model.fit(
                    xs,ys,
                    {epochs:500,
                     callback:{
                        onEpochEnd: async(epoch,logs) =>{
                            console.log("Epoch:" + epoch + "Loss:"+logs.loss)
                        }
                     }}
                )
    }


    // doTraining是一个异步方法
    doTraining(model).then(()=>{
        // 用alert进行callback
        alert(model.predict(tf.tensor2d([10],[1,1])))
    })
</script>

相关文章

网友评论

      本文标题:Introduction to TensorFlow for A

      本文链接:https://www.haomeiwen.com/subject/wysxmhtx.html