I am trying to write a basic code of simple linear regression with gradient descent method. here is my code.
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)
}
but when I test it with data it generates a warning message.
There were 50 or more warnings (use warnings() to see the first 50)
and stop terminating. what is wrong in the code? when I used warnings I get
Warning messages:
1: In while (prev_cost > cost) { ... :
the condition has length > 1 and only the first element will be used
lr = 0.01 which is learning rate.
and this is the snap of data x and y