Least squares linear fitting

Source: Internet
Author: User

Linear Fitting Using the least square method

# Coding: utf-8import numpy as npimport matplotlib. pyplot as pltdots = NP. array ([[], [], [], [], []) PLT. plot ([I [0] For I in DOTS], [I [1] For I in DOTS], 'ro') PLT. axis ([0, 6, 0, 12]) def nihezhixian (K, X, B ): return K * x + bsumxy = sum ([A [0] * A [1] For a in DOTS]) # print sumxysumxx = sum ([A [0] ** 2 for a in DOTS]) print sumxxsumx = sum ([A [0] For a in DOTS]) print sumxsumy = sum ([A [1] For a in DOTS]) # a0 = (Σ Yi)/n-A1 (Σ XI)/n (Formula 1-8) # a1 = [n Σ Xi Yi-(Σ Xi Σ Yi)]/[n Σ xi2-(Σ xi) 2)] (Formula 1-9) # print Dir (DOTS) n = dots. shape [0] K = float (N * sumxy-sumx * Sumy)/float (N * sumxx-sumx * sumx) # print A1 B = float (Sumy) /n-float (K * sumx)/NPLT. plot ([I [0] For I in DOTS], [nihezhixian (K, I [0], B) For I in DOTS]) PLT. show ()

The image output is as follows:

The problem solved by the least square method is: for a given series of points [(x1, Y1), (X2, Y2 )... (Xn, yn)], to Y's function about X.

Evaluate a Function Y = f (x) so that Y = f (x) can describe these column points, which solves the following equation:

Sum (f (xi)-yi) ** 2

There is a minimum value. In the linear fitting process, y = f (x) = ax + B. The above formula is used to calculate the minimum value. You only need to calculate the reciprocal of A and B.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.