0

While updating theta(weights) in linear regression, it seems to be increasing the cost error, rather than reducing it.

While using numpy, I attempted to update theta on every iteration, by setting a predefined array, values from the theta update and setting theta to the array on every iteration.

theta = [[0],[0]]
theta = np.array(theta)
temp = np.array([[0],[0]])
m = len(Y)
    for i in range(iteration):

    def hypothesis (theta, X, iteration):
        ''' Calculates the hypothesis by multiplying the transpose of theta with the features of X in iteration'''
        output = np.transpose(theta).dot(np.transpose(X[iteration]))
        return int(output)
    def cost_function():
        '''Calculates cost function to plot (this is to check if the cost function is converging)'''
        total = 0
        for i in range(m):
            total = pow((hypothesis(theta, X, i) - Y[i]),2) + total
        return total/(2*m)

    def cost_function_derivative(thetapos):
        '''Calculates the derivative of the cost function to determine which direction to go'''
        cost = 0
        for a in range(m):
            cost += ((hypothesis(theta, X, a) - int(Y[a])) * int(X[a, thetapos]))
        return (cost)
    alpher = alpha*(1/m)
    for j in range(len(theta)):
        temp[j, 0] = theta[j, 0] - float(alpher)*float(cost_function_derivative(j))
    print (cost_function())
    theta = temp
return hypothesis(theta, X, 5), theta

I was expecting it to output 13, with a theta of [1,2] but alas, my poor code, gave me 0, [0,0]

Smart
  • 1
  • 2
  • Did you write tests for each function? – Him Nov 04 '19 at 03:31
  • You might want to use a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) for that or look at [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Nov 04 '19 at 03:34
  • What is the value of alpha? – Sanil Khurana Nov 04 '19 at 03:42
  • Alpha is 0.001. I ran tests for each function and they gave me the correct result. I believe the issue is in the update rule – Smart Nov 04 '19 at 19:57

0 Answers0