Скачиваний:
0
Добавлен:
13.05.2026
Размер:
6.37 Кб
Скачать
import os
clear = lambda: os.system('cls')
clear()
import math
import random
import numpy as np
import matplotlib.pyplot as plt

all_data = [[],[],[]]
headings = []
count = 0
i = 0
j = 0
m = 0
b = 0

#Функция расчёта гипотезы
def hypothesis(x, theta, count):
h = []
i = 0
while i != count:
tmp = 0
tmp += float((1/(1+math.exp(-(theta[0]+theta[1]*x[i][0]+theta[2]*x[i][1])))))
h.append(tmp)
i += 1
i = 0
return h

#Функция расчёта функции стоимости
def J(y, count):
cost = 0
i = 0
tmp = 0
H = hypothesis(parameters, theta, count)
while i != count:
tmp += y[i][0]*math.log(H[i])+(1-y[i][0])*math.log(1-H[i])
i += 1
cost += (-1)*tmp/count
return(cost)

#Функция расчёта производных функции стоимости
def diff_J(x, y, count):
dJ = [0, 0, 0]
H = hypothesis(parameters, theta, count)
i = 0
tmp1 = 0
tmp2 = 0
tmp3 = 0
while i != count:
tmp1 += (H[i]-y[i][0])*1
tmp2 += (H[i]-y[i][0])*x[i][0]
tmp3 += (H[i]-y[i][0])*x[i][1]
i += 1
i = 0
dJ[0] = tmp1/count
dJ[1] = tmp2/count
dJ[2] = tmp3/count
return dJ

#Функция вычисления линии определения
def line_graf(th1,th2,th3,x1):
res = (-1*(th1 + th2*x1))/th3
return res

#Считывание данных из файла
f = open('cancer.csv', mode='r', encoding='cp1251')
for line in f:
if count == 0:
headings.extend(line.split(','))
elif count > 0:
tmp = line.split(',')
all_data[0].append(float(tmp[5]))
all_data[1].append(float(tmp[10]))
all_data[2].append(tmp[1])
count += 1
f.close()
count -= 1

#Разделение входных данных на матрицу параметров и матрицу результатов
parameters = np.zeros(count*2, dtype=np.float16)
parameters.shape = (count, 2)
result = np.zeros(count*1, dtype=np.int16)
result.shape = (count, 1)

while i != count:
parameters[i][0] = all_data[0][i]
parameters[i][1] = all_data[1][i]
if all_data[2][i] == "M":
result[i][0] = 1
elif all_data[2][i] == "B":
result[i][0] = 0
i +=1
i = 0

#Построение графика зависимости диагноза от двух параметров
plt.figure(1)
##Отображение точек разными цветами
while i != count:
if m == 1 and result[i][0] == 1:
plt.scatter(parameters[i][0], parameters[i][1], c="b")
elif b == 1 and result[i][0] == 0:
plt.scatter(parameters[i][0], parameters[i][1], c="r")
elif m == 0 and result[i][0] == 1:
plt.scatter(parameters[i][0], parameters[i][1], c="b", label="M (злокачественная)")
m += 1
elif b == 0 and result[i][0] == 0:
plt.scatter(parameters[i][0], parameters[i][1], c="r", label="B (доброкачественная)")
b += 1
i += 1
i = 0
m = 0
b = 0

#Нормирование значений параметров
x_mx = np.max(parameters, 0)
x_mn = np.min(parameters, 0)
x_sub= []
x_sub.append(x_mx[0] - x_mn[0])
x_sub.append(x_mx[1] - x_mn[1])
left_border = 0
right_border = 1

##Замена исходных параметров на нормированные
while i != count:
parameters[i][0] = left_border + ((parameters[i][0] - x_mn[0])/x_sub[0])*(right_border - left_border)
parameters[i][0] = left_border + ((parameters[i][0] - x_mn[1])/x_sub[1])*(right_border - left_border)
i += 1
i = 0

#Вычисление первых значений коэффициентов гипотезы
theta = [random.random(), random.random(), random.random()]

#Градиентный спуск
##Необходимые переменные
alpha = 0.01
iter_number = 0
iter_number_arr = [iter_number]
cost_func = J(result, count)
cost_func_arr = [cost_func]
TH = [[theta[0]], [theta[1]], [theta[2]]]
sub = 1
##Алгоритм градиентного спуска
while sub >= 10**-7: #iter_number <= 50000:
tmp = 0
tmp = cost_func

df_j = diff_J(parameters, result, count)
while j != 3:
theta[j] = theta[j] - alpha*df_j[j]
TH[j].append(theta[j])
j += 1
j = 0

cost_func = J(result, count)
cost_func_arr.append(cost_func)
sub = tmp - cost_func

iter_number += 1
iter_number_arr.append(iter_number)

#Построение графиков
##График двух параметром и границы определения
y_2 = 0
x_2 = line_graf(theta[0],theta[2],theta[1],y_2)
x_2 = x_2*x_sub[0] + x_mn[0]
plt.figure(1)
plt.plot([x_mn[0],x_2], [x_mx[1],y_2], c="g", label="Граница определения")
###Добавление подписей осям
plt.xlabel("Средняя площадь")
plt.ylabel("Средняя симметрия")
###Добавление более частой сетки
plt.grid(which='major')
plt.minorticks_on()
plt.grid(which='minor', linestyle=':')
plt.tight_layout()
###Добавление легенды
plt.legend(loc='upper right')

##График зависимости функции стоимости от итерации градиентного спуска
plt.figure(2)
plt.plot(iter_number_arr, cost_func_arr)
###Добавление подписей осям
plt.xlabel("Итерация")
plt.ylabel("Значение функции стоимости")
###Добавление более частой сетки
plt.grid(which='major')
plt.minorticks_on()
plt.grid(which='minor', linestyle=':')
plt.tight_layout()
##График зависимости значений коэффициентов гипотезы от итерации градиентног спуска
plt.figure(3)
plt.plot(iter_number_arr, TH[0], c="r", label=r"$\theta_0$")
plt.plot(iter_number_arr, TH[1], c="g", label=r"$\theta_1$")
plt.plot(iter_number_arr, TH[2], c="b", label=r"$\theta_2$")
###Добавление подписей осям
plt.xlabel("Итерация")
plt.ylabel("Значения коэффициентов гипотезы")
###Добавление более частой сетки
plt.grid(which='major')
plt.minorticks_on()
plt.grid(which='minor', linestyle=':')
plt.tight_layout()
###Добавление легенды
plt.legend(loc='upper left')
plt.show()
Соседние файлы в папке лабы