1. 程式人生 > 其它 >Task03:K近鄰的實踐1--阿里雲天池

Task03:K近鄰的實踐1--阿里雲天池

技術標籤:機器學習

分類鳶尾花圖片:

#Demo來自sklearn官網
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsRegressor
np.random.seed(0)
# 隨機生成40個(0, 1)之前的數,乘以5,再進行升序
X = np.sort(5 * np.random.rand(40, 1), axis=0)
# 建立[0, 5]之間的500個數的等差數列, 作為測試資料
T = np.linspace(0, 5, 500)[:, np.newaxis]
# 使用sin函式得到y值,並拉伸到一維
y = np.sin(X).ravel() # Add noise to targets[y值增加噪聲] y[::5] += 1 * (0.5 - np.random.rand(8))
# #############################################################################
# Fit regression model
# 設定多個k近鄰進行比較
n_neighbors = [1, 3, 5, 8, 10, 40]
# 設定圖片大小
plt.figure(figsize=(10,20))
for i, k in enumerate
(n_neighbors): # 預設使用加權平均進行計算predictor clf = KNeighborsRegressor(n_neighbors=k, p=2, metric="minkowski") # 訓練 clf.fit(X, y) # 預測 y_ = clf.predict(T) plt.subplot(6, 1, i + 1) plt.scatter(X, y, color='red', label='data') plt.plot(T, y_, color='navy', label=
'prediction') plt.axis('tight') plt.legend() plt.title("KNeighborsRegressor (k = %i)" % (k)) plt.tight_layout() plt.show()