Python最小二乘法

# -*- TomYuan
import numpy as np
import os
import matplotlib.pyplot as plt

xcord = [];
ycord = [];
def drawScatterDiagram(fileName):
    fr = open(fileName)
    for line in fr.readlines():
        line_arr = line.split(",")
        xcord.append(float(line_arr[0]));
        ycord.append(float(line_arr[1]));

drawScatterDiagram("ml.txt")

def leastSquare(xcord, ycord):
    t1 = 0; t2 = 0; t3 = 0; t4 = 0
    for num in range(0, len(xcord)):
        t1 += xcord[num] * xcord[num];
        t2 += xcord[num];
        t3 += xcord[num] * ycord[num];
        t4 += ycord[num];
    a = (t3 * len(xcord) - t2 * t4) / (t1 * len(xcord) - t2 * t2);
    b = (t1 * t4 - t2 * t3) / (t1 * len(xcord) - t2 * t2)
    return a, b

def lastDraw():
    plt.scatter(xcord, ycord, s=30, c='red')
    print(ycord[len(ycord) - 1])
    a, b = leastSquare(xcord, ycord)
    
    x1 = float(xcord[0])
    x2 = 1.0

    y1 = a * x1 + b;
    y2 = a * x2 + b;

    plt.plot([x1, x2],
             [y1, y2])
    plt.show()

lastDraw()

欢迎留言

avatar
  Subscribe  
Notify of