1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import * as tf from "@tensorflow/tfjs"; import * as tfvis from "@tensorflow/tfjs-vis";
window.onload = async () => { const xs = [1, 2, 3, 4]; //input const ys = [1, 3, 5, 7]; //output
tfvis.render.scatterplot( { name: "线性回归训练数据" }, { values: xs.map((x, i) => ({x, y:ys[i]})) }, {xAxisDomain:[0,5],yAxisDomain:[0,9]} );
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)}); //设置:损失函数为均方误差MSE,优化器为随机梯度下降SGD,学习速率为0.1,学习率是一个需要调整优化的超参数
const inputs = tf.tensor(xs); const labels = tf.tensor(ys);
await model.fit(inputs, labels,{ batchSize: 4, //批量训练的数据集大小(超参数,需要不断调整试验) epochs:100, //迭代实验次数(超参数,需要不断调整试验) callbacks:tfvis.show.fitCallbacks( {name:'训练过程'}, ['loss'], ) });
};
|