開始使用免費開始

使用 PCA

在這個練習中,你將對 wine 資料集套用 PCA,看看是否能提升模型的準確率。

本練習屬於課程

Python 的 Machine Learning 前處理

檢視課程

練習說明

  • 建立一個 PCA 物件。
  • wine 中定義特徵(X)與標籤(y),標籤使用 "Type" 欄位。
  • 將 PCA 套用到 X_trainX_test,確保沒有資料外洩,並將轉換後的值分別儲存為 pca_X_trainpca_X_test
  • 列印 pca.explained_variance_ratio_ 屬性,檢查每個主成分解釋的變異比例。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Instantiate a PCA object
pca = ____()

# Define the features and labels from the wine dataset
X = wine.drop(____, ____)
y = wine["Type"]

X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)

# Apply PCA to the wine dataset X vector
pca_X_train = ___.____(____)
pca_X_test = ___.____(____)

# Look at the percentage of variance explained by the different components
print(____)
編輯並執行程式碼