简体   繁体   English

Java Sigmoid方法返回不正确的结果

[英]Java Sigmoid method returns Incorrect Results

I wrote out a sigmoid function in java that works fine when dealing with single numbers but when given an array fails after the first data entry. 我在Java中写出了一个Sigmoid函数,当处理单个数字但在第一次输入数据后给定数组失败时,它可以正常工作。 Here's some data to Illustrate my problem (with output rounded to 3 digits). 这是一些数据来说明我的问题(输出四舍五入到3位数字)。

    Input | Correct Output | Output
        0 |       0.5      | 0.5
     -1,0 |    0.27,0.5    | 0.27,0.62
   1,0,-1 |  0.73,0.5,0.27 | 0.73,0.62,0.64

My code is as follows. 我的代码如下。

double[] data = { 1, 0, -1 };
System.out.println(sigmoid(data)[0] + "," + sigmoid(data)[1] + "," + sigmoid(data)[2]);

and

double[] sigmoid(double[] data) {
    for (int i = 0; i < data.length; i++)
        data[i] = 1 / (1 + Math.exp(-data[i]));
    return data;
}

If this is just a stupidly obvious oversight on my part please tell me as I have been trying for hours to no avail, and thanks for any responses at all. 如果这只是我看似愚蠢的疏忽,请告诉我,因为我一直在努力几个小时都无济于事,并感谢您的任何答复。

While Java is pass by value, the value being passed to your function is a reference to the input array, not a copy of the array, so your function modifies the array in place - each call in your println is updating the results from the previous call. 当Java通过值传递时,传递给您的函数的值是对输入数组的引用,而不是数组的副本,因此您的函数会就地修改数组println每个调用都会更新前一个的结果呼叫。

Make a copy of the array to return your results in: 复制数组以返回结果:

static double[] sigmoid(double[] data) {
    double[] z = Arrays.copyOf(data, data.length);
    for (int i = 0; i < z.length; i++)
        z[i] = 1 / (1 + Math.exp(-z[i]));
    return z;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM