c# LOESS/LOWESS 回归 [关闭]

2024-04-21

您知道执行 LOESS/LOWESS 回归的 .net 库吗? (最好是免费/开源)


端口来自java http://commons.apache.org/math/api-2.0/src-html/org/apache/commons/math/analysis/interpolation/LoessInterpolator.html to c#

public class LoessInterpolator
{
    public static double DEFAULT_BANDWIDTH = 0.3;
    public static int DEFAULT_ROBUSTNESS_ITERS = 2;

    /**
     * The bandwidth parameter: when computing the loess fit at
     * a particular point, this fraction of source points closest
     * to the current point is taken into account for computing
     * a least-squares regression.
     * 
     * A sensible value is usually 0.25 to 0.5.
     */
    private double bandwidth;

    /**
     * The number of robustness iterations parameter: this many
     * robustness iterations are done.
     * 
     * A sensible value is usually 0 (just the initial fit without any
     * robustness iterations) to 4.
     */
    private int robustnessIters;

    public LoessInterpolator()
    {
        this.bandwidth = DEFAULT_BANDWIDTH;
        this.robustnessIters = DEFAULT_ROBUSTNESS_ITERS;
    }

    public LoessInterpolator(double bandwidth, int robustnessIters)
    {
        if (bandwidth < 0 || bandwidth > 1)
        {
            throw new ApplicationException(string.Format("bandwidth must be in the interval [0,1], but got {0}", bandwidth));
        }
        this.bandwidth = bandwidth;
        if (robustnessIters < 0)
        {
            throw new ApplicationException(string.Format("the number of robustness iterations must be non-negative, but got {0}", robustnessIters));
        }
        this.robustnessIters = robustnessIters;
    }

