如何将 NumPy 数组归一化为单位向量? [英] How to normalize a NumPy array to a unit vector?

查看:35
本文介绍了如何将 NumPy 数组归一化为单位向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 NumPy 数组转换为单位向量.更具体地说,我正在寻找此规范化函数的等效版本:

I would like to convert a NumPy array to a unit vector. More specifically, I am looking for an equivalent version of this normalisation function:

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

该函数处理向量v的范数为0的情况.

This function handles the situation where vector v has the norm value of 0.

sklearnnumpy 中是否提供了类似的功能?

Is there any similar functions provided in sklearn or numpy?

推荐答案

如果你使用 scikit-learn 你可以使用 sklearn.preprocessing.normalize:

If you're using scikit-learn you can use sklearn.preprocessing.normalize:

import numpy as np
from sklearn.preprocessing import normalize

x = np.random.rand(1000)*10
norm1 = x / np.linalg.norm(x)
norm2 = normalize(x[:,np.newaxis], axis=0).ravel()
print np.all(norm1 == norm2)
# True

这篇关于如何将 NumPy 数组归一化为单位向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