Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแสดง Kernel Density Estimation (KDE) ด้วย Seaborn ใน Python

Kernel Density Estimation (KDE) เป็นวิธีประมาณฟังก์ชันความหนาแน่นความน่าจะเป็น (PDF) ของตัวแปรสุ่มต่อเนื่อง ใช้วิเคราะห์ข้อมูล Non-parametric (ไม่สมมติการกระจายตัว)

ใน Seaborn สามารถแสดง KDE ได้ด้วยฟังก์ชัน distplot (เวอร์ชันเก่า) หรือ kdeplot (เวอร์ชันใหม่ แนะนำ) โดยตั้งค่า kde=True และ hist=False เพื่อแสดงเฉพาะเส้น KDE

ตัวอย่างโค้ด (ใช้ distplot - เวอร์ชันเก่า)


import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt

df = sb.load_dataset('iris')
sb.distplot(df['petal_length'], kde=True, hist=False)
plt.show()

ผลลัพธ์

วิธีแสดง Kernel Density Estimation (KDE) ด้วย Seaborn ใน Python

คำอธิบาย

  • นำเข้า pandas, seaborn, matplotlib

  • โหลดข้อมูล Iris ไปยัง DataFrame

  • ใช้ distplot กับคอลัมน์ 'petal_length'

  • ตั้งค่า kde=True (แสดง KDE) และ hist=False (ซ่อน Histogram)

  • แสดงกราฟ

หมายเหตุ: distplot ถูก Deprecated แล้วใน Seaborn เวอร์ชันใหม่ ควรใช้ kdeplot หรือ displot(kind='kde') แทน

ตัวอย่างแบบใหม่ (แนะนำ)


import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')
sns.kdeplot(data=df, x='petal_length', fill=True)
plt.show()

พารามิเตอร์สำคัญของ kdeplot:

  • bw_method / bw_adjust: ควบคุมความเรียบของเส้น KDE (Bandwidth)
  • fill=True: ทาสีพื้นที่ใต้เส้น
  • multiple: 'layer', 'stack', 'fill' สำหรับเปรียบเทียบหลายกลุ่ม