so_many_questions
so_many_questions

Reputation: 31

Taking the norm without for loop

Is it possible to take the norm of different instances without looping in a for loop? ex.

Given a numpy array of shape (10,2048) -> 10 instances of 2048 features, I want to take the norm of each instance minus the average of the instances, then take the norm of each instance, and sum them up. Here is the for loop equivalent, with x being data instead of 0's

x = np.zeros((10,2048))
sum = 0
for i in range(10):
    sum += np.norm(x[i] - np.mean(x))

Upvotes: 0

Views: 117

Answers (1)

GLaw1300
GLaw1300

Reputation: 205

sum(np.linalg.norm(x, axis=1) - np.mean(x))

An explanation: axis=1 will execute .norm over each row and return an array of shape (10,). For more information on axes, check out this link.

Upvotes: 1

Related Questions