PROBLEM: I was wondering if it is possible to replace this for loop with a list comprehension. Trying to learn idiomatic Python.
STATEMENT:
import numpy as np
X = np.array([[66, 5, 15, 2, 500],
[21, 3, 50, 1, 100],
[120, 15, 5, 2, 1200]])
y = np.array([250000, 60000, 525000])
c = np.array([[3000, 200 , -50, 5000, 100],
[2000, -250, -100, 150, 250],
[3000, -100, -150, 0, 150]])
def find_best(X, y, c):
smallest_error = np.Inf
best_index = -1
idx = 0
sq_error_list = []
for coeff in c:
sq_error = sum((y - (X @ c[idx]))**2)
sq_error_list.append(sq_error)
idx += 1
best_index = sq_error_list.index(min(sq_error_list))
print("the best set is set %d" % best_index)
find_best(X, y, c)
You can solve it with this
np.argmin(np.sum((y[:,None]-X @ c.T)**2,axis=0))