-1

I am relatively new to Java and ML but have been trying to learn, so forgive any noob mistakes. I have been following an article about ML in python have been trying to kind of translate it to Java to train the language and learn about the subject in the process, I have been getting a NullPointerException at the line of the variable loss and when I try to initialize the method in the main class, I can`t seem to find the problem.

I have tried running the method in a non static way and just rewriting everything, but it doesn`t seem to work.

    public static double calcLoss() {
        for (int i = 0; i < y_true.length; i++) {
            double a = (1 / y_true.length) * Math.pow(y_true[i] - y_pred[i], 2);
            loss = a;
        }       
        return loss;
    }

I know it says not to do it but here is a pastr with the full code, maybe this helps. https://pastr.io/view/bSacVk

This is the error

>Exception in thread "main" java.lang.NullPointerException
    >at Net.Neuron.calcLoss(Neuron.java:40)
    >at Net.Main.main(Main.java:28)
gdsouza
  • 9
  • 3

1 Answers1

0

I have been getting a NullPointerException at the line of the variable loss and when I try to initialize the method in the main class, I can`t seem to find the problem.

That's because one of y_true or y_pred is likely null. You can easily handle this case by adding a if statement like this,

public static double calcLoss() {
    if (null != y_true && null != y_pred && y_pred.length == y_true.length) {
        for (int i = 0; i < y_true.length; i++) {
            double a = (1d / y_true.length) * Math.pow(y_true[i] - y_pred[i], 2);
            // This is just re-assigning loss. Are you sure this is what you intended here?
            loss = a;
        }       
        return loss;
    }
    // y_true is NULL.
    return -1;
}

Also, I'm not sure what is the original intent here but, you are just reassigning loss in every iteration of the loop.

user2004685
  • 9,548
  • 5
  • 37
  • 54