* Convert Iris data arrays to `tf.Tensor`s. * * @param data The Iris input feature data, an `Array` of `Array`s, each element * of which is assumed to be a length-4 `Array` (for petal length, petal * width, sepal length, sepal width). * @param targets An `Array` of numbers, with values from
(data, targets, testSplit)
| 94 | * - test one-hot labels as a `tf.Tensor` of shape [numTestExamples, 3] |
| 95 | */ |
| 96 | function convertToTensors(data, targets, testSplit) { |
| 97 | const numExamples = data.length; |
| 98 | if (numExamples !== targets.length) { |
| 99 | throw new Error('data and split have different numbers of examples'); |
| 100 | } |
| 101 | |
| 102 | // Randomly shuffle `data` and `targets`. |
| 103 | const indices = []; |
| 104 | for (let i = 0; i < numExamples; ++i) { |
| 105 | indices.push(i); |
| 106 | } |
| 107 | tf.util.shuffle(indices); |
| 108 | |
| 109 | const shuffledData = []; |
| 110 | const shuffledTargets = []; |
| 111 | for (let i = 0; i < numExamples; ++i) { |
| 112 | shuffledData.push(data[indices[i]]); |
| 113 | shuffledTargets.push(targets[indices[i]]); |
| 114 | } |
| 115 | |
| 116 | // Split the data into a training set and a tet set, based on `testSplit`. |
| 117 | const numTestExamples = Math.round(numExamples * testSplit); |
| 118 | const numTrainExamples = numExamples - numTestExamples; |
| 119 | |
| 120 | const xDims = shuffledData[0].length; |
| 121 | |
| 122 | // Create a 2D `tf.Tensor` to hold the feature data. |
| 123 | const xs = tf.tensor2d(shuffledData, [numExamples, xDims]); |
| 124 | |
| 125 | // Create a 1D `tf.Tensor` to hold the labels, and convert the number label |
| 126 | // from the set {0, 1, 2} into one-hot encoding (.e.g., 0 --> [1, 0, 0]). |
| 127 | const ys = tf.oneHot(tf.tensor1d(shuffledTargets).toInt(), IRIS_NUM_CLASSES); |
| 128 | |
| 129 | // Split the data into training and test sets, using `slice`. |
| 130 | const xTrain = xs.slice([0, 0], [numTrainExamples, xDims]); |
| 131 | const xTest = xs.slice([numTrainExamples, 0], [numTestExamples, xDims]); |
| 132 | const yTrain = ys.slice([0, 0], [numTrainExamples, IRIS_NUM_CLASSES]); |
| 133 | const yTest = ys.slice([0, 0], [numTestExamples, IRIS_NUM_CLASSES]); |
| 134 | return [xTrain, yTrain, xTest, yTest]; |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * Obtains Iris data, split into training and test sets. |