TGTGInsighttelegram intelligenceLIVE / telegram public index
← ML Baldini • Nikita Boyandin
ML Baldini • Nikita Boyandin avatar

TGINSIGHT POST

Post #307

@ml_baldini

ML Baldini • Nikita Boyandin

Görüntülemeler1,950Gönderi görüntüleme sayısı
Yayınlandı3 Eki03.10.2025 13:02
İçerik

Gönderi içeriği

ML алгоритмы: градиентная боль😱 Самая большая боль всех вкатывальщиков в условные Тындекс - это алгоритмическая секция. Задачи про найти что то в массиве, сумма или наименьший путь отпугивают многих. А что если введут ML алгоритмы в собесы? 🟢MLcode easy: KNN, MSE, accuracy class KNNClassifier(): def __init__(self, n_neighbors=3, metric='euclidean', weights = 'uniform'): self.k = n_neighbors self.metric = metric self.weights = weights self.distance = { 'euclidean': lambda x, y: np.linalg.norm(x - y), 'manhattan': lambda x, y: np.sum(np.abs(x - y)), }[metric] def fit(self, X, y): self.X = X self.y = y def predict(self, X): predictions = [] for x in X: distances = np.array([self.distance(x, y) for y in self.X]) k_nearest_neighbors = self.y[distances.argsort()[:self.k]] if self.weights == 'distance': k_weights = np.array([1 / (distance + 1E-15) for distance in np.sort(distances)[:self.k]]) #distances[distances.argsort()[:self.k]] k_weights = k_weights / np.sum(k_weights) predictions.append(np.argmax(np.bincount(k_nearest_neighbors, weights = k_weights))) elif self.weights == 'uniform': predictions.append(np.argmax(np.bincount(k_nearest_neighbors))) class MSE: def __call__(self, y_pred, y_true): return np.sum((y_true - y_pred) ** 2) / y_true.size def grad(self, y_pred, y_true): return -2 * (y_true - y_pred) / y_true.size def accuracy(targets, predictions): return np.equal(targets, predictions).mean() Тут можно найти все базовые алгоритмы из классики: https://github.com/AkiRusProd/basic-ml-algorithms 🟡MLcode medium: градиентный спуск class Neuron(object): def __init__(self, weights, bias): self.weights = weights self.bias = bias def forward(self, inputs): return inputs @ self.weights + self.bias class MSELoss: def forward(self, y_pred, y_true): return 1/len(y_true)*((y_pred - y_true) ** 2).sum() def backward(self, y_pred, y_true): # dL/dy~ self.dypred = 2/len(y_true)*(y_pred - y_true) return self.dypred def gradient_descent(neuron, inputs, y_true, learning_rate=0.01, epochs=100): loss_fn = MSELoss() for _ in range(epochs): # Прямое распространение y_pred = neuron.forward(inputs) # Вычисление функции потерь loss = loss_fn.forward(y_pred, y_true) # Обратное распространение dypred = loss_fn.backward(y_pred, y_true) # Градиенты для весов и смещения dw = inputs.T @ dypred db = dypred.sum() # Обновление параметров neuron.weights -= learning_rate * dw neuron.bias -= learning_rate * db print(f"Epoch: {_}, Loss: {loss}") return neuron 🔴MLcode hard: механизм Attention import numpy as np def softmax(x): exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True)) return exp_x / np.sum(exp_x, axis=-1, keepdims=True) class Attention: def __init__(self, d_model): self.d_model = d_model def forward(self, Q, K, V): # Q, K, V: матрицы запросов, ключей и значений (batch_size, seq_len, d_model) # Вычисляем скалярное произведение Q и K^T scores = np.matmul(Q, K.transpose(0, 2, 1)) / np.sqrt(self.d_model) # Применяем softmax для получения весов внимания attention_weights = softmax(scores) # Умножаем веса на V, чтобы получить итоговый выход output = np.matmul(attention_weights, V) return output, attention_weights batch_size, seq_len, d_model = 2, 3, 4 Q = np.random.randn(batch_size, seq_len, d_model) K = np.random.randn(batch_size, seq_len, d_model) V = np.random.randn(batch_size, seq_len, d_model) attention = Attention(d_model=d_model) output, weights = attention.forward(Q, K, V) print("Attention output shape:", output.shape) print("Attention weights shape:", weights.shape)