最小二乘法多项式拟合的Java实现--转
原文地址:http://blog.csdn.net/funnyrand/article/details/46742561
背景
由于项目中需要根据磁盘的历史使用情况预测未来一段时间的使用情况,决定采用最小二乘法做多项式拟合,这里简单描述下:
假设给定的数据点和其对应的函数值为 (x1, y1), (x2, y2), ... (xm, ym),需要做的就是得到一个多项式函数
f(x) = a0 * x + a1 * pow(x, 2) + .. + an * pow(x, n),使其对所有给定x所计算出的f(x)与实际对应的y值的差的平方和最小,
也就是计算多项式的各项系数 a0, a1, ... an.
根据最小二乘法的原理,该问题可转换为求以下线性方程组的解:Ga = B,
所以从编程的角度来说需要做两件事情,1,确定线性方程组的各个系数,2,解线性方程组
确定系数比较简单,对给定的 (x1, y1), (x2, y2), ... (xm, ym) 做相应的计算即可,相关代码:
private void compute() {
...
}
解线性方程组稍微复杂,这里用到了高斯消元法,基本思想是通过递归做矩阵转换,逐渐减少求解的多项式系数的个数,相关代码:
private double[] calcLinearEquation(double[][] a, double[] b) {
...
}
Java代码
- package com.my.study.algorithm.leastSquareMethod;
- /**
- * Least square method class.
- */
- public class LeastSquareMethod {
- private double[] x;
- private double[] y;
- private double[] weight;
- private int n;
- private double[] coefficient;
- /**
- * Constructor method.
- *
- * @param x
- * Array of x
- * @param y
- * Array of y
- * @param n
- * The order of polynomial
- */
- public LeastSquareMethod(double[] x, double[] y, int n) {
- if (x == null || y == null || x.length < 2 || x.length != y.length
- || n < 2) {
- throw new IllegalArgumentException(
- "IllegalArgumentException occurred.");
- }
- this.x = x;
- this.y = y;
- this.n = n;
- weight = new double[x.length];
- for (int i = 0; i < x.length; i++) {
- weight[i] = 1;
- }
- compute();
- }
- /**
- * Constructor method.
- *
- * @param x
- * Array of x
- * @param y
- * Array of y
- * @param weight
- * Array of weight
- * @param n
- * The order of polynomial
- */
- public LeastSquareMethod(double[] x, double[] y, double[] weight, int n) {
- if (x == null || y == null || weight == null || x.length < 2
- || x.length != y.length || x.length != weight.length || n < 2) {
- throw new IllegalArgumentException(
- "IllegalArgumentException occurred.");
- }
- this.x = x;
- this.y = y;
- this.n = n;
- this.weight = weight;
- compute();
- }
- /**
- * Get coefficient of polynomial.
- *
- * @return coefficient of polynomial
- */
- public double[] getCoefficient() {
- return coefficient;
- }
- /**
- * Used to calculate value by given x.
- *
- * @param x
- * x
- * @return y
- */
- public double fit(double x) {
- if (coefficient == null) {
- return 0;
- }
- double sum = 0;
- for (int i = 0; i < coefficient.length; i++) {
- sum += Math.pow(x, i) * coefficient[i];
- }
- return sum;
- }
- /**
- * Use Newton's method to solve equation.
- *
- * @param y
- * y
- * @return x
- */
- public double solve(double y) {
- return solve(y, 1.0d);
- }
- /**
- * Use Newton's method to solve equation.
- *
- * @param y
- * y
- * @param startX
- * The start point of x
- * @return x
- */
- public double solve(double y, double startX) {
- final double EPS = 0.0000001d;
- if (coefficient == null) {
- return 0;
- }
- double x1 = 0.0d;
- double x2 = startX;
- do {
- x1 = x2;
- x2 = x1 - (fit(x1) - y) / calcReciprocal(x1);
- } while (Math.abs((x1 - x2)) > EPS);
- return x2;
- }
- /*
- * Calculate the reciprocal of x.
- *
- * @param x x
- *
- * @return the reciprocal of x
- */
- private double calcReciprocal(double x) {
- if (coefficient == null) {
- return 0;
- }
- double sum = 0;
- for (int i = 1; i < coefficient.length; i++) {
- sum += i * Math.pow(x, i - 1) * coefficient[i];
- }
- return sum;
- }
- /*
- * This method is used to calculate each elements of augmented matrix.
- */
- private void compute() {
- if (x == null || y == null || x.length <= 1 || x.length != y.length
- || x.length < n || n < 2) {
- return;
- }
- double[] s = new double[(n - 1) * 2 + 1];
- for (int i = 0; i < s.length; i++) {
- for (int j = 0; j < x.length; j++) {
- s[i] += Math.pow(x[j], i) * weight[j];
- }
- }
- double[] b = new double[n];
- for (int i = 0; i < b.length; i++) {
- for (int j = 0; j < x.length; j++) {
- b[i] += Math.pow(x[j], i) * y[j] * weight[j];
- }
- }
- double[][] a = new double[n][n];
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- a[i][j] = s[i + j];
- }
- }
- // Now we need to calculate each coefficients of augmented matrix
- coefficient = calcLinearEquation(a, b);
- }
- /*
- * Calculate linear equation.
- *
- * The matrix equation is like this: Ax=B
- *
- * @param a two-dimensional array
- *
- * @param b one-dimensional array
- *
- * @return x, one-dimensional array
- */
- private double[] calcLinearEquation(double[][] a, double[] b) {
- if (a == null || b == null || a.length == 0 || a.length != b.length) {
- return null;
- }
- for (double[] x : a) {
- if (x == null || x.length != a.length)
- return null;
- }
- int len = a.length - 1;
- double[] result = new double[a.length];
- if (len == 0) {
- result[0] = b[0] / a[0][0];
- return result;
- }
- double[][] aa = new double[len][len];
- double[] bb = new double[len];
- int posx = -1, posy = -1;
- for (int i = 0; i <= len; i++) {
- for (int j = 0; j <= len; j++)
- if (a[i][j] != 0.0d) {
- posy = j;
- break;
- }
- if (posy != -1) {
- posx = i;
- break;
- }
- }
- if (posx == -1) {
- return null;
- }
- int count = 0;
- for (int i = 0; i <= len; i++) {
- if (i == posx) {
- continue;
- }
- bb[count] = b[i] * a[posx][posy] - b[posx] * a[i][posy];
- int count2 = 0;
- for (int j = 0; j <= len; j++) {
- if (j == posy) {
- continue;
- }
- aa[count][count2] = a[i][j] * a[posx][posy] - a[posx][j]
- * a[i][posy];
- count2++;
- }
- count++;
- }
- // Calculate sub linear equation
- double[] result2 = calcLinearEquation(aa, bb);
- // After sub linear calculation, calculate the current coefficient
- double sum = b[posx];
- count = 0;
- for (int i = 0; i <= len; i++) {
- if (i == posy) {
- continue;
- }
- sum -= a[posx][i] * result2[count];
- result[i] = result2[count];
- count++;
- }
- result[posy] = sum / a[posx][posy];
- return result;
- }
- public static void main(String[] args) {
- LeastSquareMethod eastSquareMethod = new LeastSquareMethod(
- new double[] { 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 }, new double[] {
- 1.75, 2.45, 3.81, 4.8, 7.0, 8.6 }, 3);
- /*double[] coefficients = eastSquareMethod.getCoefficient();
- for (double c : coefficients) {
- System.out.println(c);
- }*/
- System.out.println(eastSquareMethod.fit(4));
- LeastSquareMethod eastSquareMethod2 = new LeastSquareMethod(
- new double[] { 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 }, new double[] {
- 1.75, 2.45, 3.81, 4.8, 7.0, 8.6 }, 2);
- System.out.println(eastSquareMethod2.solve(100));
- }
- }
使用开源库
也可使用Apache开源库commons math,提供的功能更强大,
http://commons.apache.org/proper/commons-math/userguide/fitting.html
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-math3</artifactId>
- <version>3.5</version>
- </dependency>
- private static void testLeastSquareMethodFromApache() {
- final WeightedObservedPoints obs = new WeightedObservedPoints();
- obs.add(-3, 4);
- obs.add(-2, 2);
- obs.add(-1, 3);
- obs.add(0, 0);
- obs.add(1, -1);
- obs.add(2, -2);
- obs.add(3, -5);
- // Instantiate a third-degree polynomial fitter.
- final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(3);
- // Retrieve fitted parameters (coefficients of the polynomial function).
- final double[] coeff = fitter.fit(obs.toList());
- for (double c : coeff) {
- System.out.println(c);
- }
- }
转载于:https://www.cnblogs.com/davidwang456/articles/5582752.html
最小二乘法多项式拟合的Java实现--转相关推荐
- 多项式拟合 java_最小二乘法多项式拟合的Java实现
背景由于项目中需要根据磁盘的历史使用情况预测未来一段时间的使用情况,决定采用最小二乘法做多项式拟合,这里简单描述下: 假设给定的数据点和其对应的函数值为 (x1, y1), (x2, y2), ... ...
- python多项式拟合_最小二乘法—多项式拟合非线性函数
本章涉及到的知识点清单: 1.函数的近似表示-高次多项式 2.误差函数-最小二乘法 3.引出案例函数曲线 4.目标函数 5.优化目标函数 6.优化目标函数-梯度下降法 7.优化目标函数-求解线性方程组 ...
- 数值计算之 拟合法,线性拟合,多项式拟合
数值计算之 拟合法之线性拟合,多项式拟合 前言 最小二乘法 多项式拟合 线性拟合 后记 前言 拟合法是另一种由采样数据求取潜在函数的方法.插值要求函数必须经过每一个采样节点,而拟合则要求函数与全部节点 ...
- 最小二乘法函数拟合原理及matlab实现—数学笔记
最小二乘法函数拟合原理及matlab实现 --数值分析数学笔记 如有纰漏,欢迎指正 文章目录 最小二乘法函数拟合原理及matlab实现 前言 一.拟合标准 1.使偏差向量满足 1 1 1 - 范数 2 ...
- matlab多项式拟合要求系数项大于零,matlab多项式系数
要求一高阶多项式的根往 往须借助数值方法,所 幸MATLAB已将这些数值方法写成一函数 roots(p),我们只要输入多项式的各阶系数 (以 p 代表)即可求解到对应的根 >...... 2. ...
- 最小二乘法多项式曲线拟合原理与实现(错误地方已经修改底层补充自己写的java实现)
目录(?) [-] 概念 原理 运行前提 代码 运行效果 概念 最小二乘法多项式曲线拟合,根据给定的m个点,并不要求这条曲线精确地经过这些点,而是曲线y=f(x)的近似曲线y= φ(x). 原理 [原 ...
- java 多项式拟合最多的项数_机器学习(1)--线性回归和多项式拟合
机器学习(1)--线性回归和多项式拟合 机器学习(2)逻辑回归 (数学推导及代码实现) 机器学习(3)softmax实现Fashion-MNIST分类 一 线性回归 线性回归,顾名思义是利用线性模型对 ...
- 最小二乘多项式拟合程序matlab,最小二乘法的多项式拟合(matlab实现)
1.用最小二乘法进行多项式拟合(matlab实现)西安交通大学 徐彬华算法分析:对给定数据 (i=0 ,1,2,3,.,m),一共m+1个数据点,取多项式P(x),使函数P(x)称为拟合函数或最小二乘 ...
- java 多项式拟合最多的项数_Matlab概率统计与曲线拟合
一.二项分布 二项分布来源于伯努利试验 (事件发生概率 ) : 含义为独立重复N次试验后, 事件总共发生k次的概率 分布函数 二项分布记为 binopdf 获得事件共发生次的概率 binocdf 为事 ...
最新文章
- 链表问题13——删除无序单链表中值重复出现的节点(方法二)
- 你的生产型ML复现不了,可能是工作流程出了问题
- request url换成ip地址_【协议粗讲】TTP协议之URL,不能不知道的协议技术点
- android 手动 打包,android 手动打包apk
- C++11 std::bind 和 std::placeholder
- 页面残留数据该如何处理
- oracle 重复的记录数,如何确定Oracle数据库表中重复的记录
- 一站式WPF--依赖属性(DependencyProperty)
- 简书留言收费可行性评估
- 技术人必备的学习工具
- 封装条形码MaHelper
- 【易实战】Spring Cloud Greenwich Eureka:服务注册与发现
- mysql触发器报错_mysql触发器实例:莫名其妙的错误?
- 【知易行难】RS485组网连接示意图
- 计算机信息检索工作的原理,2021年湖北自考计算机信息检索课程考试大纲
- 【原创】使用高德 API
- 制作一个类“全能扫描王”的简易扫描软件(opencv)
- AI绘画小程序图片转漫画SaaS多开
- 【人工智能】人脸识别系统【实验报告与全部代码】(QDU)
- 实习6(持续更新)--数据分析
热门文章
- mysql主从复制自增_关于mysql主从复制自增长列
- java简述对象的组合_Java程序运行和对象创建过程简述
- java derby 用户安全_Java 7u51安全权限变化,运行derby server被拒,解决方法
- linux应用程序抢占键盘,linux 系统挂起
- sqlserver 指数_大盘指数大涨,牛市是否提前来了?
- Linux视频切片m3u8,使用ffmpeg+nginx使用视频切片播放
- java统计日志qps_【原创】基于日志增量,统计qps,并基于ip排序
- 记录webscraper的使用过程
- 融云php sdk下载安装,LICENSE · 融云 RongCloud/server-sdk-php-composer - Gitee.com
- mysql 22001_mysql ERROR 1264 (22003): Out of range value for column 'x' at row 1 错误