|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2019 Google LLC. All Rights Reserved. |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * ============================================================================= |
| 16 | + */ |
| 17 | + |
| 18 | +import * as tf from '@tensorflow/tfjs'; |
| 19 | + |
| 20 | +const HOUSING_CSV_URL = 'https://storage.googleapis.com/learnjs-data/csv-datasets/california_housing_train_10k.csv'; |
| 21 | + |
| 22 | +export const featureColumns = [ |
| 23 | + 'longitude', 'latitude', 'housing_median_age', 'total_rooms', |
| 24 | + 'total_bedrooms', 'population', 'households', 'median_income']; |
| 25 | +const labelColumn = 'median_house_value'; |
| 26 | + |
| 27 | +/** |
| 28 | + * Calculate the column-by-column statistics of the housing CSV dataset. |
| 29 | + * |
| 30 | + * @return An object consisting of the following fields: |
| 31 | + * count {number} Number of data rows. |
| 32 | + * featureMeans {number[]} Each element is the arithmetic mean over all values |
| 33 | + * in a column. Ordered by the feature columns in the CSV dataset. |
| 34 | + * featureStddevs {number[]} Each element is the standard deviation over all |
| 35 | + * values in a column. Ordered by the columsn in the in the CSV dataset. |
| 36 | + * labelMean {number} The arithmetic mean of the label column. |
| 37 | + * labeStddev {number} The standard deviation of the albel column. |
| 38 | + */ |
| 39 | +export async function getDatasetStats() { |
| 40 | + const featureValues = {}; |
| 41 | + featureColumns.forEach(feature => { |
| 42 | + featureValues[feature] = []; |
| 43 | + }); |
| 44 | + const labelValues = []; |
| 45 | + |
| 46 | + const dataset = tf.data.csv(HOUSING_CSV_URL, { |
| 47 | + columnConfigs: { |
| 48 | + [labelColumn]: { |
| 49 | + isLabel: true |
| 50 | + } |
| 51 | + } |
| 52 | + }); |
| 53 | + const iterator = await dataset.iterator(); |
| 54 | + let count = 0; |
| 55 | + while (true) { |
| 56 | + const item = await iterator.next(); |
| 57 | + if (item.done) { |
| 58 | + break; |
| 59 | + } |
| 60 | + featureColumns.forEach(feature => { |
| 61 | + if (item.value.xs[feature] == null) { |
| 62 | + throw new Error(`item #{count} lacks feature ${feature}`); |
| 63 | + } |
| 64 | + featureValues[feature].push(item.value.xs[feature]); |
| 65 | + }); |
| 66 | + labelValues.push(item.value.ys[labelColumn]); |
| 67 | + count++; |
| 68 | + } |
| 69 | + |
| 70 | + return tf.tidy(() => { |
| 71 | + const featureMeans = {}; |
| 72 | + const featureStddevs = {}; |
| 73 | + featureColumns.forEach(feature => { |
| 74 | + const {mean, variance} = tf.moments(featureValues[feature]); |
| 75 | + featureMeans[feature] = mean.arraySync(); |
| 76 | + featureStddevs[feature] = tf.sqrt(variance).arraySync(); |
| 77 | + }); |
| 78 | + |
| 79 | + const moments = tf.moments(labelValues); |
| 80 | + const labelMean = moments.mean.arraySync(); |
| 81 | + const labelStddev = tf.sqrt(moments.variance).arraySync(); |
| 82 | + return { |
| 83 | + count, |
| 84 | + featureMeans, |
| 85 | + featureStddevs, |
| 86 | + labelMean, |
| 87 | + labelStddev |
| 88 | + }; |
| 89 | + }); |
| 90 | +} |
| 91 | + |
| 92 | +/** |
| 93 | + * Get a dataset with the features and label z-normalized, |
| 94 | + * the dataset is split into three xs-ys tensor pairs: for training, |
| 95 | + * validation and evaluation. |
| 96 | + * |
| 97 | + * @param {number} count Number of rows in the CSV dataset, computed beforehand. |
| 98 | + * @param {{[feature: string]: number}} featureMeans Arithmetic means of the |
| 99 | + * features. Use for normalization. |
| 100 | + * @param {[feature: string]: number} featureStddevs Standard deviations of the |
| 101 | + * features. Used for normalization. |
| 102 | + * @param {number} labelMean Arithmetic mean of the label. Used for |
| 103 | + * normalization. |
| 104 | + * @param {number} labelStddev Standard deviation of the label. Used for |
| 105 | + * normalization. |
| 106 | + * @param {number} validationSplit Validation spilt, must be >0 and <1. |
| 107 | + * @param {number} evaluationSplit Evaluation split, must be >0 and <1. |
| 108 | + * @returns An object consisting of the following keys: |
| 109 | + * trainXs {tf.Tensor} training feature tensor |
| 110 | + * trainYs {tf.Tensor} training label tensor |
| 111 | + * valXs {tf.Tensor} validation feature tensor |
| 112 | + * valYs {tf.Tensor} validation label tensor |
| 113 | + * evalXs {tf.Tensor} evaluation feature tensor |
| 114 | + * evalYs {tf.Tensor} evaluation label tensor. |
| 115 | + */ |
| 116 | +export async function getNormalizedDatasets( |
| 117 | + count, featureMeans, featureStddevs, labelMean, labelStddev, |
| 118 | + validationSplit, evaluationSplit) { |
| 119 | + tf.util.assert( |
| 120 | + validationSplit > 0 && validationSplit < 1, |
| 121 | + () => `validationSplit is expected to be >0 and <1, ` + |
| 122 | + `but got ${validationSplit}`); |
| 123 | + tf.util.assert( |
| 124 | + evaluationSplit > 0 && evaluationSplit < 1, |
| 125 | + () => `evaluationSplit is expected to be >0 and <1, ` + |
| 126 | + `but got ${evaluationSplit}`); |
| 127 | + tf.util.assert( |
| 128 | + validationSplit + evaluationSplit < 1, |
| 129 | + () => `The sum of validationSplit and evaluationSplit exceeds 1`); |
| 130 | + |
| 131 | + const dataset = tf.data.csv(HOUSING_CSV_URL, { |
| 132 | + columnConfigs: { |
| 133 | + [labelColumn]: { |
| 134 | + isLabel: true |
| 135 | + } |
| 136 | + } |
| 137 | + }); |
| 138 | + |
| 139 | + const featureValues = []; |
| 140 | + const labelValues = []; |
| 141 | + const indices = []; |
| 142 | + const iterator = await dataset.iterator(); |
| 143 | + for (let i = 0; i < count; ++i) { |
| 144 | + const {value, done} = await iterator.next(); |
| 145 | + if (done) { |
| 146 | + break; |
| 147 | + } |
| 148 | + featureColumns.map(feature => { |
| 149 | + featureValues.push( |
| 150 | + (value.xs[feature] - featureMeans[feature]) / |
| 151 | + featureStddevs[feature]); |
| 152 | + }); |
| 153 | + labelValues.push((value.ys[labelColumn] - labelMean) / labelStddev); |
| 154 | + indices.push(i); |
| 155 | + } |
| 156 | + |
| 157 | + const xs = tf.tensor2d(featureValues, [count, featureColumns.length]); |
| 158 | + const ys = tf.tensor2d(labelValues, [count, 1]); |
| 159 | + |
| 160 | + // Set random seed to fix shuffling order and therefore to fix the |
| 161 | + // training, validation, and evaluation splits. |
| 162 | + Math.seedrandom('1337'); |
| 163 | + tf.util.shuffle(indices); |
| 164 | + |
| 165 | + const numTrain = Math.round(count * (1 - validationSplit - evaluationSplit)); |
| 166 | + const numVal = Math.round(count * validationSplit); |
| 167 | + const trainXs = xs.gather(indices.slice(0, numTrain)); |
| 168 | + const trainYs = ys.gather(indices.slice(0, numTrain)); |
| 169 | + const valXs = xs.gather(indices.slice(numTrain, numTrain + numVal)); |
| 170 | + const valYs = ys.gather(indices.slice(numTrain, numTrain + numVal)); |
| 171 | + const evalXs = xs.gather(indices.slice(numTrain + numVal)); |
| 172 | + const evalYs = ys.gather(indices.slice(numTrain + numVal)); |
| 173 | + |
| 174 | + return {trainXs, trainYs, valXs, valYs, evalXs, evalYs}; |
| 175 | + |
| 176 | +} |
0 commit comments