    /**
     * Compute a loess fit on the data at the original abscissae.
     *
     * @param xval the arguments for the interpolation points
     * @param yval the values for the interpolation points
     * @return values of the loess fit at corresponding original abscissae
     * @throws MathException if some of the following conditions are false:
     * <ul>
     * <li> Arguments and values are of the same size that is greater than zero</li>
     * <li> The arguments are in a strictly increasing order</li>
     * <li> All arguments and values are finite real numbers</li>
     * </ul>
     */
    public double[] smooth(double[] xval, double[] yval)
    {
        if (xval.Length != yval.Length)
        {
            throw new ApplicationException(string.Format("Loess expects the abscissa and ordinate arrays to be of the same size, but got {0} abscisssae and {1} ordinatae", xval.Length, yval.Length));
        }
        int n = xval.Length;
        if (n == 0)
        {
            throw new ApplicationException("Loess expects at least 1 point");
        }

        checkAllFiniteReal(xval, true);
        checkAllFiniteReal(yval, false);
        checkStrictlyIncreasing(xval);

        if (n == 1)
        {
            return new double[] { yval[0] };
        }

        if (n == 2)
        {
            return new double[] { yval[0], yval[1] };
        }

        int bandwidthInPoints = (int)(bandwidth * n);

        if (bandwidthInPoints < 2)
        {
            throw new ApplicationException(string.Format("the bandwidth must be large enough to accomodate at least 2 points. There are {0} " +
                " data points, and bandwidth must be at least {1} but it is only {2}",
                n, 2.0 / n, bandwidth
            ));
        }

        double[] res = new double[n];

        double[] residuals = new double[n];
        double[] sortedResiduals = new double[n];

        double[] robustnessWeights = new double[n];

        // Do an initial fit and 'robustnessIters' robustness iterations.
        // This is equivalent to doing 'robustnessIters+1' robustness iterations
        // starting with all robustness weights set to 1.
        for (int i = 0; i < robustnessWeights.Length; i++) robustnessWeights[i] = 1;
        for (int iter = 0; iter <= robustnessIters; ++iter)
        {
            int[] bandwidthInterval = { 0, bandwidthInPoints - 1 };
            // At each x, compute a local weighted linear regression
            for (int i = 0; i < n; ++i)
            {
                double x = xval[i];

                // Find out the interval of source points on which
                // a regression is to be made.
                if (i > 0)
                {
                    updateBandwidthInterval(xval, i, bandwidthInterval);
                }

                int ileft = bandwidthInterval[0];
                int iright = bandwidthInterval[1];

                // Compute the point of the bandwidth interval that is
                // farthest from x
                int edge;
                if (xval[i] - xval[ileft] > xval[iright] - xval[i])
                {
                    edge = ileft;
                }
                else
                {
                    edge = iright;
                }

                // Compute a least-squares linear fit weighted by
                // the product of robustness weights and the tricube
                // weight function.
                // See http://en.wikipedia.org/wiki/Linear_regression
                // (section "Univariate linear case")
                // and http://en.wikipedia.org/wiki/Weighted_least_squares
                // (section "Weighted least squares")
                double sumWeights = 0;
                double sumX = 0, sumXSquared = 0, sumY = 0, sumXY = 0;
                double denom = Math.Abs(1.0 / (xval[edge] - x));
                for (int k = ileft; k <= iright; ++k)
                {
                    double xk = xval[k];
                    double yk = yval[k];
                    double dist;
                    if (k < i)
                    {
                        dist = (x - xk);
                    }
                    else
                    {
                        dist = (xk - x);
                    }
                    double w = tricube(dist * denom) * robustnessWeights[k];
                    double xkw = xk * w;
                    sumWeights += w;
                    sumX += xkw;
                    sumXSquared += xk * xkw;
                    sumY += yk * w;
                    sumXY += yk * xkw;
                }

                double meanX = sumX / sumWeights;
                double meanY = sumY / sumWeights;
                double meanXY = sumXY / sumWeights;
                double meanXSquared = sumXSquared / sumWeights;

                double beta;
                if (meanXSquared == meanX * meanX)
                {
                    beta = 0;
                }
                else
                {
                    beta = (meanXY - meanX * meanY) / (meanXSquared - meanX * meanX);
                }

                double alpha = meanY - beta * meanX;

                res[i] = beta * x + alpha;
                residuals[i] = Math.Abs(yval[i] - res[i]);
            }

            // No need to recompute the robustness weights at the last
            // iteration, they won't be needed anymore
            if (iter == robustnessIters)
            {
                break;
            }

            // Recompute the robustness weights.

            // Find the median residual.
            // An arraycopy and a sort are completely tractable here, 
            // because the preceding loop is a lot more expensive
            System.Array.Copy(residuals, sortedResiduals, n);
            //System.arraycopy(residuals, 0, sortedResiduals, 0, n);
            Array.Sort<double>(sortedResiduals);
            double medianResidual = sortedResiduals[n / 2];

            if (medianResidual == 0)
            {
                break;
            }

            for (int i = 0; i < n; ++i)
            {
                double arg = residuals[i] / (6 * medianResidual);
                robustnessWeights[i] = (arg >= 1) ? 0 : Math.Pow(1 - arg * arg, 2);
            }
        }

        return res;
    }

    /**
     * Given an index interval into xval that embraces a certain number of
     * points closest to xval[i-1], update the interval so that it embraces
     * the same number of points closest to xval[i]
     *
     * @param xval arguments array
     * @param i the index around which the new interval should be computed
     * @param bandwidthInterval a two-element array {left, right} such that: <p/>
     * <tt>(left==0 or xval[i] - xval[left-1] > xval[right] - xval[i])</tt>
     * <p/> and also <p/>
     * <tt>(right==xval.length-1 or xval[right+1] - xval[i] > xval[i] - xval[left])</tt>.
     * The array will be updated.
     */
    private static void updateBandwidthInterval(double[] xval, int i, int[] bandwidthInterval)
    {
        int left = bandwidthInterval[0];
        int right = bandwidthInterval[1];

        // The right edge should be adjusted if the next point to the right
        // is closer to xval[i] than the leftmost point of the current interval
        int nextRight = nextNonzero(weights, right);
        if (nextRight < xval.Length && xval[nextRight] - xval[i] < xval[i] - xval[left])
        {
            int nextLeft = nextNonzero(weights, bandwidthInterval[0]);
            bandwidthInterval[0] = nextLeft;
            bandwidthInterval[1] = nextRight;
        }
    }

