'Why didn't theta change after iterations? I debugged and didn't get any error

import numpy as np

X = np.matrix([[1,6.1101],[1,5.5277]])
y = np.matrix([17.592,9.1302])
theta = np.matrix(np.array([0, 0]))

def gradientDescent(X, y, theta, alpha, iters):
    count = theta.ravel().shape[1]
    for i in range(iters):
        predict = X * theta.T
        for j in range(count):
            theta[0, j] = theta[0, j] - alpha * np.sum(np.multiply(predict - y, X[:, j])) / len(X)
    return theta

# def gradientDescent(X, y, theta, alpha, iters):
#     temp_theta = np.matrix(np.zeros(theta.shape))
#     count = theta.ravel().shape[1]
#     for i in range(iters):
#         predict = X * theta.T
#         for j in range(count):
#             temp_theta[0, j] = theta[0, j] - alpha * np.sum(np.multiply(predict - y, X[:, j])) / len(X)
#         theta = temp_theta
#     return theta


alpha = 0.01
iters = 1000

g= gradientDescent(X, y, theta, alpha, iters)
print(g)

The right function is annotated. Why do I have to add a temporary variable? The value of theta in my function does not change after any iterations.



Solution 1:[1]

You need to specify a type for theta.

theta = np.matrix(np.array([0, 0]), dtype=float)

In the end, your script gives you [[0.99642971 2.11975865]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 maevgor