When a model is trained, the data is divided into small sets (batches). Each batch is then fed to the model. Shuffling is important to prevent the model getting the same data over again. If using the same data twice, the model will not be able to generalize the data and give the right output. Shuffling gives a better variety of data in each batch.
tf.util.shuffle(data);
To use TensorFlow, input data needs to be converted to tensor data:
// Map x values to Tensor inputs
const inputs = values.map(obj => obj.x);
// Map y values to Tensor labels
const labels = values.map(obj => obj.y);
// Convert inputs and labels to 2d tensors
const inputTensor = tf.tensor2d(inputs, [inputs.length, 1]);
const labelTensor = tf.tensor2d(labels, [labels.length, 1]);
Data should be normalized before being used in a neural network.
A range of 0 - 1 using min-max are often best for numerical data:
const inputMin = inputTensor.min();
const inputMax = inputTensor.max();
const labelMin = labelTensor.min();
const labelMax = labelTensor.max();
const nmInputs = inputTensor.sub(inputMin).div(inputMax.sub(inputMin));
const nmLabels = labelTensor.sub(labelMin).div(labelMax.sub(labelMin));
A Machine Learning Model is an algorithm that produces output from input.
This example uses 3 lines to define a ML Model:
const model = tf.sequential();
model.add(tf.layers.dense({inputShape: [1], units: 1, useBias: true}));
model.add(tf.layers.dense({units: 1, useBias: true}));
const model = tf.sequential(); creates a Sequential ML Model.
In a sequential model, the input flows directly to the output. Other models can have multiple inputs and multiple outputs. Sequential is the easiest ML model. It allows you to build a model layer by layer, with weights that correspond to the next layer.
model.add() is used to add two layers to the model.
tf.layer.dense is a layer type that works in most cases. It multiplies its inputs by a weight-matrix and adds a number (bias) to the result.
inputShape: [1] because we have 1 input (x = rooms).
units: 1 defines the size of the weight matrix: 1 weight for each input (x value).
Compile the model with a specified optimizer and loss function:
model.compile({loss: 'meanSquaredError', optimizer:'sgd'});
The compiler is set to use the sgd optimizer. It is simple to use and quite effective.
meanSquaredError is the function we want to use to compare model predictions and true values.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!