    /**
     * Compute the 
     * <a href="http://en.wikipedia.org/wiki/Local_regression#Weight_function">tricube</a>
     * weight function
     *
     * @param x the argument
     * @return (1-|x|^3)^3
     */
    private static double tricube(double x)
    {
        double tmp = Math.abs(x);
               tmp = 1 - tmp * tmp * tmp;
        return tmp * tmp * tmp;
    }

    /**
     * Check that all elements of an array are finite real numbers.
     *
     * @param values the values array
     * @param isAbscissae if true, elements are abscissae otherwise they are ordinatae
     * @throws MathException if one of the values is not
     *         a finite real number
     */
    private static void checkAllFiniteReal(double[] values, bool isAbscissae)
    {
        for (int i = 0; i < values.Length; i++)
        {
            double x = values[i];
            if (Double.IsInfinity(x) || Double.IsNaN(x))
            {
                string pattern = isAbscissae ?
                        "all abscissae must be finite real numbers, but {0}-th is {1}" :
                        "all ordinatae must be finite real numbers, but {0}-th is {1}";
                throw new ApplicationException(string.Format(pattern, i, x));
            }
        }
    }

    /**
     * Check that elements of the abscissae array are in a strictly
     * increasing order.
     *
     * @param xval the abscissae array
     * @throws MathException if the abscissae array
     * is not in a strictly increasing order
     */
    private static void checkStrictlyIncreasing(double[] xval)
    {
        for (int i = 0; i < xval.Length; ++i)
        {
            if (i >= 1 && xval[i - 1] >= xval[i])
            {
                throw new ApplicationException(string.Format(
                        "the abscissae array must be sorted in a strictly " +
                        "increasing order, but the {0}-th element is {1} " +
                        "whereas {2}-th is {3}",
                        i - 1, xval[i - 1], i, xval[i]));
            }
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c# LOESS/LOWESS 回归 [关闭] 的相关文章

随机推荐

  • 将 OpenCV 的 findHomography 透视矩阵转换为 iOS 的 CATransform3D

    我想获取从 OpenCV 返回的透视变换矩阵findHomography http docs opencv org modules calib3d doc camera calibration and 3d reconstruction h
  • 通过 jQuery 打开和关闭 Div

    繁花似锦 在过去的几篇文章中 你们都帮助我走得很远 如果你们能够帮助我 我现在面临另一个问题 我也认为上次我没有解释得很好 所以就这样吧 我有 3 个 id div 名为 white v2black v3black 我的目标是拥有一个超链接
  • 非静态方法 getActivity()

    我将方法 showResult 设为静态 但我有问题 Toast makeText getActivity getApplication result2 n Total Amount totalAmount2 Toast LENGTH LO
  • Emacs 在 haskell 模式下挂起,并调用 下面的 haskell-load-file 调用

    当在 Haskell 文件中时 我使用C c C l运行命令inferior haskell load file其目的是将当前文件加载到 GHCI 解释器中 但 Emacs 会挂起 直到我点击C g 有人知道我怎样才能让它发挥作用吗 all
  • 如何使用保存实例状态来保存活动状态?

    我一直在研究Android SDK平台 并且不太清楚如何保存应用程序的状态 因此 考虑到对 Hello Android 示例的这个小改动 package com android hello import android app Activi
  • 使用 R 中的 Cox 比例风险模型计算生存预测

    我正在尝试使用 R 中的 Cox 比例风险模型来计算生存预测 library survival data lung model lt coxph Surv time status 2 age sex ph karno wt loss dat
  • 删除项目后强制刷新桌面上的图标,或首先停止添加项目

    我创建了一个 powershell 脚本来侦听要在桌面上创建的文件 如果文件符合特定条件 则会立即删除该文件 我用了Remove Item path where path是我要删除的文件的路径 问题是 Windows 仍然添加并继续在桌面上
  • 在 Perl 中正确检测文件的行结尾?

    问题 我有在 Windows 和 nix 上生成的数据 大部分为 CSV 格式 并且大部分在 nix 上处理 Windows 使用 CRLF 作为行结束符 Unix 使用 LF 对于任何特定文件 我不知道它是否有 windows 或 nix
  • 在 JQuery 事件中查找父元素

    我添加了一个点击事件 如下所示 并想检查目标是否有特定的父级 document click function event Check here if target has specific parent for example gt par
  • 使用 Powershell 获取 Windows DisplayLanguage

    我正在尝试通过 powershell 获取 Windows 显示语言设置 我尝试了 Get WinUserLanguageList 但这会返回所有语言的列表 Get WinSystemLocale 和 Get Culture 也不是我正在寻
  • sessionState 超时不适用于 DefaultSessionProvider

    我有一个网站 我使用 ASP NET 成员资格来管理用户创建 登录 角色管理 我使用 Visual Studio 2012 web config 中有很多由 Visual Studio 创建的元素 与会话状态相关的元素之一如下 sessio
  • Struts2 在 select 标签中使用 Map

    您可以轻松地在struts2 select标签中使用List 但是有没有办法在标签中使用Map 如果可以请提供示例代码 thanx 在我的动作课上 public class MyAction extends ActionSupport pr
  • Facebook的“蓝色”背景色的十六进制代码是什么?

    我想为我的手机应用程序设置背景颜色 例如 Facebook 的蓝色背景颜色 那么它的十六进制代码是什么呢 蓝色主横幅的颜色是 3b5999 用于评论背景的浅蓝色是 eeeff4 解决这个问题的一种方法是抓取屏幕截图并在具有颜色选择器工具的图
  • AVLayerVideoGravityResize 在新设备、iOS 10 上不匹配?

    具有全屏实时预览功能的相机 previewLayer videoGravity AVLayerVideoGravityResize 制作图像 stillImageOutput captureStillImageAsynchronously
  • 使用自制软件安装hadoop时出错

    我正在尝试在 Mac 上本地安装 hadoop 但在尝试 brew install hadoop 时收到以下错误 brew install hadoop gt Downloading http www apache org dyn clos
  • IntelliJ IDEA 中缺少“更新资源”选项

    我正在使用 tomcat 7 来开发 java web 应用程序 在调试模式下运行tomcat 我在 更新 菜单上没有 更新资源 和 更新类和资源 选项 只有 热插拔类 重新部署 和 重新启动服务器 请问你能帮忙找到他们吗 预先非常感谢 这
  • 玩框架。无需编译

    我被介绍到 Play 框架 我发现它的令人惊奇的事情之一是不需要编译项目 您只需保存编辑的文件并重新加载网页即可 我听说 Java 源代码被编译为字节码 然后使用 JIT 编译器进行编译 那么 Play 框架内部到底有什么魔力呢 在 DEV
  • MySQL:如何选择本周的记录?

    我有桌子temp结构上sqlfiddle http sqlfiddle com 2 cf1aa id int 11 primary key name varchar 100 name2 varchar 100 date datetime 我
  • 如何在Python 3.6中安装pymssql模块?

    我已经阅读了一些涉及 FreeTDS Wheel git 和 github 的文档 但在我的带有 Python 3 6 的 Windows 10 PC 上没有任何功能 但我需要安装它 我正在开发一个项目 我对已经安装在我的电脑中的 mssq
  • c# LOESS/LOWESS 回归 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 您知道执行 LOESS LOWESS 回归的 net 库吗 最好是免费 开源 端口来自java htt