ความแปรปรวนของ feature ใน PCA
ชุดข้อมูลปลามีทั้งหมด 6 มิติ แต่ มิติที่แท้จริง ของมันคือเท่าไร? สร้างกราฟแสดงความแปรปรวนของ feature ใน PCA เพื่อหาคำตอบ เช่นเดิม samples คืออาร์เรย์ 2 มิติ ที่แต่ละแถวแทนปลาหนึ่งตัว คุณต้องทำการ standardize feature ก่อน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Unsupervised Learning ใน Python
คำแนะนำการฝึกหัด
- สร้าง instance ของ
StandardScalerชื่อว่าscaler - สร้าง instance ของ
PCAชื่อว่าpca - ใช้ฟังก์ชัน
make_pipeline()เพื่อสร้าง pipeline ที่เชื่อมscalerและpcaเข้าด้วยกัน - ใช้เมธอด
.fit()ของpipelineเพื่อ fit กับข้อมูลปลาในsamples - ดึงจำนวน component ที่ใช้ผ่าน attribute
.n_components_ของpcaนำค่านี้ใส่ในฟังก์ชันrange()แล้วเก็บผลลัพธ์เป็นfeatures - ใช้ฟังก์ชัน
plt.bar()เพื่อพล็อตกราฟ explained variance โดยให้featuresอยู่บนแกน x และpca.explained_variance_อยู่บนแกน y
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Perform the necessary imports
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
import matplotlib.pyplot as plt
# Create scaler: scaler
scaler = ____
# Create a PCA instance: pca
pca = ____
# Create pipeline: pipeline
pipeline = ____
# Fit the pipeline to 'samples'
____
# Plot the explained variances
features = ____
plt.bar(____, ____)
plt.xlabel('PCA feature')
plt.ylabel('variance')
plt.xticks(features)
plt.show()