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

96732238800.35297
94112406641.67743
75874846680.09282

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