简体   繁体   中英

Replacing for loop with list comprehension

PROBLEM: I was wondering if it is possible to replace this for loop with a list comprehension. Trying to learn idiomatic Python.

STATEMENT:

  1. Take row #0 of X and c
  2. Multiply corresponding elements (you get 5 numbers for 5 columns)
  3. Sum these 5 numbers
  4. Subtract it from y[0]
  5. square it for the final result
  6. Repeat for all rows of X , c and columns of y
  7. Find the index of c with the smallest result in step 5
    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)

你可以用这个解决它

np.argmin(np.sum((y[:,None]-X @ c.T)**2,axis=0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM