1. ទំព័រដើម
  2. Data Science Roadmap
  3. ជំហានទី ៥
Data Science Roadmap · ជំហានទី ៥ នៃ ៦ (Python 🐍 & R 📊)

Machine Learning & AI

បង្ហាត់ និងវាយតម្លៃម៉ូដែល Machine Learning (Linear Regression, Classification, K-Means Clustering) ដោយ Scikit-learn និង R ។

១. Train / Test Split និង Linear Regression

ដើម្បីកុំឱ្យម៉ូដែល «ទន្ទេញចាំ» (Overfitting) ត្រូវបែងចែកទិន្នន័យជា Training set (80%) និង Test set (20%) មុននឹងបង្ហាត់ Linear Regression \(\hat{y} = \beta_0 + \beta_1 x\) ៖

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

X = np.array([[1], [2], [3], [4], [5]])
y = np.array([50, 60, 70, 80, 90])
model = LinearRegression().fit(X, y)
pred = model.predict([[6]])
print('Intercept:', round(model.intercept_, 2), '| Slope:', round(model.coef_[0], 2))
print('Predict for 6 hrs:', round(pred[0], 2))
Intercept: 40.0 | Slope: 10.0 Predict for 6 hrs: 100.0
df <- data.frame(hours = 1:5, score = c(50, 60, 70, 80, 90))
model <- lm(score ~ hours, data = df)
print(coef(model))
pred <- predict(model, newdata = data.frame(hours = 6))
cat('Predict for 6 hrs:', pred, '\n')
(Intercept) hours 40 10 Predict for 6 hrs: 100

២. Classification (Logistic Regression & Decision Tree / Random Forest)

សម្រាប់ទស្សន៍ទាយប្រភេទ (ឧ. ជាប់ = 1 ឬ ធ្លាក់ = 0) គេប្រើ Logistic Regression ឬ Random Forest ហើយវាស់ដោយ Confusion Matrix, Accuracy, F1-score ៖

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score

X = [[2], [3], [4], [5], [6], [7], [8]]
y = [0, 0, 1, 0, 1, 1, 1]
clf = LogisticRegression(penalty=None).fit(X, y)
preds = clf.predict(X)
prob = clf.predict_proba([[5.5]])[0, 1]
print('P(pass at 5.5h):', round(prob, 3), '-> Class:', clf.predict([[5.5]])[0])
print('Accuracy:', round(accuracy_score(y, preds), 3), '| F1:', round(f1_score(y, preds), 3))
P(pass at 5.5h): 0.78 -> Class: 1 Accuracy: 0.714 | F1: 0.75
df <- data.frame(hours = c(2,3,4,5,6,7,8), pass = c(0,0,1,0,1,1,1))
clf <- glm(pass ~ hours, data = df, family = binomial())
prob <- predict(clf, newdata = data.frame(hours = 5.5), type = 'response')
cat('P(pass at 5.5h) =', round(prob, 3), '-> Class:', ifelse(prob >= 0.5, 1, 0), '\n')
P(pass at 5.5h) = 0.78 -> Class: 1

៣. Unsupervised Learning ៖ K-Means Clustering

ពេលគ្មានស្លាកចម្លើយ (Unlabeled Data) ក្បួន K-Means បែងចែកទិន្នន័យជា \(K\) ក្រុមស្វ័យប្រវត្តិ (ឧ. ចែកកម្រិតសមត្ថភាពសិស្សជា ២ ក្រុម) ៖

import numpy as np
from sklearn.cluster import KMeans

X = np.array([[45, 50], [50, 52], [88, 90], [92, 95]])
km = KMeans(n_clusters=2, n_init=10, random_state=42).fit(X)
print('Cluster labels:', km.labels_)
print('Centers:\n', km.cluster_centers_)
Cluster labels: [0 0 1 1] Centers: [[47.5 51. ] [90. 92.5]]
X <- matrix(c(45, 50, 88, 92, 50, 52, 90, 95), ncol = 2)
set.seed(42)
km <- kmeans(X, centers = 2, nstart = 10)
cat('Cluster labels:', km$cluster, '\n')
print(km$centers)
Cluster labels: 1 1 2 2 [,1] [,2] 1 47.5 51.0 2 90.0 92.5

📝 លំហាត់អនុវត្ត (Python & R)

លំហាត់ទី ១ ៖ គណនា Accuracy និង F1-Score ពី Confusion Matrix

ម៉ូដែល Classification ទទួលបាន \(TP = 40,\ FP = 10,\ FN = 10,\ TN = 40\)។ ចូរគណនា Accuracy, Precision, Recall និង F1-score ។

▸ បើកមើលដំណោះស្រាយ (គណិតវិទ្យា + Python & R)

គណិតវិទ្យា៖ \(\text{Acc}=\frac{80}{100}=0.80\), \(\text{Prec}=\frac{40}{50}=0.80\), \(\text{Rec}=\frac{40}{50}=0.80\), \(F_1=\frac{2(0.8)(0.8)}{0.8+0.8}=0.80\) ។

tp, fp, fn, tn = 40, 10, 10, 40
acc = (tp + tn) / (tp + fp + fn + tn)
prec = tp / (tp + fp); rec = tp / (tp + fn)
f1 = 2 * prec * rec / (prec + rec)
print(f'Acc={acc:.2f}, Prec={prec:.2f}, Rec={rec:.2f}, F1={f1:.2f}')
Acc=0.80, Prec=0.80, Rec=0.80, F1=0.80
tp <- 40; fp <- 10; fn <- 10; tn <- 40
acc <- (tp + tn) / (tp + fp + fn + tn)
prec <- tp / (tp + fp); rec <- tp / (tp + fn)
f1 <- 2 * prec * rec / (prec + rec)
cat(sprintf('Acc=%.2f, Prec=%.2f, Rec=%.2f, F1=%.2f\n', acc, prec, rec, f1))
Acc=0.80, Prec=0.80, Rec=0.80, F1=0.80
លំហាត់ទី ២ ៖ គណនា RMSE នៃ Linear Regression

តម្លៃពិត \(y = [10, 20, 30]\) និងតម្លៃទស្សន៍ទាយ \(\hat{y} = [12, 18, 33]\)។ រក \(\text{RMSE} = \sqrt{\frac{1}{n}\sum (y_i - \hat{y}_i)^2}\) ។

▸ បើកមើលដំណោះស្រាយ (គណិតវិទ្យា + Python & R)

គណិតវិទ្យា៖ កំហុស \([-2, 2, -3]\), ការេ \([4, 4, 9]\) ផលបូក \(= 17\), \(\text{RMSE}=\sqrt{17/3}\approx 2.3805\) ។

import numpy as np
y, yhat = np.array([10, 20, 30]), np.array([12, 18, 33])
rmse = np.sqrt(np.mean((y - yhat)**2))
print('RMSE =', round(rmse, 4))
RMSE = 2.3805
y <- c(10, 20, 30); yhat <- c(12, 18, 33)
rmse <- sqrt(mean((y - yhat)^2))
cat('RMSE =', round(rmse, 4), '\n')
RMSE = 2.3805