| 22 | |
| 23 | // Tiny TFJS train / predict example. |
| 24 | async function run() { |
| 25 | // Create a simple model. |
| 26 | const model = tf.sequential(); |
| 27 | model.add(tf.layers.dense({units: 1, inputShape: [1]})); |
| 28 | |
| 29 | // Prepare the model for training: Specify the loss and the optimizer. |
| 30 | model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); |
| 31 | |
| 32 | // Generate some synthetic data for training. (y = 2x - 1) |
| 33 | const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]); |
| 34 | const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]); |
| 35 | |
| 36 | // Train the model using the data. |
| 37 | await model.fit(xs, ys, {epochs: 250}); |
| 38 | |
| 39 | // Use the model to do inference on a data point the model hasn't seen. |
| 40 | // Should print approximately 39. |
| 41 | document.getElementById('micro-out-div').innerText = |
| 42 | model.predict(tf.tensor2d([20], [1, 1])).dataSync(); |
| 43 | } |
| 44 | |
| 45 | run(); |