

Preview text:
lOMoAR cPSD| 58778885 Tên: Biện Công Tân MSSV: 22146216
Homework 3: Classification Data Points using Random Forest (n- classes) import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
def generate_spiral_data(n_points, n_classes): X = [] y = [] for j in range(n_classes):
ix = range(n_points*j, n_points*(j+1))
r = np.linspace(0.0, 1, n_points) # bán kính từ 0 đế0n 1
t = np.linspace(j*4, (j+1)*4, n_points) + np.random.randn(n_points)*0.2 # góc xoắ0n + noise x1 = r * np.sin(t * 2.5) x2 = r * np.cos(t * 2.5) X.extend(np.c_[x1, x2]) y.extend([j]*n_points)
return np.array(X), np.array(y)
# Nhập số0 lớp từ người dùng
n_classes = int(input("Nhập số0 lớp phân loại: "))
n_points = 200 # số0 điế@m mốAi lớp
X, y = generate_spiral_data(n_points, n_classes) #
Tạo mố hình Random Forest với 10,000 cây, độ sâu 20
model = RandomForestClassifier(n_estimators=10000, max_depth=5050, random_state=42)
model.fit(X, y) y_pred = model.predict(X)
print("Độ chính xác trến tập dữ liệu gố0c:", accuracy_score(y, y_pred))
# Vẽ biế@u đốK phân lớp
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 500), np.linspace(y_min, y_max, 500))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape)
plt.figure(figsize=(10, 8)) plt.contourf(xx, yy, Z, alpha=0.3)
colors = ['navy', 'cyan', 'yellow', 'brown', 'green', 'magenta', 'orange', 'red', 'blue', 'purple'] for i in range(n_classes):
plt.scatter(X[y == i, 0], X[y == i, 1], s=20, color=colors[i % len(colors)],
label=f'Lớp {i}', edgecolor='k') plt.title(f'Random Forest Classification (số0 lớp
= {n_classes})') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.legend() plt.show() KẾT QUẢ lOMoAR cPSD| 58778885
Kết quả minh chứng n = 4, độ chính xác 99,6%
Kết quả minh chứng n = 5, độ chính xác 99,6%