From 8241125b4812f7d10bb7953969efa788fe1a897a Mon Sep 17 00:00:00 2001 From: Ziyuan Lin Date: Thu, 3 Oct 2024 10:46:23 -0400 Subject: [PATCH] handle min = max case during data normalization (#208) * handle min = max case * add warning message --- src/NeuralNetwork/NeuralNetworkData.js | 6 +++++- src/NeuralNetwork/NeuralNetworkUtils.js | 16 +++++++++++----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/NeuralNetwork/NeuralNetworkData.js b/src/NeuralNetwork/NeuralNetworkData.js index 77cdc35d..a4015233 100644 --- a/src/NeuralNetwork/NeuralNetworkData.js +++ b/src/NeuralNetwork/NeuralNetworkData.js @@ -284,7 +284,6 @@ class NeuralNetworkData { const dataLength = dataRaw.length; // the copy of the inputs.meta[inputOrOutput] const inputMeta = Object.assign({}, inputOrOutputMeta); - // normalized output object const normalized = {}; Object.keys(inputMeta).forEach((k) => { @@ -343,6 +342,11 @@ class NeuralNetworkData { return normalized; } + if (min === max) { + console.warn( + "🟪 ml5.js NeuralNetwork warns: Normalization failed, all data entries for an input parameter are identical (min === max). The data for this input parameter will be set to 0, effectively removing it from the model. Please check your input data." + ); + } // if the dtype is a number if (inputArray.every((v) => typeof v === "number")) { const normalized = inputArray.map((v) => diff --git a/src/NeuralNetwork/NeuralNetworkUtils.js b/src/NeuralNetwork/NeuralNetworkUtils.js index 227d841b..f9c12a25 100644 --- a/src/NeuralNetwork/NeuralNetworkUtils.js +++ b/src/NeuralNetwork/NeuralNetworkUtils.js @@ -4,13 +4,16 @@ class NeuralNetworkUtils { } /** - * normalizeValue - * @param {*} value - * @param {*} min - * @param {*} max + * Normalize a value between min and max, return 0 if min === max + * @param {number} value - The value to normalize + * @param {number} min - The minimum bound + * @param {number} max - The maximum bound */ - // eslint-disable-next-line class-methods-use-this normalizeValue(value, min, max) { + // When min is equal to max, set everything to 0 + if (min === max) { + return 0; + } return (value - min) / (max - min); } @@ -22,6 +25,9 @@ class NeuralNetworkUtils { */ // eslint-disable-next-line class-methods-use-this unnormalizeValue(value, min, max) { + if (min === max) { + return min; + } return value * (max - min) + min; }