## 相关概念

### TFJS

WebGL ：浏览器平台中的3D绘图标准，用来实现张量的存储和数学操作。

## HOW（方法、措施）​

#### ​一、创建模型

```function createModel(numOfFeatures) {

const model = tf.sequential();

model.add(tf.layers.dense({ inputShape: [numOfFeatures], units: 1 }));

return model;
}```

#### 二、准备数据，将数据转换为张量

```function convertToTensor(data) {
return tf.tidy(() => {

const inputs = data.x;

const labels = data.y;

const inputTensor = tf.tensor2d(inputs);
const labelTensor = tf.tensor2d(labels, [labels.length, 1]);

const inputMax = inputTensor.max();
const inputMin = inputTensor.min();
const labelMax = labelTensor.max();
const labelMin = labelTensor.min();
const normalizedInputs = inputTensor
.sub(inputMin)
.div(inputMax.sub(inputMin));
const normalizedLabels = labelTensor
.sub(labelMin)
.div(labelMax.sub(labelMin));
return {
inputs: normalizedInputs,
labels: normalizedLabels,
inputMax,
inputMin,
labelMax,
labelMin,
};
});
}```

#### 三、训练模型

```function trainModel(model, inputs, labels) {
return new Promise((resolve, reject) => {
model.compile({
optimizer: 'sgd',
loss: 'meanAbsoluteError',
metrics: ['mse'],
});
const batchSize = 32;
const epochs = 200;
return model
.fit(inputs, labels, {
batchSize,
epochs,
callbacks: { onEpochEnd: (epoch, logs) => console.log(logs) },
})
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}```

#### 四、预测

```function predict(model, inputData, normalizationData) {
const { inputMax, inputMin, labelMin, labelMax } = normalizationData;
const arr = tf.tidy(() => {

const xs = tf.linspace(0, 1, 100);

const preds = model.predict(xs.reshape([100, 1]));

return [unNormXs.dataSync(), unNormPreds.dataSync()];
});
const xs = arr[0];
const preds = arr[1];
const predictedPoints = Array.from(xs).map((val, i) => {
return { x: val, y: preds[i] };
});
const originalPoints = inputData.map(d => ({
x: d.x,
y: d.y,
}));
return {
predictedPoints,
originalPoints,
};
}```

## WHAT（现象、成果）

### 均方误差

```function evaluate(inputs, labels) {
const result = labels.sub(inputs).pow([2]).mean();
result.print();
return result;
}```