⚙️ На каждой итерации берёт один случайный пример из датасета и делает шаг в направлении уменьшения ошибки.
Дальше будем считать градиенты, а пока спать
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
w₁ — вес признака x₁
w₂ — вес признака x₂
w₀ — свободный член (смещение, пересечение, как вам удобно)
🧑💻 И вместе они задают уравнение плоскости, а в нашем случае — просто прямую на плоскости: x₁, x₂.‼️ Кстати, b мы итак можем определить чисто по графику, оно будет равно 3 (точка, где прямая пересекает ось)
w₁ = -3
w₂ = -2/3
w₀ = 1
Please open Telegram to view this post
VIEW IN TELEGRAM
x1, y1 = -3, 1
x2, y2 = 3, 5
delta_x = x2 - x1
delta_y = y2 - y1
# Ax + By + C = 0
A = delta_y
B = -delta_x
C = delta_x * y1 - delta_y * x1
w = [C, A, B]
x1, y1 = -3, 1
x2, y2 = 3, 5
delta_x = x2 - x1 # 6
delta_y = y2 - y1 # 4
# Ax + By + C = 0
A = delta_y # A = 4
B = -delta_x # B = -6
C = delta_x * y1 - delta_y * x1 #Будет равно 18
w = [C, A, B]
школьным образом
Please open Telegram to view this post
VIEW IN TELEGRAM
x1, y1 = -3, 5
x2, y2 = 7, 5
delta_x = x2 - x1
delta_y = y2 - y1
# Ax + By + C = 0
A = delta_y
B = -delta_x
C = delta_x * y1 - delta_y * x1
w = [C, A, B]
print(w)
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
1 3 2 2
Please open Telegram to view this post
VIEW IN TELEGRAM
x_test = [(5, -3), (-3, 8), (3, 6), (0, 0), (5, 3), (-3, -1), (-3, 3)]
... где x = [1, x₁, x₂] — вектор признаков (координат) объекта выборки, дополненный первой единицей для параметра w₀.
Скоро продолжим
Please open Telegram to view this post
VIEW IN TELEGRAM
w = np.array([-33, 9, 13]) # [свободный член, вес при x1, вес при x2]
a_sign = lambda x, w: -1 if np.dot(x, w) < 0 else 1
x_test_new = np.array([[1, x1, x2] for x1, x2 in x_test])
predict = [a_sign(x, w) for x in x_test_new]
Please open Telegram to view this post
VIEW IN TELEGRAM
🧑💻 ‼️ Для понимания, представьте обычную линейную комбинацию признаков:🔵 z = w₁ * x₁ + w₂ * x₂ + b🧑💻 Далее, мы прогоняем нашу линейную зависимость через сигмоиду:
🔵 σ(z) = 1 / 1 + e⁻ ᶻ🧑💻 Считаем функцию потерь (НО НЕ MSE, мы бы использовали логарифмическую функцию потерь, так как MSE, MAE это для регрессий).🧑💻 Далее обновляем веса с помощью любимого градиентного спуска и минимизируем Loss❓ Почему именно сигмоида? Как минимум, она переводит число в диапазон (0, 1)
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
Please open Telegram to view this post
VIEW IN TELEGRAM
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
# Функцмя возвращает Bunch объект (типа словаря). Этот объект содержит data.data — признаки (массив NumPy), data.target — метки (0 или 1), data.feature_names — названия признаков (столбцов)
X = pd.DataFrame(data.data, columns = data.feature_names)
y = pd.Series(data.target)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 1)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
Картиночку скоро повторим
Please open Telegram to view this post
VIEW IN TELEGRAM
Какой пост хотите следующим?
Anonymous Poll
62%
Продолжаем логистическую регрессию
38%
Продолжаем бинарную классификацию
1 4 3 3
model = LogisticRegression(max_iter = 1000)
👨💻 Вам нужно понимать одно: регуляризация штука интересная, нужна для 'защиты от переобучения модельки', и ,грубо говоря, она 'штрафует большие веса модели' — это все про L2, еще есть L1 (но обо всем потом)
model.fit(X_train_scaled, y_train)
y_pred = model.predict(X_test_scaled) #выдаст 0 или 1
print("Classification Report:\n", classification_report(y_test, y_pred))print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))🧑💻 Вот такой получится вывод для двух функций сверху
precision recall f1-score support
0 0.98 0.95 0.96 43
1 0.97 0.99 0.98 71
accuracy 0.97 114
macro avg 0.97 0.97 0.97 114
weighted avg 0.97 0.97 0.97 114
sns.heatmap(confusion_matrix(y_test, y_pred), annot=True, fmt='d', cmap='Blues')
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title("Confusion Matrix")
plt.show()
Please open Telegram to view this post
VIEW IN TELEGRAM
import numpy as np
x_test = [(5, -3), (-3, 8), (3, 6), (0,0), (5, 3), (-3, -1), (-3, 3)]
w = np.array([-33, 9, 13])
a_sign = lambda x, w: -1 if np.dot(x, w) < 0 else 1
x_test_new = np.array([[1, x1, x2] for x1, x2 in x_test])
predict = [a_sign(x, w) for x in x_test_new]
wᵀ * x ≥ 0
wᵀ * x < 0
Мы уже имеем метки по ТЗ:
x_test = [(5, -3), (-3, 8), (3, 6), (0, 0), (5, 3), (-3, -1), (-3, 3)]
predict=[−1, +1, +1, −1, +1, −1, −1]
Please open Telegram to view this post
VIEW IN TELEGRAM
1 5 5 4 2