Lasso 模型結果
現在你已經訓練好 Lasso 模型,接著要在測試集上評分其預測能力($R^2$),並計算有多少特徵因係數被縮減為 0 而被忽略。
X_test 與 y_test 資料集已為你預先載入。
Lasso() 模型與 StandardScaler() 分別以 la 和 scaler 建立,且兩者皆已對訓練資料完成擬合。
本練習屬於課程
Python 的降維
練習說明
- 使用已預先擬合的 scaler 來轉換測試集。
- 在縮放後的測試資料上計算 \(R^2\) 值。
- 建立一個清單:當係數等於 0 時為 True。
- 計算係數為 0 的特徵總數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Transform the test set with the pre-fitted scaler
X_test_std = scaler.____
# Calculate the coefficient of determination (R squared) on X_test_std
r_squared = la.____(____, ____)
print(f"The model can predict {r_squared:.1%} of the variance in the test set.")
# Create a list that has True values when coefficients equal 0
zero_coef = la.____ == ____
# Calculate how many features have a zero coefficient
n_ignored = sum(____)
print(f"The model has ignored {n_ignored} out of {len(la.coef_)} features.")