ultralytics / yolov5

YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
50.79k stars 16.36k forks source link

Class scores from TFlite model's output data don't add up to 1 #13064

Closed Rishivarshil closed 3 months ago

Rishivarshil commented 5 months ago

Search before asking

Question

Hi, I have successfully trained a custom model based on YOLOv5s and converted the model to TFlite.

I get this as output: name: StatefulPartitionedCall:0 tensor: float32[1,10647,15]

In this output array, I expect the column names to be [xywh, conf, class0, class1, class2, class3, class4, class5, class6, class7, class8, class9]. Here is a sample of the output array: [0.0099678915, 0.02021235, 0.048227567, 0.11275095, 0.0020225942, 0.10732424, 0.048576027, 0.18665865, 0.07772142, 0.020257145, 0.13898787, 0.039612412, 0.074305505, 0.05975789, 0.008609295]

If you look at just the class scores, they don't add up to 1, so there is some issue here. Here is the relevant code:

/**
     * Writes Image data into a {@code ByteBuffer}.
     */
    protected ByteBuffer convertBitmapToByteBuffer(Bitmap bitmap) {
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * BATCH_SIZE * INPUT_SIZE * INPUT_SIZE * PIXEL_SIZE);
        byteBuffer.order(ByteOrder.nativeOrder());
        int[] intValues = new int[INPUT_SIZE * INPUT_SIZE];
        bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
        int pixel = 0;
        if(imgData != null){
            imgData.rewind();
        }
        for (int i = 0; i < INPUT_SIZE; ++i) {
            for (int j = 0; j < INPUT_SIZE; ++j) {
                int pixelValue = intValues[i * INPUT_SIZE + j];
                if (isModelQuantized) {
                    // Quantized model
                    imgData.putFloat(((pixelValue >> 16) & 0xFF) / 255.0f);
                    imgData.putFloat(((pixelValue >> 8) & 0xFF) / 255.0f);
                    imgData.putFloat((pixelValue & 0xFF) / 255.0f);
                } else { // Float model
                    imgData.putFloat((((pixelValue >> 16) & 0xFF)- IMAGE_MEAN) / IMAGE_STD); //image_mean = 0f and image_std = 255f
                    imgData.putFloat((((pixelValue >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD);
                    imgData.putFloat(((pixelValue & 0xFF) - IMAGE_MEAN) / IMAGE_STD);
                }
            }
        }
        return imgData;
    }
public ArrayList<Recognition> recognizeImage(Bitmap bitmap) {
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, INPUT_SIZE, INPUT_SIZE, true);
    ByteBuffer byteBuffer_ = convertBitmapToByteBuffer(resizedBitmap);

    float[][][] out = new float[1][output_box][15];
    if(outData != null){
        outData.rewind();
    }

    Object[] inputArray = {imgData};
    this.tfLite.run(byteBuffer_, out);

    ArrayList<Recognition> detections = new ArrayList<Recognition>();

    for (int i = 0; i < output_box; ++i) {
        // Denormalize xywh
        for (int j = 0; j < 4; ++j) {
            out[0][i][j] *= getInputSize();
        }

    }
    float[] probs = new float[output_box];
    for (int i = 0; i < output_box; ++i){
        probs[i]= out[0][i][4];
    }
    System.out.println("Softmax");
    probs = softmax(probs);
    for (int i = 0; i < output_box; ++i){
        out[0][i][4] = probs[i];
        System.out.println(probs[i]);
    }

    for (int i = 0; i < output_box; ++i){
        final int offset = 0;
        final float confidence = out[0][i][4];
        int detectedClass = -1;
        float maxClass = -1;

        final float[] classes = new float[10];
        for (int c = 0; c < 10; ++c) {
            classes[c] = out[0][i][5 + c];
        }
        System.out.println("Step 2");
        for (int c = 0; c < 10; ++c) {
            if (Float.compare(classes[c],maxClass) > 0) {
                detectedClass = c;
                maxClass = classes[c];
            }
        }

        final float confidenceInClass = maxClass * confidence;
        System.out.println("Confidence in Class:" + confidenceInClass);
        System.out.println("Confidence in Label:" + confidence);

        if (confidenceInClass > 0.3f) {
            final float xPos = out[0][i][0];
            final float yPos = out[0][i][1];

            final float w = out[0][i][2];
            final float h = out[0][i][3];

            final RectF rect =
                    new RectF(
                          Math.max(0, xPos - w / 2),
                          Math.max(0, yPos - h / 2),
                          Math.min(bitmap.getWidth() - 1, xPos + w / 2),
                          Math.min(bitmap.getHeight() - 1, yPos + h / 2));
            detections.add(new Recognition("" + offset, this.labels.get(detectedClass),
                    confidenceInClass, rect, detectedClass));
        }
    }

    final ArrayList<Recognition> recognitions = nms(detections);
    return recognitions;
}`

Additional

I have updated java, yolo, and tensorflow as of 6/3/2024. I am using android studio 3.6.3.

github-actions[bot] commented 5 months ago

👋 Hello @Rishivarshil, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our Tips for Best Training Results.

Requirements

Python>=3.8.0 with all requirements.txt installed including PyTorch>=1.8. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

YOLOv5 CI

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training, validation, inference, export and benchmarks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

Introducing YOLOv8 🚀

We're excited to announce the launch of our latest state-of-the-art (SOTA) object detection model for 2023 - YOLOv8 🚀!

Designed to be fast, accurate, and easy to use, YOLOv8 is an ideal choice for a wide range of object detection, image segmentation and image classification tasks. With YOLOv8, you'll be able to quickly and accurately detect objects in real-time, streamline your workflows, and achieve new levels of accuracy in your projects.

Check out our YOLOv8 Docs for details and get started with:

pip install ultralytics
glenn-jocher commented 5 months ago

Hello,

Thank you for providing detailed information about your issue. From your description, it seems like the class scores from your TFLite model's output do not naturally sum up to 1 because they are raw logits or unnormalized scores. In YOLO models, the output scores for each class are typically passed through a softmax function to convert them into probabilities that sum to 1.

In your recognizeImage function, you are applying softmax to the confidence scores but not to the class scores. To resolve this, you should apply the softmax function to the class scores as well. Here's a modified snippet of your code where softmax is applied to the class scores:

for (int i = 0; i < output_box; ++i) {
    final float[] classes = new float[10];
    for (int c = 0; c < 10; ++c) {
        classes[c] = out[0][i][5 + c];
    }
    classes = softmax(classes);  // Apply softmax to class scores
    for (int c = 0; c < 10; ++c) {
        out[0][i][5 + c] = classes[c];
    }
}

Make sure to implement or use an existing softmax function that operates on an array of scores. This adjustment should normalize the class scores so that they sum up to 1, reflecting the probability distribution over the classes.

Let me know if this helps or if you have any further questions!

Rishivarshil commented 5 months ago

@glenn-jocher Can you provide me an example of a softmax function? This is my current one:

   /**
     * Computes the softmax of an array of scores.
     *
     * @param scores Array of double values representing the raw scores.
     * @return Array of double values representing the probabilities.
     */
    public static float[] softmax(float[] scores) {
        float maxScore = Float.NEGATIVE_INFINITY;
        // Find the maximum score to avoid numerical instability
        for (float score : scores) {
            if (score > maxScore) {
                maxScore = score;
            }
        }

        // Calculate the exponential of each score subtracted by maxScore
        float[] expScores = new float[scores.length];
        float sumExpScores = 0;
        for (int i = 0; i < scores.length; i++) {
            expScores[i] = (float) Math.exp(scores[i] - maxScore);
            sumExpScores += expScores[i];
        }

        // Calculate the probabilities
        float[] probabilities = new float[scores.length];
        for (int i = 0; i < scores.length; i++) {
            probabilities[i] = expScores[i] / sumExpScores;
        }

        return probabilities;
    }

Also, I feel like the confidence value is very low, always being less than 0.003. After applying the softmax function to the confidence value, it grows even smaller to ~9.4E-5. Is there any processing I need to do on that value?

glenn-jocher commented 5 months ago

Hello,

Your implementation of the softmax function looks correct and should effectively convert raw scores into probabilities that sum to 1. This function is crucial for handling numerical stability by subtracting the maximum score from each score before the exponentiation.

Regarding the issue with the very low confidence values, it's important to note that softmax is typically applied to class scores and not directly to the confidence scores of the detections. The confidence score in YOLO models usually represents the objectness of the bounding box and is separate from the class probabilities. If the confidence scores are consistently low, it might indicate issues with the model's ability to detect objects confidently. This could be due to several factors such as insufficient training data, improper training parameters, or the need for further tuning.

You might want to revisit the training process, ensuring that your model is adequately trained with diverse and representative data. Additionally, adjusting the confidence threshold used to filter predictions might help in handling low confidence values more effectively.

Let me know if you need further assistance or clarification!

github-actions[bot] commented 4 months ago

👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.

For additional resources and information, please see the links below:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLO 🚀 and Vision AI ⭐