最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(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)的評論 (共 條)

分享到微博請遵守國家法律
财经| 红原县| 钟山县| 平顺县| 和平区| 上栗县| 祁阳县| 阿合奇县| 灌南县| 常熟市| 永吉县| 河北省| 简阳市| 龙陵县| 尼木县| 黄石市| 合作市| 岫岩| 肥城市| 宝丰县| 荔波县| 唐海县| 通化县| 马关县| 苍南县| 南漳县| 金沙县| 朝阳县| 油尖旺区| 乌海市| 乌拉特中旗| 台北县| 新丰县| 隆安县| 永寿县| 南漳县| 虎林市| 宜兴市| 临高县| 祁门县| 镇平县|