python與機器學習入門

1、Anaconda的安裝與使用。

2、第一個機器學習樣例:

(1.3.1 獲取與處理數據)

#導入需要用到的庫
import numpy as np
import matplotlib.pyplot as plt

#定義存儲輸入數據(x)和目標數據(y)的數組
x,y=[],[]
#遍歷數據集,變量sample對應的正是一個個樣本
for sample in open("D:/1/_Data/prices.txt","r"):   #“/”相對路徑
#for sample in open("D:\\1\\_Data\\prices.txt","r"):  #"\\"絕對路徑
#由於數據是用逗號隔開的,所以調用python中的split方法並將逗號作爲參數傳入
    _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()


上面這段代碼的運行結果如圖1.9所示。

圖1.9  預處理後的數據散點圖

(1.3.2  選擇與訓練模型)

#在(-2,4)這個區間上取100個點作爲畫圖的基礎
x0 = np.linspace(-2,4,100)
#利用Numpy的函數定義訓練並返回多項式迴歸的函數
#deg參數代表着模型參數中的n,亦即模型中的多項式的次數
#返回的模型能夠根據輸入的x(模型是x0),返回相應的預測的y
def get_model(deg):

    return lambda input_x=x0:np.polyval(np.polyfit(x,y,deg),input_x)

(1.3.3  評估與可視化結果)

#根據參數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 d in test_set:
    #輸出相應的損失
    print(get_cost(d,x,y))
    
#畫出相應的圖像
plt.scatter(x,y,c="g",s=20)
for d in test_set:
    plt.plot(x0,get_model(d)(),label="degree={}".format(d))
#將橫軸、縱軸的範圍分別限制在(-2,4)、(10^5,8*10^5)
plt.xlim(-2,4)
plt.ylim(1e5,8e5)
#調用legend方法使曲線對應的label正確顯示
plt.legend()
plt.show()




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章