調整 n_neighbors
n_neighbors 是 KNN 最關鍵的參數。當你不確定資料集中離群值的數量(這種情況很常見)時,就不能套用經驗法則(污染率低於 10% 時使用 20 個鄰居)。
在這類情況下,你需要調整 n_neighbors。請在上一個練習的 females 資料集的轉換版本上練習這個流程。它已載入為 females_transformed。KNN 估計器、evaluate_outlier_classifier 與 evaluate_regressor 函式也都已載入。
以下是函式內容供你複習:
def evaluate_outlier_classifier(model, data, threshold=.75):
model.fit(data)
probs = model.predict_proba(data)
inliers = data[probs[:, 1] <= threshold]
return inliers
def evaluate_regressor(inliers):
X, y = inliers.drop("weightkg", axis=1), inliers[['weightkg']]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=10, train_size=0.8)
lr = LinearRegression()
lr.fit(X_train, y_train)
preds = lr.predict(X_test)
rmse = root_mean_squared_error(y_test, preds)
return round(rmse, 3)
本練習屬於課程
Python 中的異常偵測
練習說明
- 建立一個
n_neighbors的候選值清單,依序為:5、10、20。 - 在迴圈中以當前的
k作為n_neighbors,實例化一個KNN模型。 - 使用
evaluate_outlier_classifier函式找出內點。 - 使用
evaluate_regressor計算 RMSE,並將結果存入scores,其中鍵為k、值為對應的 RMSE。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a list of values for n_neigbors
n_neighbors = [____, ____, ____]
scores = dict()
for k in n_neighbors:
# Instantiate KNN with the current k
knn = ____(____, n_jobs=-1)
# Find the inliers with the current KNN
inliers = ____(____, ____, .50)
# Calculate and store RMSE into scores
scores[____] = ____
print(scores)