Скачиваний:
0
Добавлен:
13.05.2026
Размер:
5.21 Кб
Скачать
import time
import random
import numpy as np
from scipy.optimize import minimize
from itertools import count
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches


#  Масштабирование параметров
def norm(arr):
    mini = np.min(arr)
    maxi = np.max(arr)
    for i in range(len(arr)):
        arr[i] = (arr[i] - mini) / (maxi - mini)
    return arr


with open("cancer.csv", encoding="cp1251") as f:
    lines = f.readlines()  # Считывание строк в один массив
# Выкинули заголовки в отдельный массив
headers = lines[0]
lines.pop(0)
headers = headers.replace('"', '')
headers = headers.split(",")  # Разделение строки по разделителям (запятые в данном случае)

# Преобразование в нормальный массив NumPy
for i in range(len(lines)):
    lines[i] = lines[i].split(",")  # Разделение строки по разделителям (запятые в данном случае)
lines[0][-1] = lines[0][-1][:-1]  # Стирание "\n" в конце строки с названиями столбцов
lines = np.asarray(lines)

# Параметры в отдельные переменные
diagnosis = lines[:, 1]
mean_area = lines[:, 5].astype(np.float64)
mean_symmetry = lines[:, 10].astype(np.float64)

mean_param = np.vstack([np.ones(len(mean_area)),mean_area, mean_symmetry])  # Все незав. параметры в одном массиве
norm_param = norm(mean_param)
th = np.asarray([0 for _ in range(len(norm_param))])

# График параметров
colour = []
y = []
for i in diagnosis:
    if i == "M":
        colour.append("r")
        y.append(0)
    else:
        colour.append("b")
        y.append(1)
y = np.asarray(y)

# Функции для спуска
def h(theta):   # Гипотеза, подаётся массив theta с размером (n, ) и массив x с размером (n, m)
    hypothesis = 1 / (1 + np.exp(-(norm_param.T @ theta)))
    return hypothesis

one = np.ones(len(y))
def J(theta):  # Подсчёт функции стоимости в матричном виде
    summ = np.sum(y.T @ np.log(h(theta)) + (one - y).T @ np.log(one - h(theta))) / len(y)
    return abs(summ)

def dJ(theta):  # Подсчёт дифференциала функции стоимости
    dif = (norm_param.T @ (h(theta) - y)) / len(diagnosis)
    return dif

# Метод градиентного спуска
hh = h(th)
j = J(th)
dj = dJ(th)

xline = np.array([0])
Jmass = np.array([j])
thetamass = np.copy(th)
k = 0
a = 0.01
# Первая итерация вручную
th = th - a * dj
thetamass = np.vstack([thetamass, th])
hh = h(th)
j = J(th)
dj = dJ(th)
Jmass = np.append(Jmass, j)
xline = np.append(xline, k)
k += 1


#while abs(Jmass[-1]-Jmass[-2]) >= 10**-11:
while k <= 50000:
    th = th - a * dj
    thetamass = np.vstack([thetamass, th])
    hh = h(th)
    j = J(th)
    dj = dJ(th)
    Jmass = np.append(Jmass, j)
    xline = np.append(xline, k)
    k += 1
    if k % 1000 == 0:
        print(f"Прошла {k / 1000}К -я итерация")
        print(f"Последняя ф-я стоимости: {Jmass[-1]}\n"
              f"Предпоследняя ф-я стоимости{Jmass[-2]}\n"
              f"Разница между ними: {Jmass[-1]-Jmass[-2]}")

print(xline.shape, thetamass.shape)
Badcancer = mpatches.Patch(color='red', label='Злокач-ая опухоль')
Goodcancer = mpatches.Patch(color='blue', label='Доброкач-ая опухоль')

plt.figure(1)
plt.scatter(mean_area, mean_symmetry, c=colour, alpha=0.5)
plt.legend(handles=[Badcancer, Goodcancer], loc='upper right', framealpha=0.5, frameon=True)
plt.title(r"График зависимости вида опухоли от площади и симметричности онной")
plt.ylabel(r"Симметричность")
plt.xlabel("Площадь")
plt.grid(which='major')
plt.minorticks_on()
plt.grid(which='minor', linestyle=':')

plt.figure(2)
plt.plot(xline, Jmass)
plt.title("Завимимость стоимости от итераций")
plt.title(r"Графики зависимости ф-ии стоимости от кол-ва итераций")
plt.ylabel(r"Ф-я стоимости")
plt.xlabel("Количество итераций")
plt.grid(which='major')
plt.minorticks_on()
plt.grid(which='minor', linestyle=':')

plt.figure(3)
plt.plot(xline, thetamass[:, 0], label=r"График $\theta_{0}$")
plt.plot(xline, thetamass[:, 1], label=r"График $\theta_{1}$")
plt.plot(xline, thetamass[:, 2], label=r"График ${\theta_2}$")
plt.legend(loc="right")
plt.title(r"Графики зависимостей ${\theta}$ от кол-ва итераций через град.спуск")
plt.ylabel(r"Параметры ${\theta}$")
plt.xlabel("Количество итераций")
plt.grid(which='major')
plt.minorticks_on()
plt.grid(which='minor', linestyle=':')
plt.show()
Соседние файлы в папке лабы