1
$\begingroup$

I am learning SVD by following this MIT course

The lecturer is trying to normalize a vector

$${\begin{bmatrix} -3\\ 1\\ \end{bmatrix}}$$

to

$${\begin{bmatrix} \dfrac{-3}{\sqrt{10}}\\ \dfrac{1}{\sqrt{10}}\\ \end{bmatrix}}$$

I tried this with Python NumPy

np.linalg.norm(v1,ord=2,axis=1,keepdims=True)

and got

array([[3.],
       [1.]])

I would like to get something like this

[[-0.9486833 ],
[ 0.31622777]]

is there a way with Python (for instance, NumPy) to do the job? any other 3rd party library is also appreciated.

$\endgroup$
6
$\begingroup$

You have already computed that, but you've not bound the output to a variable, also called name in python. Try the following snippet:

result = np.linalg.norm(v1,ord=2,axis=1,keepdims=True)
print(result)


Based on the edit, I update the answer. As you may find answers to your question, a typical way to find what you need is something like the following function:

def normalize(v):
    norm = np.linalg.norm(v)
    if norm == 0: 
       return v
    return v / norm

Equivalently, there is a function called normalize in sklearn.preprocessing which can be employed for your task.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.