This is the 20th day of my participation in the Genwen Challenge

Now that the model has been defined, the data has been downloaded and processed, everything is ready to start training.

async function trainModel(model, inputs, labels) {
  // Prepare the model to train
  model.compile({
    optimizer: tf.train.adam(),
    loss: tf.losses.meanSquaredError,
    metrics: ['mse']});const batchSize = 32;
  const epochs = 50;

  return await model.fit(inputs, labels, {
    batchSize,
    epochs,
    shuffle: true.callbacks: tfvis.show.fitCallbacks(
      { name: 'Training Performance'},'loss'.'mse'] and {height: 200.callbacks: ['onEpochEnd']})}); }Copy the code

Some preparation before training

model.compile({
  optimizer: tf.train.adam(),
  loss: tf.losses.meanSquaredError,
  metrics: ['mse'],
});
Copy the code

Before you can train a model, you need to “compile” it, so how do you do that? We need an optimization and a loss function, the loss function can also understand the objective function, which is basically specifying the training, let’s train a target, optimizer which is giving a strategy for how to update parameters during training.

  • The optimizer. It’s an algorithm, it’s an algorithm for updating parameters. There are many optimizers available in tensorflow.js. The Adam optimizer was chosen here, but you can also try other optimizers
  • Loss function: Essentially a function that tells the model how well it performs in each batch (subset of data) during the learning process. MeanSquaredError is selected here to compare the model’s prediction with the true value
const batchSize = 32;
const epochs = 50;
Copy the code

Set the batchSize and the number of epochs.

  • BatchSize refers to the size of the subset of data that the model sees during each iteration of training. Common batch sizes range from 32 to 512. Batch size has an effect on training speed

  • Epochs completes the entire data set for training times

Start training

return await model.fit(inputs, labels, {
  batchSize,
  epochs,
  callbacks: tfvis.show.fitCallbacks(
    { name: 'Training Performance'},'loss'.'mse'] and {height: 200.callbacks: ['onEpochEnd']})});Copy the code

Model.fit is the function to start the training. This is an asynchronous function, so the return will be a promise.

In order to monitor the training progress, the callback function is used as model.fit to get the information during the training. The callback function is then defined using tfvis.show.fitCallbacks, which can then draw the loss value for the iteration icon

const tensorData = convertToTensor(data);
const {inputs, labels} = tensorData;

// Train the model
await trainModel(model, inputs, labels);
console.log('Done Training');
Copy the code

Note that this part of the code is written in the run function, as follows

async function run() {
    // Load data
    const data = await getData();
    // Process raw data. Map the data setup to X and the MPG to Y
    const values = data.map(d= > ({
      x: d.horsepower,
      y: d.mpg,
    }));
    // Display the data as a scatter chart in the developer debug tool
    
  
    tfvis.render.scatterplot(
      {name: 'Horsepower v MPG'},
      {values},
      {
        xLabel: 'Horsepower'.yLabel: 'MPG'.height: 300});const model = createModel();
    const tensorData = convertToTensor(data);
    const {inputs, labels} = tensorData;

    // Train the model
    await trainModel(model, inputs, labels);
    console.log('Done Training');
}
Copy the code