Mô tả
sklearn.datasets cung cấp các hàm tạo dữ liệu tổng hợp (synthetic) cho testing, demo, benchmark thuật toán ML.
1. make_blobs: Cụm Gaussian (Clustering)
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
# 200 samples, 3 centers, 2 features
X, y = make_blobs(n_samples=200, centers=3, cluster_std=1.0, n_features=2, random_state=42)
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=y, s=60, cmap='viridis', edgecolors='k')
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.title("make_blobs: 3 clusters")
plt.colorbar(label='Cluster')
plt.show()
2. make_circles: Hai vòng tròn đồng tâm (Non-linear)
from sklearn.datasets import make_circles
import matplotlib.pyplot as plt
X, y = make_circles(n_samples=100, noise=0.04, factor=0.3, random_state=42)
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap='winter', edgecolors='k')
plt.title("make_circles: 2 concentric circles")
plt.axis('equal')
plt.show()
3. Các dataset generator phổ biến khác
| Hàm | Mô tả | Tham số chính |
|---|---|---|
make_classification | Dữ liệu phân loại (n_classes, n_informative, n_redundant) | n_samples, n_features, n_classes |
make_regression | Dữ liệu hồi quy tuyến tính | n_samples, n_features, noise |
make_moons | Hai hình lưỡi liềm xen kẽ | n_samples, noise |
make_swiss_roll | Dữ liệu 3D cuộn (manifold learning) | n_samples, noise |
make_s_curve | Đường cong S 3D | n_samples, noise |
make_spd_matrix | Ma trận xác định dương | n_dim |
4. Load dataset thật (Real-world)
from sklearn.datasets import load_iris, load_digits, load_wine, load_breast_cancer # Iris (phân loại hoa) iris = load_iris() print(iris.data.shape) # (150, 4) print(iris.target_names) # ['setosa' 'versicolor' 'virginica'] # Digits (nhận dạng chữ số 8x8) digits = load_digits() print(digits.images.shape) # (1797, 8, 8)
5. Train/Test Split
from sklearn.model_selection import train_test_split
X, y = make_blobs(n_samples=200, centers=3, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
print(f"Train: {X_train.shape}, Test: {X_test.shape}")
Lưu ý: Code gốc có lỗi syntax centers= (thiếu giá trị). Đã sửa thành centers=3.