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
Please open Telegram to view this post
VIEW IN TELEGRAM
CodeLab
Друзья, у админа сессия, так что пока держите мем 👨💻
Media is too big
VIEW IN TELEGRAM
Фотка задания в комментах
Отступ (или margin или γ или M) — все это, так или иначе, относится к отступу.
🔵 Показывает margin насколько уверенно модель классифицировала точку а также, с какой стороны от разделяющей прямой она находится.
Please open Telegram to view this post
VIEW IN TELEGRAM
import numpy as np
w = np.array([15/7, -9/7, -1]) # [w0, w1, w2]
x_test = np.array([
(1, -8, -4),
(1, -2, 2),
(1, 4, 8),
(1, 6, 3)
])
y_test = np.sign(x_test @ w.T)
🔵 w — вектор весов: w = [w₀, w₁, w₂]🔵 xᵢ — вектор признаков: xᵢ = [1, x₁, x₂]🔵 w * xᵢ — это то, насколько объект далеко от прямой
margin = x_test @ w.T * y_test #Все по формуле
import numpy as np
w = np.array([15/7, -9/7, -1])
x_test = np.array([
(1, -8, -4),
(1, -2, 2),
(1, 4, 8),
(1, 6, 3),
])
y_test = np.sign(x_test @ w.T)
margin = x_test @ w.T * y_test
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
Скажу сразу, что получилось у меня:
import numpy as np
w = np.array([-16, -4, 9])
x_test = np.array([
[1, -5, 2],
[1, -4, 6],
[1, 3, 2],
[1, 3, -3],
[1, 5, 6],
[1, 9, 2]
])
y_test = np.array([1, 1, 1, -1, -1])
y_test = np.sign(x_test @ w.T)
#y_test = np.array([1, 1, -1, -1, 1]) — А такой ответ не подойдет
margin = x_test @ w * y_test #Скалярное произведение
print(margin)
‼️ Чем больше отступ, тем увереннее классификация.🔵 В нашем случае, в точках 3 и 5 наша модель опростоволосилась
‼️ Сама формула🟰 margin — Mᵢ = wᵀ * xᵢ🟰 — это просто скалярное произведение между весами (это наши параметры в начале кода) и x-объектами (это и есть наши 6 точек).🔵 y_test — целевые значения. Говорит нам о том, каким должен быть знак margin, если классификация верная.
‼️ Вот как работает главная формула нашего кода:
w = np.array([-16, -4, 9])
x_test[0] = [1, -5, 2]
M₁ = (-16) * 1 + (-4) * (-5) + 9 * 2 = -16 + 20 + 18 = 22
y₁ = 1
margin₁ = 22 * 1 = 22
import numpy as np
w = np.array([-16, -4, 9])
x_test = np.array([
[1, -5, 2],
[1, -4, 6],
[1, 3, 2],
[1, 3, -3],
[1, 5, 6],
[1, 9, 2]
])
y_test = np.array([1, 1, 1, -1, -1, -1])
# y_test = np.sign(x_test @ w.T)
# print(y_test)
margin = x_test @ w * y_test
🔗 Ссылка на курс 🔗
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
import numpy as np
x_test = np.array([(-5, 2), (-4, 6), (3, 2), (3, -3), (5, 5), (5, 2), (-1, 3)])
y_test = np.array([1, 1, 1, -1, -1, -1, -1])
w = np.array([-8/3, -2/3, 1])
X = np.column_stack((np.ones(len(x_test)), x_test))
[[ 1. -5. 2.]
[ 1. -4. 6.]
[ 1. 3. 2.]
...
margin = y_test * (X @ w)
Q = np.sum(margin < 0)
print(int(Q))
Q = 2
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
import numpy as np
import matplotlib.pyplot as plt
x_train = [
[10, 50], [20, 30], [25, 30], [20, 60], [15, 75],
[40, 40], [30, 45], [20, 45], [40, 30], [7, 36]
]
x_train = [x + [1] for x in x_train]
умножений и тд.
x_train = np.array(x_train)
y_train = np.array([-1, 1, 1, -1, -1, 1, 1, -1, 1, 1])
sumvec = np.sum([x * y for x, y in zip(x_train, y_train)], axis = 0)
Please open Telegram to view this post
VIEW IN TELEGRAM
sumvec = np.sum([x * y for x, y in zip(x_train, y_train)], axis=0)
xxt = np.sum([np.outer(x, x) for x in x_train], axis=0)
x = [10, 50, 1]
np.outer(x, x) =
[[100, 500, 10],
[500, 2500, 50],
[10, 50, 1]]
w = np.dot(sumvec, np.linalg.inv(xxt))
print("Вектор весов w:", w.round(3))
line_x = np.linspace(0, 45, 100)
line_y = -(w[0] * line_x + w[2]) / w[1]
x_pos = x_train[y_train == 1]
x_neg = x_train[y_train == -1]
Визуализацию продолжим позже (PART 3 SOON)
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
CodeLab
🧑💻Разбираем код
🌷🔤🔤🔤
‼️ Ситуация примерно та же: нужно посчитать количество неправильно классифицированных объектов. Помимо этого, докрутим для кода визуал.
1⃣ Библиотеки:
import numpy as np
import matplotlib.pyplot as plt
2⃣ Теперь наши данные:
x_train…
🌷🔤🔤🔤
‼️ Ситуация примерно та же: нужно посчитать количество неправильно классифицированных объектов. Помимо этого, докрутим для кода визуал.
1⃣ Библиотеки:
import numpy as np
import matplotlib.pyplot as plt
2⃣ Теперь наши данные:
x_train…