Python實(shí)現(xiàn)線性函數(shù)的擬合算法

關(guān)于Python數(shù)據(jù)分析在數(shù)學(xué)建模中的更多相關(guān)應(yīng)用:Python數(shù)據(jù)分析在數(shù)學(xué)建模中的應(yīng)用匯總(持續(xù)更新中?。?/a>

(一)、讀取數(shù)據(jù)

在這里插入圖片描述
#從excel文件中讀取數(shù)據(jù)
def read(file):
    wb = xlrd.open_workbook(filename=file)#打開(kāi)文件
    sheet = wb.sheet_by_index(0)#通過(guò)索引獲取表格
    rows = sheet.nrows # 獲取行數(shù)
    all_content = []        #存放讀取的數(shù)據(jù)
    for j in range(0, 2):       #取第1~第2列對(duì)的數(shù)據(jù)
        temp = []
        for i in range(1,rows) :
            cell = sheet.cell_value(i, j)   #獲取數(shù)據(jù) 
            temp.append(cell)           
        all_content.append(temp)    #按列添加到結(jié)果集中
        temp = []
    return np.array(all_content)    #返回讀取的數(shù)據(jù)

(二)、獲得擬合函數(shù)并繪制圖象

在這里插入圖片描述
#獲得擬合函數(shù)并繪制圖象
def temp1(datas):
    x = datas[0]        #獲取自變量x
    y = datas[1]        #獲取因變量y
    n = np.size(answer1, axis = 1)  #獲取有多少個(gè)自變量,axis=1代表獲取矩陣的列數(shù)
    #根據(jù)公式計(jì)算k
    k = (n*np.sum(x*y) - np.sum(x)*np.sum(y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))   
    #根據(jù)公式計(jì)算b
    b = (np.sum(np.power(x,2)) * np.sum(y) -np.sum(x) * np.sum(x*y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))
    las = k*x + b       #根據(jù)公式得到擬合函數(shù)
    fig = plt.figure()  #獲得figure對(duì)象
    ax1 = fig.add_subplot(1,1,1)    #添加一個(gè)圖紙
    ax1.set_xlim([min(x)-0.5, max(x)+0.5])      #設(shè)置x軸刻度
    ax1.set_ylim([min(y) -0.5, max(y) +0.5])    #設(shè)置y軸刻度
    plt.plot(x,las,'k',label='擬合函數(shù)')    #畫出擬合函數(shù)
    plt.plot(x,y,'o',label = '樣本數(shù)據(jù)')    #畫出樣本數(shù)據(jù)
    plt.grid()  #添加網(wǎng)格線
    ax1.legend(loc = 'best')    #設(shè)置圖例的位置為最佳best
    return [k,b]    #返回k和b

(三)、通過(guò)計(jì)算擬合優(yōu)度評(píng)價(jià)擬合函數(shù)

在這里插入圖片描述
#通過(guò)計(jì)算擬合優(yōu)度評(píng)價(jià)擬合函數(shù)
def judge(datas,k,b):
    x = datas[0]    #獲取自變量x
    y = datas[1]    #獲取自變量y
    z = k * x + b   #得到擬合函數(shù)
    SST = np.sum(np.power(y - np.average(y),2))     #根據(jù)公式計(jì)算SST
    SSE = np.sum(np.power(y - z, 2))                #根據(jù)公式計(jì)算SSE
    SSR = np.sum(np.power(z - np.average(y),2))     #根據(jù)公式計(jì)算SSR
    R_2 = SSR / SST             #得到R_2
    print('k = ',k)
    print('b = ',b)
    print('SST = ',SST)
    print('SSE = ',SSE)
    print('SSR = ',SSR)
    print('R_2 = ',R_2)

(四)、綜合代碼

# -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 11:03:49 2019

@author: lenovo
"""
import xlrd
import numpy as np
import matplotlib.pyplot as plt

#從excel文件中讀取數(shù)據(jù)
def read(file):
    wb = xlrd.open_workbook(filename=file)#打開(kāi)文件
    sheet = wb.sheet_by_index(0)#通過(guò)索引獲取表格
    rows = sheet.nrows # 獲取行數(shù)
    all_content = []        #存放讀取的數(shù)據(jù)
    for j in range(0, 2):       #取第1~第2列對(duì)的數(shù)據(jù)
        temp = []
        for i in range(1,rows) :
            cell = sheet.cell_value(i, j)   #獲取數(shù)據(jù) 
            temp.append(cell)           
        all_content.append(temp)    #按列添加到結(jié)果集中
        temp = []
    return np.array(all_content)    #返回讀取的數(shù)據(jù)
#獲得擬合函數(shù)并繪制圖象
def temp1(datas):
    x = datas[0]        #獲取自變量x
    y = datas[1]        #獲取因變量y
    n = np.size(answer1, axis = 1)  #獲取有多少個(gè)自變量,axis=1代表獲取矩陣的列數(shù)
    #根據(jù)公式計(jì)算k
    k = (n*np.sum(x*y) - np.sum(x)*np.sum(y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))   
    #根據(jù)公式計(jì)算b
    b = (np.sum(np.power(x,2)) * np.sum(y) -np.sum(x) * np.sum(x*y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x))
    las = k*x + b       #根據(jù)公式得到擬合函數(shù)
    fig = plt.figure()  #獲得figure對(duì)象
    ax1 = fig.add_subplot(1,1,1)    #添加一個(gè)圖紙
    ax1.set_xlim([min(x)-0.5, max(x)+0.5])      #設(shè)置x軸刻度
    ax1.set_ylim([min(y) -0.5, max(y) +0.5])    #設(shè)置y軸刻度
    plt.plot(x,las,'k',label='擬合函數(shù)')    #畫出擬合函數(shù)
    plt.plot(x,y,'o',label = '樣本數(shù)據(jù)')    #畫出樣本數(shù)據(jù)
    plt.grid()  #添加網(wǎng)格線
    ax1.legend(loc = 'best')    #設(shè)置圖例的位置為最佳best
    return [k,b]    #返回k和b
#通過(guò)計(jì)算擬合優(yōu)度評(píng)價(jià)擬合函數(shù)
def judge(datas,k,b):
    x = datas[0]    #獲取自變量x
    y = datas[1]    #獲取自變量y
    z = k * x + b   #得到擬合函數(shù)
    SST = np.sum(np.power(y - np.average(y),2))     #根據(jù)公式計(jì)算SST
    SSE = np.sum(np.power(y - z, 2))                #根據(jù)公式計(jì)算SSE
    SSR = np.sum(np.power(z - np.average(y),2))     #根據(jù)公式計(jì)算SSR
    R_2 = SSR / SST             #得到R_2
    print('k = ',k)
    print('b = ',b)
    print('SST = ',SST)
    print('SSE = ',SSE)
    print('SSR = ',SSR)
    print('R_2 = ',R_2)
    
answer1 = read('C:\\Users\\lenovo\\Desktop\\數(shù)學(xué)建模\\擬合算法\\第4講.擬合7.21\\代碼和例題數(shù)據(jù)\\data1.xlsx')
answer2 = temp1(answer1)
judge(answer1,answer2[0],answer2[1])

(五)、結(jié)果輸出

在這里插入圖片描述

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容