Ошибка обучения и ошибка тестирования очень похожи для модели линейной регрессии при использовании градиентного спуска.Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Ошибка обучения и ошибка тестирования очень похожи для модели линейной регрессии при использовании градиентного спуска.

Сообщение Anonymous »

Мне пришлось реализовать градиентный спуск, чтобы изучить 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]
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»