Мне пришлось реализовать градиентный спуск, чтобы изучить B0 и B1 для прогнозирования линейного полиномиального уравнения, программа работает как положено, но график показывает, что ошибка обучения и ошибка тестирования модели очень похожи.Вот следующая программа:
import random
# Importing the numerical Python library
import numpy as np
# Importing matplotlib for plotting the graph
import matplotlib.pyplot as plt
# Function to generate a dataset based on the input x
def datasetGenerator(x: int) -> int:
return ((2 * x) - 3) + np.random.normal(0, 5)
# mean squared error calculation for comparing the actual y with the prediction
def meanSquaredError(y: float, y_pred: float) -> float:
# summation of squares of all the y with y predictions divided by the length of y using the np.mean method
# return np.mean((y - y_pred) ** 2)
return np.mean((y - y_pred) ** 2)
def gradientDescent(
X: list[float],
Y: list[float],
Y_pred: list[float],
B0: float,
B1: float,
learningRate: float,
):
# doe E by doe B0
B0 -= learningRate * np.mean(-2 * (Y - Y_pred))
# doe E by doe B1
B1 -= learningRate * np.mean(-2 * (Y - Y_pred) * (X))
return B0, B1
def betaCalculation(X: list[float], Y: list[float], n: int) -> int:
# numpy array of X power 1 to 5
Xtrans = [np.power(X, i) for i in range(n + 1)]
# actual X values in form of X tranpose's transpose
Xnew = np.transpose(Xtrans)
# dot product of X transpose with X
XTX = np.matmul(Xtrans, Xnew)
# inverse of dot product of X Transpose with X
XTXm1 = np.linalg.inv(XTX)
# dot product of inverse of dot product of X transpose and X with X tranpose
XTXinvintoXT = np.matmul(XTXm1, Xtrans)
# Dot product of dot product of inverse of dot product of X transpose and X with X tranpose with Y
Beta = np.matmul(XTXinvintoXT, Y)
# array of beta elements
return Beta
def optimalFit(
B0: float,
B1: float,
X_train: list[float],
Y_train: list[float],
X_test: list[float],
Y_test: list[float],
learningRate,
) -> tuple[list[list[float]], list[float], list[int]]:
flag = True
Ynew = Y_train
epsTrainArr = []
epsTestArr = []
epochsArr = []
B = []
epochs = 0
while flag:
# prediction of the model for previous B0 and B1
Y_pred_train = B0 + B1 * X_train
Y_pred_test = B0 + B1 * X_test
# checking if the code converged or not
flag = False if meanSquaredError(Ynew, Y_pred_train)
Подробнее здесь: [url]https://stackoverflow.com/questions/78480089/the-training-error-and-testing-error-is-very-similiar-for-linear-regression-mode[/url]
Мне пришлось реализовать градиентный спуск, чтобы изучить B0 и B1 для прогнозирования линейного полиномиального уравнения, программа работает как положено, но график показывает, что ошибка обучения и ошибка тестирования модели очень похожи.Вот следующая программа: [code]import random
# Importing the numerical Python library import numpy as np
# Importing matplotlib for plotting the graph import matplotlib.pyplot as plt
# Function to generate a dataset based on the input x def datasetGenerator(x: int) -> int: return ((2 * x) - 3) + np.random.normal(0, 5)
# mean squared error calculation for comparing the actual y with the prediction def meanSquaredError(y: float, y_pred: float) -> float: # summation of squares of all the y with y predictions divided by the length of y using the np.mean method # return np.mean((y - y_pred) ** 2) return np.mean((y - y_pred) ** 2)
def gradientDescent( X: list[float], Y: list[float], Y_pred: list[float], B0: float, B1: float, learningRate: float, ): # doe E by doe B0 B0 -= learningRate * np.mean(-2 * (Y - Y_pred)) # doe E by doe B1 B1 -= learningRate * np.mean(-2 * (Y - Y_pred) * (X)) return B0, B1
def betaCalculation(X: list[float], Y: list[float], n: int) -> int: # numpy array of X power 1 to 5 Xtrans = [np.power(X, i) for i in range(n + 1)]
# actual X values in form of X tranpose's transpose Xnew = np.transpose(Xtrans)
# dot product of X transpose with X XTX = np.matmul(Xtrans, Xnew)
# inverse of dot product of X Transpose with X XTXm1 = np.linalg.inv(XTX)
# dot product of inverse of dot product of X transpose and X with X tranpose XTXinvintoXT = np.matmul(XTXm1, Xtrans)
# Dot product of dot product of inverse of dot product of X transpose and X with X tranpose with Y Beta = np.matmul(XTXinvintoXT, Y)
Мне пришлось реализовать градиентный спуск, чтобы изучить B0 и B1 для прогнозирования линейного полиномиального уравнения, программа работает как положено, но график показывает, что ошибка обучения и ошибка тестирования модели очень похожи.Вот...
Я пишу статью, сравнивающую эффективность обычного метода наименьших квадратов (OLS) и обычного градиентного спуска (CGD) для линейной регрессии. Хотя моя реализация OLS с использованием SciPy соответствует ожидаемым результатам (например,...
Я пишу статью, сравнивающую эффективность обычного метода наименьших квадратов (OLS) и обычного градиентного спуска (CGD) для линейной регрессии. Хотя моя реализация OLS с использованием SciPy соответствует ожидаемым результатам (например,...
Итак, я сделал многократную регрессионную модель и попробовал обучение на ней. Код для этого ниже. При запуске кода после нескольких начальных итераций стоимость стоимости застряла на уровне 5818179,55 и не уменьшается. Я также сделал нормализацию Z...
Я узнаю об алгоритмах машинного обучения, внедряя их с нуля. Начиная с оснований, я работаю над линейной регрессией. Тем не менее, я сталкиваюсь с проблемами с производительностью модели. Учитывая простоту набора данных, я ожидал, что модель будет...