五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

python數(shù)據(jù)線性擬合(I)

2020-03-05 17:51 作者:一心想當(dāng)網(wǎng)紅的李老師  | 我要投稿

線性擬合是數(shù)據(jù)處理中一種比較常用的方式。但是擬合的方法也又好幾種。

1、第一版代碼(網(wǎng)上學(xué)習(xí)別人的,感覺用的是平均數(shù)方法,最小二乘法自己處理的感覺)

#! /usr/bin/env python

# -*- coding: utf-8 -*-

import numpy as np ?###使用的數(shù)學(xué)模塊

from matplotlib import pylab as pl

# 定義要分析的數(shù)據(jù),自己處理時候,可以開放接口去讀取相應(yīng)文件中的內(nèi)容

x = np.array([6,7.8,3.7,4.8,3.5])

y = np.array([14.2,24.3,18.6,17.8,27.9])


# 回歸方程求取函數(shù)

def fit(x,y):

? ? if len(x) != len(y): ?

? ? ? ??return

###先判斷一下這個數(shù)據(jù)逆否可以擬合,主要是讀取其他文件數(shù)據(jù)的時候可能出錯? ??

? ? numerator = 0.0

? ? denominator = 0.0

? ? x_mean = np.mean(x)

? ? y_mean = np.mean(y)

? ? for i in range(len(x)):

? ? ? ? numerator += (x[i]-x_mean)*(y[i]-y_mean)

? ? ? ? denominator += np.square((x[i]-x_mean))

? ? print('numerator:',numerator,'denominator:',denominator)

? ? b0 = numerator/denominator

? ? b1 = y_mean - b0*x_mean

? ? return b0,b1


# 定義預(yù)測函數(shù)

def predit(x,b0,b1):

? ? return b0*x + b1


# 求取回歸方程

b0,b1 = fit(x,y)

print('Line is:y = %2.0fx + %2.0f'%(b0,b1))


# 預(yù)測

x_test = np.array([0.5,1.5,2.5,3,4])

y_test = np.zeros((1,len(x_test)))

for i in range(len(x_test)):

? ? y_test[0][i] = predit(x_test[i],b0,b1)


# 繪制圖像

xx = np.linspace(0, 5)

yy = b0*xx + b1

pl.plot(xx,yy,'k-')

pl.scatter(x,y,cmap=pl.cm.Paired)

pl.scatter(x_test,y_test[0],cmap=pl.cm.Paired)

pl.show()


2、感覺使用了最下二乘法但是代碼不太看得懂

#! /usr/bin/env python

# -*- coding: utf-8 -*-


###最小二乘法試驗###

import numpy as np

from scipy.optimize import leastsq

from matplotlib import pylab as pl

import matplotlib.pyplot as plt



# 定義訓(xùn)練數(shù)據(jù)

x = np.array([6,7.8,3.7,4.8,3.5])

y = np.array([14.2,24.3,18.6,17.8,27.9])



###需要擬合的函數(shù)func及誤差error###

def func(p,x):

? ? k,b=p

? ? return k*x+b


def error(p,x,y,s):

? ? print s

? ? return func(p,x)-y #x、y都是列表,故返回值也是個列表


#TEST

p0=[100,2]

###主函數(shù)從此開始###

s="Test the number of iteration" #試驗最小二乘法函數(shù)leastsq得調(diào)用幾次error函數(shù)才能找到使得均方誤差之和最小的k、b

Para=leastsq(error,p0,args=(x,y,s)) #把error函數(shù)中除了p以外的參數(shù)打包到args中

k,b=Para[0]

print"k=",k,'\n',"b=",b


plt.figure(figsize=(8,6))

plt.scatter(x,y,color="red",label="Sample Point",linewidth=3) #畫樣本點

x=np.linspace(0,10,1000)

y=k*x+b

plt.plot(x,y,color="orange",label="Fitting Line",linewidth=2) #畫擬合直線

plt.legend()

plt.show()


python數(shù)據(jù)線性擬合(I)的評論 (共 條)

分享到微博請遵守國家法律
柳州市| 黔西| 平武县| 宜州市| 东光县| 普兰店市| 陇川县| 汕尾市| 江都市| 平罗县| 孟津县| 玉林市| 南昌县| 崇仁县| 衢州市| 育儿| 武清区| 莎车县| 温宿县| 西乡县| 阆中市| 林口县| 栖霞市| 新昌县| 东台市| 平舆县| 新晃| 庆云县| 闵行区| 嘉黎县| 曲水县| 景泰县| 延川县| 平潭县| 和顺县| 清丰县| 吴旗县| 纳雍县| 双江| 额敏县| 五常市|