机器学习:Regression,第一个简单的示例,多项式回归
生活随笔
收集整理的這篇文章主要介紹了
机器学习:Regression,第一个简单的示例,多项式回归
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
# -*- coding: utf-8 -*-# 導(dǎo)入需要的庫
import numpy as np
import matplotlib.pyplot as plt# 定義存儲輸入數(shù)據(jù)x,目標(biāo)數(shù)據(jù)y
x,y = [],[]# 遍歷數(shù)據(jù)集,并把數(shù)據(jù)按照順序存在對應(yīng)的list# 在文件中遍歷,文件是一行一行的,每次讀取的是一行數(shù)據(jù)
for sample in open("_Data/prices.txt","r"):# 每一行,有兩個數(shù)據(jù),用逗號分開x_,y_ = sample.split(",")# 轉(zhuǎn)化為浮點(diǎn)數(shù)據(jù),x.append(float(x_))y.append(float(y_))# 獲取到數(shù)據(jù)之后,轉(zhuǎn)化為numpy數(shù)據(jù),因?yàn)樗麄兘?jīng)過優(yōu)化之后,計(jì)算特別快
x,y = np.array(x),np.array(y)# 標(biāo)準(zhǔn)化
x = (x-x.mean())/x.std()# 畫圖
plt.figure()
plt.scatter(x,y,c="g",s=6)
plt.show()#%%
# 這個模型得到是一個多項(xiàng)式的函數(shù),根據(jù)x0和多項(xiàng)式的函數(shù),畫出圖形
x0 = np.linspace(-2,4,100)# deg是多項(xiàng)式的參數(shù),準(zhǔn)確是多項(xiàng)式的階,np.polyfit是是fit之后的參數(shù),
# np.polyval根據(jù)參數(shù)和輸入x,求在計(jì)算的y,注意這里lamda的用法
def get_model(deg):return lambda input_x =x0:np.polyval(np.polyfit(x,y,deg),input_x)# 根據(jù)參數(shù)n,和輸入x,y求損失
def get_cost(deg,input_x,input_y):return 0.5*((get_model(deg)(input_x)-input_y)**2).sum()# 定義數(shù)據(jù)集
test_set = (1,4,10)
for degree in test_set:print(get_cost(degree,x,y))#%%
#畫出對應(yīng)的圖像
plt.scatter(x,y,c="g",s=20)
for degree in test_set:plt.plot(x0,get_model(degree)(),label="degree = {}".format(degree))# x,y軸區(qū)間限制,1e5,8e5 10^5,8*10^5
plt.xlim(-2,4)
plt.ylim(1e5,8e5)
# 顯示label
plt.legend()
plt.show()
測試結(jié)果
runfile(‘D:/share/test/repression.py’, wdir=‘D:/share/test’)

96732238800.35297
94112406641.67743
75874846680.09282

總結(jié)
以上是生活随笔為你收集整理的机器学习:Regression,第一个简单的示例,多项式回归的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python学习:numpy的使用技巧和
- 下一篇: 机器学习:贝叶斯分类器,朴素贝叶斯,拉普