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

# Вариант 3: grade
with open("kc_house_data.csv", encoding="cp1251") as f:
    lines = f.readlines()  # Считывание строк в один массив

for i in range(len(lines)):
    lines[i] = lines[i].split(",")  # Разделение строки по разделителям (запятые в данном случае)

lines[0][-1] = lines[0][-1][:-1]  # Стирание "\n" в конце строки с названиями столбцов
lines = np.array(lines)

# Отделение массива с ценами/качеством
req = np.copy(lines[:, 2])
req = np.vstack([req, lines[:, 11]])

# Отделение заголовков от массива в отдельную переменную
headers = req[:, 0]
req = np.delete(req, np.s_[0], axis=1)

# Отделение параметров в отдельные массивы
price = req[0].astype(np.float64)
price.shape = (len(price), 1)
price = price.astype(np.float64)
grade = req[1].astype(np.float64)
gradeor = np.copy(grade)
#  Масштабирование параметров
normgrade = grade.copy()
mini = np.min(grade)
maxi = np.max(grade)
for i in range(len(grade)):
    grade[i] = (grade[i] - mini) / (maxi - mini)
# Функция для создания массива независимых данных
pw = 4
grade = np.vstack([grade, np.power(grade, 2)])
for i in range(3, pw + 1):
    grade = np.vstack([grade, np.power(grade[0], i)])
o = np.ones(len(grade[0]), dtype=np.float64)
grade = np.vstack([o, grade])
grade = np.transpose(grade)

# Задаём первичный набор коэф-ов
th = [random.random() for _ in range(5)]
th = np.asarray(th, dtype=np.float64)


# Функции для оптимизации
def h(theta):  # Гипотеза
    theta.shape = (5, 1)
    hypo = grade @ theta
    theta.shape = (5,)
    return hypo


def J(theta):  # Подсчёт функции стоимости в матричном виде
    summ = np.sum((h(theta) - price) ** 2) / 2 / len(grade)
    return summ


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


'''print("Лаба №19")
print(f"Размер диффура: {dJ(th).shape}")
print(f"Размер theta: {th.shape}")
print(f"Размер гипотезы: {h(th).shape}")
print(f"Theta: \n{th}")
print(f"гипотеза: \n{h(th)}")
print(f"диффур: \n {dJ(th)}")
print(f"Стоимость {J(th)}")
print(f"Тип данных:\n"
      f"Theta \n {type(th[0])} \n"
      f"Differ \n {type(dJ(th)[0])}")'''

c = count()
x_line = []
J_mass = []
theta_mass = []


def Callback(theta):
    x_line.append(next(c))
    J_mass.append(J(theta))
    theta_mass.append(theta)


res = minimize(J, th, method='BFGS', jac=dJ, tol=10 ** -3, callback=Callback)
print(f"Done: {res.success}")

# Графики
plt.figure(1)
plt.plot(x_line, J_mass)

plt.figure(2)
plt.plot(x_line, J_mass)
theta_mass = np.asarray(theta_mass)
plt.figure(1)
plt.plot(x_line, theta_mass[:,0], label=r"График $\theta_{0}$")
plt.plot(x_line, theta_mass[:,1], label=r"График $\theta_{1}$")
plt.plot(x_line, theta_mass[:,2], label=r"График ${\theta_2}$")
plt.plot(x_line, theta_mass[:,3], label=r"График ${\theta_3}$")
plt.plot(x_line, theta_mass[:,4], label=r"График ${\theta_4}$")
plt.legend()
Соседние файлы в папке лабы