| 18 | import * as tf from '@tensorflow/tfjs'; |
| 19 | |
| 20 | export function generateData(numPoints, coeff, sigma = 0.04) { |
| 21 | return tf.tidy(() => { |
| 22 | const [a, b, c, d] = [ |
| 23 | tf.scalar(coeff.a), tf.scalar(coeff.b), tf.scalar(coeff.c), |
| 24 | tf.scalar(coeff.d) |
| 25 | ]; |
| 26 | |
| 27 | const xs = tf.randomUniform([numPoints], -1, 1); |
| 28 | |
| 29 | // Generate polynomial data |
| 30 | const three = tf.scalar(3, 'int32'); |
| 31 | const ys = a.mul(xs.pow(three)) |
| 32 | .add(b.mul(xs.square())) |
| 33 | .add(c.mul(xs)) |
| 34 | .add(d) |
| 35 | // Add random noise to the generated data |
| 36 | // to make the problem a bit more interesting |
| 37 | .add(tf.randomNormal([numPoints], 0, sigma)); |
| 38 | |
| 39 | // Normalize the y values to the range 0 to 1. |
| 40 | const ymin = ys.min(); |
| 41 | const ymax = ys.max(); |
| 42 | const yrange = ymax.sub(ymin); |
| 43 | const ysNormalized = ys.sub(ymin).div(yrange); |
| 44 | |
| 45 | return { |
| 46 | xs, |
| 47 | ys: ysNormalized |
| 48 | }; |
| 49 | }) |
| 50 | } |