TensorFlow图像识别代码优化需求:仅展示置信度最高的分类结果
Show Only the Top Confidence Prediction in TensorFlow.js
Alright, let's tweak your code so it only displays the prediction with the highest confidence instead of all results. Here's the adjusted version of your predict function:
async function predict() { // predict can take an image, video, or canvas HTML element const prediction = await model.predict(webcam.canvas); // Find the prediction with the highest confidence const topPrediction = prediction.reduce((highest, current) => { return current.probability > highest.probability ? current : highest; }, prediction[0]); // Format the result text const classPrediction = `${topPrediction.className}: ${topPrediction.probability.toFixed(2)}`; // Update the label container to only show the top result // Clear all old content first labelContainer.innerHTML = ''; // Create a new element for the top result and add it to the container const resultDiv = document.createElement('div'); resultDiv.textContent = classPrediction; labelContainer.appendChild(resultDiv); // Alternative: If your labelContainer has fixed pre-existing child nodes // labelContainer.childNodes.forEach(node => node.innerHTML = ''); // labelContainer.childNodes[0].innerHTML = classPrediction; }
Breakdown of the changes:
- Finding the top prediction: We use the
reducemethod to loop through all predictions and keep track of the one with the highestprobabilityvalue. This is a concise alternative to writing a manual for-loop, though either approach works. - Updating the UI: Instead of looping through all
maxPredictionsto update every child node, we clear the container first to remove old results, then add a new element with just the top prediction. If your HTML has a fixed set of result elements, you can use the commented alternative to only populate the first node and clear the rest.
This way, your camera feed will only show the most confident recognition result each time the predict function runs.
内容的提问来源于stack exchange,提问作者mmarchjr
相关产品推荐
相关产品推荐

