【问题标题】:How to find correlation between two integer arrays in java如何在java中找到两个整数数组之间的相关性
【发布时间】:2015-02-10 09:39:17
【问题描述】:

我搜索了很多,但直到现在都找不到我需要的东西。 我有两个整数数组int[] xint[] y。我想在这两个整数数组之间找到简单的线性相关,它应该将结果返回为double。在java中你知道提供这个或任何代码sn-p的任何库函数吗?

【问题讨论】:

    标签: java arrays math int correlation


    【解决方案1】:

    核心 Java 中没有任何内容。那里有你可以使用的库。 Apache Commons 有一个 statistical project,请查看 PearsonCorrelation 类。

    示例代码:

    public static void main(String[] args) {
        double[] x = {1, 2, 4, 8};
        double[] y = {2, 4, 8, 16};
        double corr = new PearsonsCorrelation().correlation(y, x);
    
        System.out.println(corr);
    }
    

    打印出 1.0

    【讨论】:

      【解决方案2】:

      相关性非常很容易手动计算

      http://en.wikipedia.org/wiki/Correlation_and_dependence

        public static double Correlation(int[] xs, int[] ys) {
          //TODO: check here that arrays are not null, of the same length etc
      
          double sx = 0.0;
          double sy = 0.0;
          double sxx = 0.0;
          double syy = 0.0;
          double sxy = 0.0;
      
          int n = xs.length;
      
          for(int i = 0; i < n; ++i) {
            double x = xs[i];
            double y = ys[i];
      
            sx += x;
            sy += y;
            sxx += x * x;
            syy += y * y;
            sxy += x * y;
          }
      
          // covariation
          double cov = sxy / n - sx * sy / n / n;
          // standard error of x
          double sigmax = Math.sqrt(sxx / n -  sx * sx / n / n);
          // standard error of y
          double sigmay = Math.sqrt(syy / n -  sy * sy / n / n);
      
          // correlation is just a normalized covariation
          return cov / sigmax / sigmay;
        }
      

      【讨论】:

      • @Mvorisek:可以是i++++i++i 在旧时编译器上可能会更快一些(无需返回先前的状态)。只是英特尔 8086 时代和C 编译器的习惯......
      • 这不包括 xs 和 ys 长度不同的情况。
      • @htellez:相关性(甚至协变)需要相等的长度,或者应该扩展标准相关性的定义。
      猜你喜欢
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 2023-01-08
      相关资源
      最近更新 更多