Линейная регрессия с нуля в г - PullRequest
0 голосов
/ 21 сентября 2018

Я пытаюсь написать базовый код простой линейной регрессии с методом градиентного спуска.вот мой код.

linear = function(x,y,lr)
{
theta0 = 0

theta1 = 0

m=length(x)

hypo = theta0 +theta1*x

costt = cost(hypo , y)
prev_cost = 1000000

while (prev_cost > cost)
{

prev_cost = cost

theta0 = theta0 - (lr/m)*(hypo - y)

theta1 = theta1 - (lr/m)*(hypo - y)*x

hypo = theta0 + theta1*x

New_cost = cost(hypo , y)

if(New_cost < cost)
{
cost = New_cost
}
}
theta = c(theta0 , theta1)
return( theta )
}  

cost = function(hypo , y)
{
interm = (hypo - y)^2

interm1 = sum(interm)

interm2 = interm1/(2 * m)

return(interm2)  
}

, но когда я проверяю его с данными, он генерирует предупреждающее сообщение.

There were 50 or more warnings (use warnings() to see the first 50)

и прекращает работу.что не так в коде?когда я использую предупреждения, я получаю

Warning messages:
1: In while (prev_cost > cost) { ... :
the condition has length > 1 and only the first element will be used 

lr = 0,01, что является скоростью обучения.и это снимок данных х и у enter image description here

1 Ответ

0 голосов
/ 21 сентября 2018

Это работает для меня.Он производит вектор, который в два раза длиннее length(x) - это то, что вы ищете?

linear = function(x,y,lr)
{
    theta0 = 0

    theta1 = 0

    m=length(x)

    hypo = theta0 +theta1*x

    costt = cost(hypo , y, m)
    prev_cost = 1000000

    while (prev_cost > costt)
    {

        prev_cost = costt

        theta0 = theta0 - (lr/m)*(hypo - y)

        theta1 = theta1 - (lr/m)*(hypo - y)*x

        hypo = theta0 + theta1*x

        New_cost = cost(hypo , y, m)

        if(New_cost < costt)
        {
            costt = New_cost
        }
    }
    theta = c(theta0 , theta1)
    return( theta )
}  

cost = function(hypo , y, m)
{
    interm = (hypo - y)^2

    interm1 = sum(interm)

    interm2 = interm1/(2 * m)

    return(interm2)  
}

x <- rnorm(80)
y <- rnorm(80)
lr <- 0.01
linear(x, y, lr)
...