import torch
from sklearn.metrics import accuracy_score
import numpy as np
from matplotlib import pyplot as plt
______________________________________________
def sigmoid(x):
# Функция активации sigmoid:: f(x) = 1 / (1 + e^(-x))
return 1 / (1 + np.exp(-x))
__________________________________________________________
def deriv_sigmoid(x):
# Производная от sigmoid: f'(x) = f(x) * (1 - f(x))
fx = sigmoid(x)
return fx * (1 - fx)
____________________________________________________________
def mse_loss(y_pred, y): # функция потерь
y_pred = y_pred.reshape(-1, 1)
y = np.array(y).reshape(-1, 1)
return 0.5 * np.mean((y_pred - y) ** 2)
___________________________________________________________
class Perceptron_Sigmoid:
def __init__(self, w=None, b=0):
self.w = w
self.b = b
def activate(self, x):
return np.array(sigmoid(x))
def forward(self, X): # прямой проход
y_pred = np.zeros((X.shape[0],1)) # инициализируем нулями ответы
y_pred = self.activate(X @ self.w.reshape(X.shape[1],1)+self.b) # выполняем прямой проход
return y_pred.reshape(-1,1)
def backward(self, X, y, y_pred, learning_rate=0.005): # обратный проход
n = X.shape[0]
y = np.array(y).reshape(-1,1)
dw = (1/n) * X.T @ (y_pred - y) * y_pred * (1 - y_pred)#неправильно!!!
db = (1/n) * np.sum((y_pred - y) * y_pred * (1 - y_pred))#неправильно!!!
self.w -= learning_rate*dw
self.b -= learning_rate*db
def fit(self, X, y, num_epochs=5000):
self.w = np.zeros((X.shape[1], 1)) # вектор весов
self.b = 0 # смещение
loss_values = [] # значения функции потерь на различных итерациях обновления весов
for i in range(num_epochs):
y_pred = self.forward(X)
loss_values.append(mse_loss(y_pred,y))
self.backward(X,y,y_pred)
return np.array(loss_values)
________________________________________________________________
rng = np.random.default_rng()
data_0 = np.concatenate([rng.normal((-1, -1), 1, (500, 2)), np.zeros((500, 1))], axis=1) # сэмплируем нули
data_1 = np.concatenate([rng.normal((1, 1), 1, (500, 2)), np.ones((500, 1))], axis=1) # сэмплируем единицы
_______________________________________________________________
def random_mix(X_1, X_2): # перемешиваем
c = np.concatenate((X_1, X_2))
np.random.shuffle(c)
return c
______________________________________________________________
data = random_mix(data_0, data_1) # получаем наш набор данных
data
__________________________________________________________
X = data[:, [0, 1]] # обучающая выборка
y = data[:, [2]] # целевая переменная
____________________________________________________________
perceptron = Perceptron_Sigmoid()
losses = perceptron.fit(X,y)
ValueError: operands could not be broadcast together with shapes (2,1) (1000,1)
---> 19 dw = (1/n) * X.T @ (y_pred - y) * y_pred * (1 - y_pred)
20 db = (1/n) * np.sum((y_pred - y) * y_pred * (1 - y_pred))